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: '未开始', 1: '进行中', 2: '已结束', 3: '手动停止' }; 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(e) { console.log('=== 表单提交验证开始 ==='); // 验证是否选择了商品 var goodsIds = $('#goods-ids').val(); if (!goodsIds || goodsIds.trim() === '') { Layer.alert('请先选择参与活动的商品', {icon: 2}); e.preventDefault(); return false; } // 更新商品信息 var goodsInfo = updateGoodsInfo(); // 验证商品信息 if (!goodsInfo || goodsInfo.length === 0) { Layer.alert('商品信息不能为空', {icon: 2}); e.preventDefault(); return false; } // 验证每个商品的折扣设置 var hasError = false; var errorMsg = ''; $.each(goodsInfo, function(index, item) { if (item.spec_type == 0) { // 单规格商品验证 if (!item.discount || !item.discount_price || item.discount_stocks === undefined) { hasError = true; errorMsg = '商品"' + item.title + '"的折扣信息不完整'; return false; } } else if (item.spec_type == 1) { // 多规格商品验证 if (!item.spec || item.spec.length === 0) { hasError = true; errorMsg = '商品"' + item.title + '"请设置规格折扣'; return false; } } }); if (hasError) { Layer.alert(errorMsg, {icon: 2}); e.preventDefault(); return false; } console.log('=== 表单验证通过,准备提交 ==='); console.log('提交的商品ID:', $('#goods-ids').val()); 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) { // 使用共享的商品渲染方法 Controller.renderSelectedGoods(data, false); } } }); }); }, edit: function () { Controller.api.bindevent(); // 表单提交前处理 $('#edit-form').on('submit', function(e) { console.log('=== 编辑表单提交验证开始 ==='); // 验证是否选择了商品 var goodsIds = $('#goods-ids').val(); if (!goodsIds || goodsIds.trim() === '') { Layer.alert('请先选择参与活动的商品', {icon: 2}); e.preventDefault(); return false; } // 更新商品信息 var goodsInfo = updateGoodsInfo(); // 验证商品信息 if (!goodsInfo || goodsInfo.length === 0) { Layer.alert('商品信息不能为空', {icon: 2}); e.preventDefault(); return false; } // 验证每个商品的折扣设置 var hasError = false; var errorMsg = ''; $.each(goodsInfo, function(index, item) { if (item.spec_type == 0) { // 单规格商品验证 if (!item.discount || !item.discount_price || item.discount_stocks === undefined) { hasError = true; errorMsg = '商品"' + item.title + '"的折扣信息不完整'; return false; } } else if (item.spec_type == 1) { // 多规格商品验证 if (!item.spec || item.spec.length === 0) { hasError = true; errorMsg = '商品"' + item.title + '"请设置规格折扣'; return false; } } }); if (hasError) { Layer.alert(errorMsg, {icon: 2}); e.preventDefault(); return false; } console.log('=== 编辑表单验证通过,准备提交 ==='); console.log('提交的商品ID:', $('#goods-ids').val()); console.log('提交的商品信息:', $('#goods-info').val()); return true; }); // 初始化已选择的商品 var goodsIds = $('#goods-ids').val(); var goodsInfo = $('#goods-info').val() ? JSON.parse($('#goods-info').val()) : []; // 从goods_info构建折扣数据映射 var discountData = {}; if (goodsInfo && goodsInfo.length > 0) { $.each(goodsInfo, function(index, item) { if (item.goods_id) { discountData[item.goods_id] = { id: item.goods_id, sku_id: item.sku_id || 0, discount: item.discount || 9, discount_price: item.discount_price || '', stocks: item.discount_stocks || item.stock || 0 }; // 处理多规格商品 if (item.spec && item.spec.length > 0) { var specs = {}; var summary = { participate_count: 0, avg_discount: 0, total_stocks: 0 }; var totalDiscount = 0; $.each(item.spec, function(specIndex, spec) { specs[spec.sku_id] = { id: spec.sku_id, participate: true, discount: spec.discount, discount_price: spec.discount_price, stocks: spec.discount_stocks }; summary.participate_count++; totalDiscount += parseFloat(spec.discount); summary.total_stocks += parseInt(spec.discount_stocks); }); summary.avg_discount = summary.participate_count > 0 ? (totalDiscount / summary.participate_count).toFixed(1) : '0'; discountData[item.goods_id].specs = specs; discountData[item.goods_id].summary = summary; } } }); } console.log('编辑页面初始化:', { goodsIds: goodsIds, goodsInfo: goodsInfo, discountData: discountData }); // 设置discount-data隐藏字段以便共享方法使用 if (!$('#discount-data').length) { $('#goods-info').after(''); } $('#discount-data').val(JSON.stringify(discountData)); if(goodsIds) { console.log('开始加载商品数据,商品IDs:', goodsIds); // 检查是否有预设的goodsData(从服务器端传递) var goodsData = Controller.api.parseConfigJson('goodsData', []); if (goodsData && goodsData.length > 0) { console.log('使用服务器端预设的商品数据,数量:', goodsData.length); // 处理服务器端返回的活动折扣数据 $.each(goodsData, function(index, goods) { // 处理SKU中的活动折扣数据 if (goods.skus && goods.skus.length > 0) { $.each(goods.skus, function(skuIndex, sku) { // 如果SKU有活动折扣数据,构造discount_info if (sku.activity_discount !== undefined) { if (!goods.discount_info) { goods.discount_info = { goods_id: goods.id, spec_type: goods.spec_type }; } if (goods.spec_type == 0) { // 单规格商品 goods.discount_info.sku_id = sku.id; goods.discount_info.discount = sku.activity_discount; goods.discount_info.discount_price = sku.activity_discount_price; goods.discount_info.discount_stocks = sku.activity_stocks; } else if (goods.spec_type == 1) { // 多规格商品 if (!goods.discount_info.spec) { goods.discount_info.spec = []; } goods.discount_info.spec.push({ sku_id: sku.id, discount: sku.activity_discount, discount_price: sku.activity_discount_price, discount_stocks: sku.activity_stocks }); } } }); } // 处理多规格商品的已选择规格数据 if (goods.spec_type == 1 && goods.selected_discount_data) { console.log('商品', goods.id, '已选择的规格折扣数据:', goods.selected_discount_data); // 如果没有discount_info,从selected_discount_data构建 if (!goods.discount_info) { goods.discount_info = { goods_id: goods.id, spec_type: goods.spec_type, spec: goods.selected_discount_data.spec }; } } }); console.log('处理后的商品数据(包含活动折扣信息):', goodsData); // 使用共享的商品渲染方法,传入编辑模式标识 Controller.renderSelectedGoods(goodsData, true); } else { // 如果没有预设数据,则通过AJAX加载 console.log('没有预设数据,通过AJAX加载商品数据'); $.ajax({ url: Fast.api.fixurl('shop/goods/get_goods_by_ids'), type: 'POST', dataType: 'json', data: {ids: goodsIds}, headers: { 'X-Requested-With': 'XMLHttpRequest' }, success: function(ret, textStatus, jqXHR) { console.log('AJAX商品数据加载结果:', ret); // 根据实际返回的数据结构来处理 var goodsData = []; // 情况1: 标准FastAdmin格式,数据在ret.data中 if (ret && ret.code === 1 && ret.data && Array.isArray(ret.data)) { goodsData = ret.data; console.log('使用标准格式数据,数量:', goodsData.length); } // 情况2: 直接返回商品数组 else if (Array.isArray(ret)) { goodsData = ret; console.log('使用直接数组数据,数量:', goodsData.length); } // 情况3: 如果ret.code不等于1,说明有错误 else if (ret && ret.code !== undefined && ret.code !== 1) { console.error('接口返回错误:', ret.msg || '未知错误'); Layer.msg(ret.msg || '加载商品数据失败', {icon: 2}); return; } if(goodsData && goodsData.length > 0) { console.log('AJAX返回商品数据成功,商品数量:', goodsData.length); // 如果有goods_info数据,则合并折扣信息 if (goodsInfo && goodsInfo.length > 0) { console.log('合并goods_info中的折扣数据'); // 将goods_info中的折扣数据合并到接口返回的商品数据中 $.each(goodsData, function(index, goods) { var matchedInfo = null; $.each(goodsInfo, function(infoIndex, info) { if (info.goods_id == goods.id) { matchedInfo = info; return false; // 跳出循环 } }); if (matchedInfo) { // 合并折扣信息到商品数据 goods.discount_info = matchedInfo; console.log('商品', goods.id, '合并折扣信息:', matchedInfo); } }); } // 使用共享的商品渲染方法,传入编辑模式标识 Controller.renderSelectedGoods(goodsData, true); } else { console.warn('没有获取到商品数据或数据为空'); } }, error: function(jqXHR, textStatus, errorThrown) { console.error('加载商品数据失败:', { status: jqXHR.status, statusText: jqXHR.statusText, textStatus: textStatus, errorThrown: errorThrown }); Layer.msg('加载商品数据失败', {icon: 2}); } }); } } else { console.log('没有商品IDs,跳过商品数据加载'); } // 绑定选择商品按钮事件 - 使用共享方法 $('#select-goods').off('click').on('click', function() { Fast.api.open('shop/goods/select', '选择商品', { area: ['95%', '90%'], callback: function(data) { if (data && data.length > 0) { Controller.renderSelectedGoods(data, true); } } }); }); }, // 规格折扣设置页面 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); }); }, // 渲染已选择的商品表格 - 共享方法 renderSelectedGoods: function(data, isEdit) { var defaultDiscount = 9; var existingDiscountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {}; // 如果是编辑模式且有现有数据,合并数据 if (isEdit && Object.keys(existingDiscountData).length > 0) { console.log('编辑模式,使用现有折扣数据:', existingDiscountData); } console.log('renderSelectedGoods调用:', { dataLength: data ? data.length : 0, isEdit: isEdit, existingDataCount: Object.keys(existingDiscountData).length }); // 收集商品ID var goodsIds = []; $.each(data, function(index, item) { goodsIds.push(item.id); }); // 使用模板渲染表格 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) { 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 '
分类:' + (row.category ? row.category.name : '') + ' | 规格:' + (row.spec_type == 0 ? '单规格' : '多规格') + '
' + '