1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294 |
- define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {
- // 代码更新说明:
- // 1. 添加了单规格商品的"折扣库存"列,多规格商品使用按钮方式设置
- // 2. 添加了折扣库存输入处理事件,并确保数据被正确保存
- // 3. 更新了updateDiscountData函数,确保折扣库存数据被正确提交
-
- var Controller = {
- index: function () {
- // 初始化表格参数配置
- Table.api.init({
- extend: {
- index_url: 'marketing/discount/index' + location.search,
- add_url: 'marketing/discount/add',
- edit_url: 'marketing/discount/edit',
- del_url: 'marketing/discount/del',
- multi_url: 'marketing/discount/multi',
- import_url: 'marketing/discount/import',
- table: 'shop_activity',
- }
- });
- var table = $("#table");
- // 初始化表格
- table.bootstrapTable({
- url: $.fn.bootstrapTable.defaults.extend.index_url,
- pk: 'id',
- sortName: 'id',
- fixedColumns: true,
- fixedRightNumber: 1,
- columns: [
- [
- {checkbox: true},
- {field: 'id', title: __('Id'), visible: false},
- {
- field: 'name',
- title: __('活动名称'),
- operate: 'LIKE',
- align: 'left',
- cellStyle: {css: {'max-width': '180px', 'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap'}}
- },
- {
- field: 'image',
- title: __('活动主图'),
- operate: false,
- events: Table.api.events.image,
- formatter: Table.api.formatter.image,
- width: 80
- },
- {
- field: 'type',
- title: __('活动类型'),
- searchList: {"discount": "折扣活动"},
- formatter: Table.api.formatter.normal,
- width: 80
- },
- {
- field: 'goods_count',
- title: __('商品数量'),
- width: 80,
- align: 'center'
- },
- {
- field: 'start_time',
- title: __('开始时间'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime,
- width: 150
- },
- {
- field: 'end_time',
- title: __('结束时间'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime,
- width: 150
- },
- {
- field: 'activity_status',
- title: __('活动状态'),
- searchList: {
- 0: '未开始',
- 1: '进行中',
- 2: '已结束',
- 3: '手动停止'
- },
- formatter: function(value, row, index) {
- var statusMap = {
- 0: '<span class="label label-default">未开始</span>',
- 1: '<span class="label label-success">进行中</span>',
- 2: '<span class="label label-warning">已结束</span>',
- 3: '<span class="label label-danger">手动停止</span>'
- };
- return statusMap[value] || value;
- },
- width: 80,
- align: 'center'
- },
- {
- field: 'order_count',
- title: __('订单数'),
- width: 80,
- align: 'center'
- },
- {
- field: 'order_amount',
- title: __('成交金额'),
- width: 100,
- align: 'right',
- formatter: function(value, row, index) {
- return '¥' + value;
- }
- },
- {
- field: 'discount_amount',
- title: __('优惠金额'),
- width: 100,
- align: 'right',
- formatter: function(value, row, index) {
- return '¥' + value;
- }
- },
- {
- field: 'sale_quantity',
- title: __('销售数量'),
- width: 80,
- align: 'center'
- },
- {
- field: 'customer_count',
- title: __('成交人数'),
- width: 80,
- align: 'center'
- },
- {
- field: 'createtime',
- title: __('创建时间'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime,
- visible: false
- },
- {
- field: 'updatetime',
- title: __('更新时间'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime,
- visible: false
- },
- {
- field: 'operate',
- title: __('操作'),
- table: table,
- events: Table.api.events.operate,
- formatter: Table.api.formatter.operate,
- buttons: [
- {
- name: 'stop',
- text: __('停止活动'),
- icon: 'fa fa-stop',
- classname: 'btn btn-xs btn-warning btn-ajax',
- url: 'marketing/discount/stopActivity',
- confirm: '确认要停止此活动吗?停止后将无法恢复',
- visible: function(row) {
- return row.activity_status == 1; // 只有进行中的活动才显示停止按钮
- },
- success: function(data, ret) {
- Layer.msg(ret.msg);
- table.bootstrapTable('refresh');
- return false;
- },
- error: function(data, ret) {
- Layer.alert(ret.msg);
- return false;
- }
- }
- ]
- }
- ]
- ]
- });
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- recyclebin: function () {
- // 初始化表格参数配置
- Table.api.init({
- extend: {
- 'dragsort_url': ''
- }
- });
- var table = $("#table");
- // 初始化表格
- table.bootstrapTable({
- url: 'marketing/discount/recyclebin' + location.search,
- pk: 'id',
- sortName: 'id',
- columns: [
- [
- {checkbox: true},
- {field: 'id', title: __('Id')},
- {field: 'title', title: __('Title'), align: 'left'},
- {
- field: 'deletetime',
- title: __('Deletetime'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime
- },
- {
- field: 'operate',
- width: '140px',
- title: __('Operate'),
- table: table,
- events: Table.api.events.operate,
- buttons: [
- {
- name: 'Restore',
- text: __('Restore'),
- classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
- icon: 'fa fa-rotate-left',
- url: 'marketing/discount/restore',
- refresh: true
- },
- {
- name: 'Destroy',
- text: __('Destroy'),
- classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
- icon: 'fa fa-times',
- url: 'marketing/discount/destroy',
- refresh: true
- }
- ],
- formatter: Table.api.formatter.operate
- }
- ]
- ]
- });
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- add: function () {
- Controller.api.bindevent();
-
- // 表单提交前处理
- $('#add-form').on('submit', function() {
- // 同时更新goods_info字段,包含商品的详细信息
- updateGoodsInfo();
-
- console.log('提交的商品信息:', $('#goods-info').val());
- return true;
- });
-
- // 选择商品功能
- $('#select-goods').on('click', function() {
- Fast.api.open('shop/goods/select', '选择商品', {
- area: ['95%', '90%'],
- callback: function(data) {
- if (data && data.length > 0) {
- var goodsIds = [];
-
- // 收集商品ID
- $.each(data, function(index, item) {
- goodsIds.push(item.id);
- });
-
- // 默认折扣值
- var defaultDiscount = 9;
-
- // 使用模板渲染表格
- var html = Template('goodsTableTpl', {
- list: data,
- discount: defaultDiscount
- });
-
- // 清空容器并显示表格
- $('#selected-goods-container').empty().append(html);
-
- // 初始化分页表格
- $('#selected-goods-table').bootstrapTable({
- data: data,
- pagination: true,
- pageSize: 5,
- pageList: [5, 10, 20],
- sortable: true,
- search: false,
- classes: 'table table-hover table-striped',
- onPostBody: function() {
- // 表格渲染完成后处理行属性
- $('#selected-goods-table tbody tr').each(function(index) {
- // 确保每行有data-id属性
- var rowData = data[index];
- if(rowData && rowData.id) {
- $(this).attr('data-id', rowData.id);
- console.log('设置行data-id属性:', rowData.id);
- }
- });
- },
- columns: [
- {
- field: 'goods',
- title: '商品',
- width: '30%',
- formatter: function(value, row) {
- return '<div class="goods-item">' +
- '<img src="' + Fast.api.cdnurl(row.image) + '" style="width:60px;height:60px;margin-right:10px;" class="pull-left img-thumbnail">' +
- '<div style="margin-left:70px;">' +
- '<h5 style="margin-top:0;font-weight:600;">' + row.title + '</h5>' +
- '<p class="text-muted">分类:' + (row.category ? row.category.name : '') + ' | 规格:' + (row.spec_type == 0 ? '单规格' : '多规格') + '</p>' +
- '</div>' +
- '</div>'
- }
- },
- {
- field: 'price',
- title: '价格',
- width: '10%',
- align: 'center',
- formatter: function(value, row) {
- return '<span class="text-danger">¥' + row.price + '</span>';
- }
- },
- {
- field: 'stocks',
- title: '现库存',
- width: '10%',
- align: 'center'
- },
- {
- field: 'discount_stocks',
- title: '折扣库存',
- width: '20%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 0) { // 只有单规格商品显示输入框
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- console.log('渲染折扣库存输入框:', row.id, row.stocks);
- // 确保折扣库存默认等于现库存
- var stocks = parseInt(row.stocks);
- // 移除max属性,仅通过JS验证限制最大值
- return '<input type="number" class="form-control discount-stocks-input" value="' + stocks + '" min="0" data-id="' + row.id + '" data-max-stocks="' + stocks + '" style="width:100%;">';
- } else {
- return ''; // 多规格商品留空
- }
- }
- },
- {
- field: 'discount',
- title: '折扣',
- width: '15%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 1) {
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- var hasSpec = discountData[row.id] && discountData[row.id].specs;
- var specBtnText = hasSpec ? '规格折扣设置 <span class="label label-success">已设置</span>' : '规格折扣设置';
- var html = '<div class="text-center">' +
- '<a href="javascript:;" class="btn btn-info btn-sm btn-spec-discount" data-id="' + row.id + '">' + specBtnText + '</a>' +
- '<div class="text-muted small" style="margin-top:8px;">请点击设置各规格折扣</div>';
-
- // 如果已设置规格折扣,显示汇总信息
- if (hasSpec && discountData[row.id].summary) {
- var summary = discountData[row.id].summary;
- var infoText = '已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件';
- html += '<div class="spec-discount-info text-muted" style="margin-top:5px;">' + infoText + '</div>';
- }
-
- html += '</div>';
- return html;
- } else {
- return '<div class="input-group">' +
- '<input type="number" class="form-control discount-input" value="' + defaultDiscount + '" min="0.1" max="10" step="0.1" data-price="' + row.price + '" data-id="' + row.id + '">' +
- '<span class="input-group-addon">折</span>' +
- '</div>';
- }
- }
- },
- {
- field: 'discount_price',
- title: '折后价',
- width: '20%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 0) {
- return '<span class="discount-price text-success" id="discount-price-' + row.id + '">¥' + (row.price * defaultDiscount / 10).toFixed(2) + '</span>';
- } else {
- return '';
- }
- }
- },
- {
- field: 'operate',
- title: '操作',
- width: '15%',
- align: 'center',
- formatter: function(value, row) {
- return '<a href="javascript:;" class="btn btn-xs btn-danger remove-goods" data-id="' + row.id + '"><i class="fa fa-trash"></i> 删除</a>';
- },
- events: {
- 'click .remove-goods': function (e, value, row, index) {
- // 从表格中移除该行
- $('#selected-goods-table').bootstrapTable('remove', {
- field: 'id',
- values: [row.id]
- });
-
- // 更新隐藏字段
- var currentIds = $('#goods-ids').val().split(',');
- var newIds = [];
- $.each(currentIds, function(i, val) {
- if (val != row.id && val) {
- newIds.push(val);
- }
- });
- $('#goods-ids').val(newIds.join(','));
-
- // 移除折扣数据
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- if(discountData[row.id]) {
- delete discountData[row.id];
- $('#discount-data').val(JSON.stringify(discountData));
- }
-
- // 如果表格为空,则移除整个表格
- if(newIds.length === 0) {
- $('#selected-goods-container').empty();
- }
- }
- }
- }
- ]
- });
-
- // 更新隐藏字段
- $('#goods-ids').val(goodsIds.join(','));
-
- // 初始化折扣数据
- var discountData = {};
- $.each(data, function(index, item) {
- if (item.spec_type == 0) { // 单规格商品
- // 确保折扣库存默认值为现有库存
- var currentStocks = parseInt(item.stocks) || 0;
-
- // 单规格商品需要获取其默认SKU ID
- var skuId = item.sku_id || 0; // 如果返回数据中有sku_id就使用,否则用0
-
- discountData[item.id] = {
- id: item.id,
- sku_id: skuId, // 添加SKU ID
- discount: defaultDiscount,
- discount_price: (item.price * defaultDiscount / 10).toFixed(2),
- stocks: currentStocks // 默认折扣库存等于商品库存
- };
- console.log('初始化单规格商品:', item.id, 'SKU ID:', skuId, '库存:', currentStocks);
- }
- });
- $('#discount-data').val(JSON.stringify(discountData));
-
- // 同步更新商品详情信息
- updateGoodsInfo();
-
- // 等待表格渲染完成后修复折扣库存输入框
- setTimeout(function() {
- $('.discount-stocks-input').each(function() {
- var $input = $(this);
- var goodsId = $input.data('id');
- var maxStocks = parseInt($input.data('max-stocks')) || 0;
-
- // 从折扣数据中获取正确的库存值
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- var correctStocks = discountData[goodsId] && discountData[goodsId].stocks !== undefined ?
- discountData[goodsId].stocks : maxStocks;
-
- // 直接设置正确的库存值
- $input.val(correctStocks);
- console.log('修复折扣库存输入框值:', goodsId, '设置为:', correctStocks);
- });
- }, 500);
-
- // 绑定折扣库存输入事件
- $(document).on('input', '.discount-stocks-input', function() {
- var stocks = parseInt($(this).val()) || 0;
- var goodsId = $(this).data('id');
- var maxStocks = parseInt($(this).data('max-stocks')) || 0;
-
- console.log('折扣库存输入事件:', goodsId, '输入值:', stocks, '最大值:', maxStocks);
-
- // 限制输入范围,确保不超过现库存
- if(stocks < 0) stocks = 0;
- if(stocks > maxStocks) stocks = maxStocks;
- $(this).val(stocks);
-
- // 更新商品折扣数据
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
-
- if(discountData[goodsId]) {
- discountData[goodsId].stocks = stocks;
- } else {
- // 新建数据时需要包含SKU ID
- discountData[goodsId] = {
- id: goodsId,
- sku_id: 0, // 单规格商品默认SKU ID为0,实际应从商品数据获取
- stocks: stocks
- };
- }
-
- $('#discount-data').val(JSON.stringify(discountData));
- });
-
- // 绑定折扣输入事件
- $(document).on('input', '.discount-input', function() {
- var discount = parseFloat($(this).val()) || 0;
- if(discount < 0.1) discount = 0.1;
- if(discount > 10) discount = 10;
-
- var price = parseFloat($(this).data('price')) || 0;
- var goodsId = $(this).data('id');
- var discountPrice = (price * discount / 10).toFixed(2);
-
- $('#discount-price-' + goodsId).text('¥' + discountPrice);
-
- // 更新商品折扣数据
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
-
- // 保留折扣库存值和SKU ID,如果已存在
- var stocks = discountData[goodsId] && discountData[goodsId].stocks ? discountData[goodsId].stocks : null;
- var skuId = discountData[goodsId] && discountData[goodsId].sku_id ? discountData[goodsId].sku_id : 0;
-
- var goodsDiscount = {
- id: goodsId,
- sku_id: skuId, // 保留SKU ID
- discount: discount,
- discount_price: discountPrice
- };
-
- // 如果已有设置折扣库存,保留该值
- if (stocks !== null) {
- goodsDiscount.stocks = stocks;
- }
-
- // 存储折扣数据
- discountData[goodsId] = goodsDiscount;
- $('#discount-data').val(JSON.stringify(discountData));
-
- // 更新商品详情信息
- updateGoodsInfo();
- });
-
- // 处理规格设置按钮点击事件
- $(document).on('click', '.btn-spec-discount', function() {
- var goodsId = $(this).data('id');
- var $row = $(this).closest('tr');
- var hasDiscountSetting = $row.attr('data-has-discount-setting');
- var specData = '';
-
- console.log('点击规格折扣设置按钮:', goodsId, '当前设置状态:', hasDiscountSetting);
-
- // 如果已经有设置,则传递已有的数据
- if (hasDiscountSetting && $row.attr('data-discount-data')) {
- specData = encodeURIComponent($row.attr('data-discount-data'));
- console.log('已有折扣数据:', $row.attr('data-discount-data'));
- }
-
- Fast.api.open('marketing/discount/spec_discount?goods_id=' + goodsId + '&spec_data=' + specData, '规格折扣设置', {
- area: ['90%', '90%'],
- callback: function(data) {
- if (data && data.goodsId && data.specs) {
- console.log('规格折扣设置返回数据:', data);
-
- // 保存数据到行属性
- $row.attr('data-has-discount-setting', 'true');
- $row.attr('data-discount-data', JSON.stringify(data));
-
- // 调试确认设置成功
- console.log('设置后的data-discount-data属性:', $row.attr('data-discount-data'));
-
- // 更新按钮文字
- $row.find('.btn-spec-discount').html('规格折扣设置 <span class="label label-success">已设置</span>');
-
- // 更新状态和折扣显示
- $row.find('.discount-status').text('已设置');
-
- // 计算平均折扣和参与规格数量
- var totalDiscount = 0;
- var count = 0;
- var totalStocks = 0;
-
- $.each(data.specs, function(id, item) {
- if (item.participate) {
- totalDiscount += parseFloat(item.discount);
- totalStocks += parseInt(item.stocks);
- count++;
- }
- });
-
- var avgDiscount = count > 0 ? (totalDiscount / count).toFixed(1) : '-';
-
- // 添加汇总信息
- var summary = {
- participate_count: count,
- avg_discount: avgDiscount,
- total_stocks: totalStocks
- };
-
- // 更新显示
- var infoText = '已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件';
-
- // 如果已有汇总信息区域则更新,否则创建
- var $infoArea = $row.find('.spec-discount-info');
- if ($infoArea.length > 0) {
- $infoArea.text(infoText);
- } else {
- $row.find('.btn-spec-discount').parent().append('<div class="spec-discount-info text-muted" style="margin-top:5px;">' + infoText + '</div>');
- }
-
- // 将汇总信息添加到数据中
- data.summary = summary;
-
- // 将折扣数据保存到隐藏字段
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- discountData[goodsId] = data;
- $('#discount-data').val(JSON.stringify(discountData));
-
- // 更新商品详情信息
- updateGoodsInfo();
-
- console.log('多规格商品设置后的折扣数据:', $('#discount-data').val());
- }
- }
- });
- });
- }
- }
- });
- });
- },
- edit: function () {
- Controller.api.bindevent();
-
- // 表单提交前处理
- $('#add-form').on('submit', function() {
- // 同时更新goods_info字段,包含商品的详细信息
- updateGoodsInfo();
-
- console.log('提交的商品信息:', $('#goods-info').val());
- return true;
- });
-
- // 初始化已选择的商品
- var goodsIds = $('#goods-ids').val();
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
-
- if(goodsIds) {
- // 加载已选择的商品数据
- Fast.api.ajax({
- url: 'shop/goods/get_goods_by_ids',
- data: {ids: goodsIds}
- }, function(data) {
- if(data && data.length > 0) {
- // 使用模板渲染表格
- var html = Template('goodsTableTpl', {
- list: data
- });
-
- // 清空容器并显示表格
- $('#selected-goods-container').empty().append(html);
-
- // 初始化分页表格
- $('#selected-goods-table').bootstrapTable({
- data: data,
- pagination: true,
- pageSize: 5,
- pageList: [5, 10, 20],
- sortable: true,
- search: false,
- classes: 'table table-hover table-striped',
- columns: [
- {
- field: 'goods',
- title: '商品',
- width: '30%',
- formatter: function(value, row) {
- return '<div class="goods-item">' +
- '<img src="' + Fast.api.cdnurl(row.image) + '" style="width:60px;height:60px;margin-right:10px;" class="pull-left img-thumbnail">' +
- '<div style="margin-left:70px;">' +
- '<h5 style="margin-top:0;font-weight:600;">' + row.title + '</h5>' +
- '<p class="text-muted">分类:' + (row.category ? row.category.name : '') + ' | 规格:' + (row.spec_type == 0 ? '单规格' : '多规格') + '</p>' +
- '</div>' +
- '</div>'
- }
- },
- {
- field: 'price',
- title: '价格',
- width: '10%',
- align: 'center',
- formatter: function(value, row) {
- return '<span class="text-danger">¥' + row.price + '</span>';
- }
- },
- {
- field: 'stocks',
- title: '现库存',
- width: '10%',
- align: 'center'
- },
- {
- field: 'discount_stocks',
- title: '折扣库存',
- width: '10%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 0) { // 只有单规格商品显示输入框
- // 从折扣数据中获取库存值,如果没有则使用商品库存
- var currentStocks = discountData[row.id] && discountData[row.id].stocks !== undefined ?
- discountData[row.id].stocks : parseInt(row.stocks);
- return '<input type="number" class="form-control discount-stocks-input" value="' + currentStocks + '" min="0" data-id="' + row.id + '" data-max-stocks="' + parseInt(row.stocks) + '" style="width:100%;">';
- } else {
- return ''; // 多规格商品留空
- }
- }
- },
- {
- field: 'discount',
- title: '折扣',
- width: '15%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 1) {
- var hasSpec = discountData[row.id] && discountData[row.id].specs;
- var specBtnText = hasSpec ? '规格折扣设置 <span class="label label-success">已设置</span>' : '规格折扣设置';
- var html = '<div class="text-center">' +
- '<a href="javascript:;" class="btn btn-info btn-sm btn-spec-discount" data-id="' + row.id + '">' + specBtnText + '</a>' +
- '<div class="text-muted small" style="margin-top:8px;">请点击设置各规格折扣</div>';
-
- // 如果已设置规格折扣,显示汇总信息
- if (hasSpec && discountData[row.id].summary) {
- var summary = discountData[row.id].summary;
- var infoText = '已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件';
- html += '<div class="spec-discount-info text-muted" style="margin-top:5px;">' + infoText + '</div>';
- }
-
- html += '</div>';
- return html;
- } else {
- var discount = (discountData[row.id] && discountData[row.id].discount) ? discountData[row.id].discount : 9;
- return '<div class="input-group">' +
- '<input type="number" class="form-control discount-input" value="' + discount + '" min="0.1" max="10" step="0.1" data-price="' + row.price + '" data-id="' + row.id + '">' +
- '<span class="input-group-addon">折</span>' +
- '</div>';
- }
- }
- },
- {
- field: 'discount_price',
- title: '折后价',
- width: '20%',
- align: 'center',
- formatter: function(value, row) {
- if(row.spec_type == 0) {
- var discount = (discountData[row.id] && discountData[row.id].discount) ? discountData[row.id].discount : 9;
- var discountPrice = (row.price * discount / 10).toFixed(2);
- return '<span class="discount-price text-success" id="discount-price-' + row.id + '">¥' + discountPrice + '</span>';
- } else {
- return '';
- }
- }
- },
- {
- field: 'operate',
- title: '操作',
- width: '15%',
- align: 'center',
- formatter: function(value, row) {
- return '<a href="javascript:;" class="btn btn-xs btn-danger remove-goods" data-id="' + row.id + '"><i class="fa fa-trash"></i> 删除</a>';
- },
- events: {
- 'click .remove-goods': function (e, value, row, index) {
- // 从表格中移除该行
- $('#selected-goods-table').bootstrapTable('remove', {
- field: 'id',
- values: [row.id]
- });
-
- // 更新隐藏字段
- var currentIds = $('#goods-ids').val().split(',');
- var newIds = [];
- $.each(currentIds, function(i, val) {
- if (val != row.id && val) {
- newIds.push(val);
- }
- });
- $('#goods-ids').val(newIds.join(','));
-
- // 移除折扣数据
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- if(discountData[row.id]) {
- delete discountData[row.id];
- $('#discount-data').val(JSON.stringify(discountData));
- }
-
- // 如果表格为空,则移除整个表格
- if(newIds.length === 0) {
- $('#selected-goods-container').empty();
- }
- }
- }
- }
- ]
- });
- }
- return false;
- });
- }
-
- // 选择商品功能和删除商品功能,与add方法相同
- Controller.add();
- },
-
- // 规格折扣设置页面
- spec_discount: function () {
- // 获取URL参数中的goods_id和spec_data
- var goodsId = Fast.api.query('goods_id');
- var specData = Fast.api.query('spec_data');
-
- // 设置批量折扣默认值,但不自动勾选
- $('#batch-participate').prop('checked', false);
- $('#batch-discount').val(9);
-
- // 更新批量价格信息
- Controller.api.updateBatchPriceInfo();
-
- // 如果有规格数据,则进行回显
- if (specData) {
- try {
- var data = JSON.parse(decodeURIComponent(specData));
- if (data && data.specs) {
- $.each(data.specs, function(id, item) {
- var $row = $('tr[data-id="' + id + '"]');
- if ($row.length > 0) {
- // 设置参与折扣
- if (item.participate) {
- // 勾选并确保输入框可编辑
- $row.find('.participate-checkbox').prop('checked', true);
- $row.find('.sku-stocks').prop('disabled', false);
- $row.find('.sku-discount').prop('disabled', false);
-
- // 设置折扣库存
- if (item.stocks !== undefined) {
- var maxStocks = parseInt($row.data('stocks')) || 0;
- var stocks = parseInt(item.stocks) || 0;
-
- // 确保回显的库存不超过现有库存
- if (stocks > maxStocks) {
- stocks = maxStocks;
- }
-
- $row.find('.sku-stocks').val(stocks);
- }
-
- // 设置折扣
- if (item.discount !== undefined) {
- $row.find('.sku-discount').val(item.discount);
-
- // 更新折后价显示
- var price = parseFloat($row.data('price')) || 0;
- var discount = parseFloat(item.discount) || 0;
- var discountPrice = (price * discount / 10).toFixed(2);
- $row.find('.discount-price').text('¥' + discountPrice);
- }
- } else {
- // 如果之前设置了不参与,则取消勾选
- $row.find('.participate-checkbox').prop('checked', false);
- $row.find('.sku-stocks').prop('disabled', true);
- $row.find('.sku-discount').prop('disabled', true);
- }
- }
- });
-
- // 检查已选规格数量,更新批量选择框状态
- var checkedCount = $('.participate-checkbox:checked').length;
- var totalCount = $('.participate-checkbox').length;
-
- if (checkedCount > 0 && checkedCount === totalCount) {
- // 如果所有规格都已选中,勾选批量选择框
- $('#batch-participate').prop('checked', true);
- } else if (checkedCount > 0) {
- // 部分选中,不勾选批量框但显示提示
- $('#batch-participate').prop('checked', false);
- } else {
- // 没有任何选中
- $('#batch-participate').prop('checked', false);
- }
-
- // 更新批量价格信息
- Controller.api.updateBatchPriceInfo();
- }
- } catch (e) {
- console.error('解析规格数据失败', e);
- }
- }
-
- // 参与折扣复选框事件,但勾选后可以直接编辑
- $('.participate-checkbox').off('change').on('change', function() {
- var checked = $(this).prop('checked');
- var $row = $(this).closest('tr');
-
- // 启用/禁用库存和折扣输入框
- var $stocksInput = $row.find('.sku-stocks');
- var $discountInput = $row.find('.sku-discount');
-
- $stocksInput.prop('disabled', !checked);
- $discountInput.prop('disabled', !checked);
-
- // 如果勾选,设置默认值
- if (checked) {
- // 获取库存默认值
- var stocks = $row.data('stocks') || 0;
- if (!$stocksInput.val()) {
- $stocksInput.val(stocks);
- } else if (parseInt($stocksInput.val()) > stocks) {
- // 如果当前值超过了最大库存,则调整为最大库存
- $stocksInput.val(stocks);
- }
-
- // 设置折扣默认值,如果未设置
- if (!$discountInput.val()) {
- $discountInput.val(9);
- }
-
- // 触发折扣输入框的input事件以更新折扣价格
- $discountInput.trigger('input');
-
- // 聚焦到折扣输入框方便用户直接修改
- setTimeout(function() {
- $discountInput.focus();
- }, 100);
- }
- });
-
- // 批量参与复选框事件
- $('#batch-participate').on('change', function() {
- var checked = $(this).prop('checked');
-
- // 同步所有规格的选中状态
- $('.participate-checkbox').prop('checked', checked).trigger('change');
-
- // 如果勾选了批量参与,则聚焦到批量折扣输入框
- if (checked) {
- setTimeout(function() {
- $('#batch-discount').focus();
- }, 100);
- }
- });
-
- // 批量折扣变化事件
- $('#batch-discount').on('input', function() {
- var discount = parseFloat($(this).val()) || 0;
- if (discount < 0.1) discount = 0.1;
- if (discount > 10) discount = 10;
-
- $(this).val(discount);
-
- // 更新批量价格信息
- Controller.api.updateBatchPriceInfo();
- });
-
- // 初始化批量价格信息
- Controller.api.updateBatchPriceInfo();
-
- // 应用批量设置按钮事件
- $('#apply-batch').on('click', function() {
- var discount = parseFloat($('#batch-discount').val()) || 9;
-
- // 如果没有选中规格,先勾选所有规格
- if ($('.participate-checkbox:checked').length === 0) {
- Layer.msg('请先勾选需要参与折扣的规格');
- return;
- }
-
- // 应用到所有已勾选的行
- $('.participate-checkbox:checked').each(function() {
- var $row = $(this).closest('tr');
- $row.find('.sku-discount').val(discount).trigger('input');
- });
-
- Layer.msg('批量设置折扣已应用');
- });
-
- // 折扣输入事件
- $('.sku-discount').off('input').on('input', function() {
- var discount = parseFloat($(this).val()) || 0;
- if(discount < 0.1) discount = 0.1;
- if(discount > 10) discount = 10;
-
- $(this).val(discount);
-
- var $row = $(this).closest('tr');
- var price = parseFloat($row.data('price')) || 0;
- var discountPrice = (price * discount / 10).toFixed(2);
-
- $row.find('.discount-price').text('¥' + discountPrice);
- });
-
- // 库存输入验证
- $('.sku-stocks').on('input', function() {
- var stocks = parseInt($(this).val()) || 0;
- var $row = $(this).closest('tr');
- var maxStocks = parseInt($row.data('stocks')) || 0;
-
- // 限制库存范围,不能超过现有库存
- if (stocks < 0) stocks = 0;
- if (stocks > maxStocks) stocks = maxStocks;
-
- $(this).val(stocks);
- });
-
- // 确认按钮事件
- $('.btn-confirm').on('click', function() {
- var specs = {};
- var hasParticipate = false;
-
- // 收集所有参与的规格数据
- $('.participate-checkbox:checked').each(function() {
- var $row = $(this).closest('tr');
- var id = $row.data('id');
- var price = parseFloat($row.data('price')) || 0;
- var discount = parseFloat($row.find('.sku-discount').val()) || 9;
- var stocks = parseInt($row.find('.sku-stocks').val()) || 0;
- var discountPrice = (price * discount / 10).toFixed(2);
-
- specs[id] = {
- id: id,
- participate: true,
- discount: discount,
- price: price,
- stocks: stocks,
- discount_price: discountPrice
- };
-
- hasParticipate = true;
-
- console.log('添加参与规格:', id, '折扣:', discount, '库存:', stocks);
- });
-
- // 验证是否有选择参与的规格
- if (!hasParticipate) {
- Layer.alert('请至少选择一个参与折扣的规格', {icon: 2});
- return;
- }
-
- // 计算平均折扣和参与规格数量
- var totalDiscount = 0;
- var count = 0;
- var totalStocks = 0;
-
- $.each(specs, function(id, item) {
- if (item.participate) {
- totalDiscount += parseFloat(item.discount);
- totalStocks += parseInt(item.stocks);
- count++;
- }
- });
-
- var avgDiscount = count > 0 ? (totalDiscount / count).toFixed(1) : '-';
-
- // 添加汇总信息
- var summary = {
- participate_count: count,
- avg_discount: avgDiscount,
- total_stocks: totalStocks
- };
-
- var returnData = {
- goodsId: goodsId,
- specs: specs,
- summary: summary
- };
-
- console.log('多规格确认返回数据:', returnData);
-
- // 返回数据到add.html页面
- Fast.api.close(returnData);
- });
- },
- api: {
- bindevent: function () {
- Form.api.bindevent($("form[role=form]"));
-
- // 处理活动类型选择
- $('select[name="row[type]"]').on('change', function() {
- var type = $(this).val();
-
- // 根据类型显示或隐藏内部类型选择
- if (type == 'discount') {
- // 折扣活动隐藏内部类型选择,默认为0
- $('#inner-type-group').hide();
- $('#c-inner-type').val(0);
-
- // 折扣活动隐藏商品参与方式,强制为指定商品
- $('.goods-join-type-group').hide();
- $('input[name="row[goods_join_type]"][value="2"]').prop('checked', true);
- } else {
- // 其他活动类型显示相关选项
- $('#inner-type-group').show();
- $('.goods-join-type-group').show();
- }
- }).trigger('change'); // 页面加载时立即触发一次
-
- // 活动名称字数限制处理
- var nameInput = $("#c-name");
- var countElement = $("#name-count");
-
- // 初始化显示
- countElement.text(nameInput.val().length + "/20");
-
- // 监听输入事件
- nameInput.on("input propertychange", function() {
- var text = $(this).val();
- var len = text.length;
-
- // 更新显示的字数
- countElement.text(len + "/20");
-
- // 限制最多输入20个字符
- if (len > 20) {
- $(this).val(text.substring(0, 20));
- countElement.text("20/20");
- }
- });
-
- // 限购选项处理
- $('input[name="row[purchase_limit_type]"]').on('change', function() {
- var type = $(this).val();
-
- // 禁用所有输入框
- $('input[name="row[purchase_limit_total]"]').prop('disabled', true);
- $('input[name="row[purchase_limit_daily]"]').prop('disabled', true);
-
- // 根据选择启用对应输入框
- if(type == '1') {
- $('input[name="row[purchase_limit_total]"]').prop('disabled', false).focus();
- } else if(type == '2') {
- $('input[name="row[purchase_limit_daily]"]').prop('disabled', false).focus();
- }
- });
- },
-
- // 更新批量价格信息
- updateBatchPriceInfo: function() {
- var discount = parseFloat($('#batch-discount').val()) || 0;
- var totalPrice = 0;
- var totalCount = 0;
-
- $('tr[data-price]').each(function() {
- var price = parseFloat($(this).data('price')) || 0;
- totalPrice += price;
- totalCount++;
- });
-
- var avgPrice = totalCount > 0 ? totalPrice / totalCount : 0;
- var discountPrice = (avgPrice * discount / 10).toFixed(2);
-
- $('.batch-price-info').text('平均折后价:¥' + discountPrice);
- }
- }
- };
-
- // 更新商品详细信息到goods_info隐藏域
- function updateGoodsInfo() {
- // 获取表格中的所有商品数据
- var goodsInfo = [];
- var table = $('#selected-goods-table').bootstrapTable('getData');
- var discountData = {};
-
- // 处理单规格商品的折扣数据
- $('.discount-input').each(function() {
- var $input = $(this);
- var goodsId = $input.data('id');
- var discount = parseFloat($input.val()) || 0;
- var price = parseFloat($input.data('price')) || 0;
- var discountPrice = (price * discount / 10).toFixed(2);
-
- var $tr = $input.closest('tr');
- var $stocksInput = $tr.find('.discount-stocks-input');
- var stocks = parseInt($stocksInput.val()) || 0;
-
- discountData[goodsId] = {
- id: goodsId,
- discount: discount,
- discount_price: discountPrice,
- stocks: stocks
- };
- });
-
- // 处理多规格商品的折扣数据
- $('#selected-goods-table tbody tr').each(function() {
- var $row = $(this);
- var goodsId = $row.data('id');
- var hasDiscountSetting = $row.attr('data-has-discount-setting');
- var discountDataStr = $row.attr('data-discount-data');
-
- console.log('检查多规格商品:', goodsId, '设置状态:', hasDiscountSetting, '数据:', discountDataStr);
-
- if (goodsId && hasDiscountSetting === 'true' && discountDataStr) {
- try {
- // 如果是多规格商品且已设置规格折扣
- var rowDiscountData = JSON.parse(discountDataStr);
- discountData[goodsId] = rowDiscountData;
- console.log('解析多规格数据成功:', goodsId, rowDiscountData);
- } catch (e) {
- console.error('解析多规格折扣数据失败:', e);
- }
- }
- });
-
- // 调试所有收集的折扣数据
- console.log('所有折扣数据:', discountData);
-
- // 更新折扣数据隐藏域
- $('#discount-data').val(JSON.stringify(discountData));
-
- if(table && table.length > 0) {
- $.each(table, function(index, item) {
- // 基础商品信息
- var goodsData = {
- goods_id: item.id,
- title: item.title,
- stock: item.stocks || 0,
- spec_type: item.spec_type
- };
-
- // 添加折扣信息
- if(discountData[item.id]) {
- if(item.spec_type == 0) {
- // 单规格商品只保留折扣相关字段
- goodsData.sku_id = discountData[item.id].sku_id || 0; // 添加SKU ID
- goodsData.discount = discountData[item.id].discount;
- goodsData.discount_price = discountData[item.id].discount_price;
- goodsData.discount_stocks = discountData[item.id].stocks;
- } else if(item.spec_type == 1) {
- // 多规格商品 - 检查是否有规格折扣设置
- console.log('处理多规格商品:', item.id, discountData[item.id]);
- var spec = [];
-
- // 确保specs存在
- if(discountData[item.id] && discountData[item.id].specs) {
- var specData = discountData[item.id].specs;
-
- // 提取已选中参与折扣的规格
- $.each(specData, function(specId, specItem) {
- console.log('规格项:', specId, specItem);
- if(specItem && specItem.participate) {
- spec.push({
- sku_id: specId,
- discount: specItem.discount,
- discount_price: specItem.discount_price,
- discount_stocks: specItem.stocks
- });
- }
- });
-
- console.log('最终生成的spec数组:', spec);
- } else {
- console.log('没有找到多规格商品的specs数据');
- }
-
- // 即使为空也保存spec数组
- goodsData.spec = spec;
- }
- }
-
- goodsInfo.push(goodsData);
- });
- }
-
- // 调试最终结果
- console.log('最终goods_info:', goodsInfo);
-
- // 更新隐藏域
- $('#goods-info').val(JSON.stringify(goodsInfo));
- return goodsInfo;
- }
- return Controller;
- });
|