12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607 |
- 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(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('<input type="hidden" id="discount-data" value="">');
- }
- $('#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 '<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 currentStocks = existingDiscountData[row.id] && existingDiscountData[row.id].stocks !== undefined ?
- existingDiscountData[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 = false;
- var specBtnText = '规格折扣设置';
- var summaryInfo = '';
-
- // 先检查合并的折扣信息
- if (row.discount_info && row.discount_info.spec && row.discount_info.spec.length > 0) {
- hasSpec = true;
- specBtnText = '规格折扣设置 <span class="label label-success">已设置</span>';
-
- // 计算汇总信息
- var totalDiscount = 0;
- var count = 0;
- var totalStocks = 0;
- $.each(row.discount_info.spec, function(index, spec) {
- totalDiscount += parseFloat(spec.discount || 0);
- totalStocks += parseInt(spec.discount_stocks || 0);
- count++;
- });
- var avgDiscount = count > 0 ? (totalDiscount / count).toFixed(1) : '0';
- summaryInfo = '<div class="spec-discount-info text-muted" style="margin-top:5px;"><i class="fa fa-check-circle text-success"></i> 已设置' + count + '个规格,平均' + avgDiscount + '折,共' + totalStocks + '件</div>';
- }
- // 再检查existingDiscountData
- else if (existingDiscountData[row.id] && existingDiscountData[row.id].specs) {
- hasSpec = true;
- specBtnText = '规格折扣设置 <span class="label label-success">已设置</span>';
-
- if (existingDiscountData[row.id].summary) {
- var summary = existingDiscountData[row.id].summary;
- summaryInfo = '<div class="spec-discount-info text-muted" style="margin-top:5px;"><i class="fa fa-check-circle text-success"></i> 已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件</div>';
- }
- }
-
- var html = '<div class="text-center">' +
- '<a href="javascript:;" class="btn btn-info btn-sm btn-spec-discount" data-id="' + row.id + '">' + specBtnText + '</a>';
-
- // 根据是否已设置显示不同的提示语
- if (hasSpec) {
- html += '<div class="text-muted small" style="margin-top:8px;">点击可重新设置各规格折扣</div>';
- } else {
- html += '<div class="text-muted small" style="margin-top:8px;">请点击设置各规格折扣</div>';
- }
-
- html += summaryInfo + '</div>';
-
- return html;
- } else {
- var discount = (existingDiscountData[row.id] && existingDiscountData[row.id].discount) ? existingDiscountData[row.id].discount : defaultDiscount;
- 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 = (existingDiscountData[row.id] && existingDiscountData[row.id].discount) ? existingDiscountData[row.id].discount : defaultDiscount;
- 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();
- }
-
- updateGoodsInfo();
- }
- }
- }
- ]
- });
-
- // 更新隐藏字段
- $('#goods-ids').val(goodsIds.join(','));
-
- // 初始化折扣数据
- var discountData = existingDiscountData;
- $.each(data, function(index, item) {
- // 检查是否有合并的折扣信息
- var hasDiscountInfo = item.discount_info;
- // 检查是否有服务器端的已选择规格数据
- var hasSelectedData = item.selected_discount_data;
-
- if (item.spec_type == 0) {
- if (hasDiscountInfo) {
- // 使用合并的折扣信息
- discountData[item.id] = {
- id: item.id,
- sku_id: hasDiscountInfo.sku_id || 0,
- discount: hasDiscountInfo.discount || defaultDiscount,
- discount_price: hasDiscountInfo.discount_price || (item.price * defaultDiscount / 10).toFixed(2),
- stocks: hasDiscountInfo.discount_stocks || parseInt(item.stocks) || 0
- };
- console.log('使用已保存的单规格商品折扣信息:', item.id, discountData[item.id]);
- } else if (!discountData[item.id]) {
- // 单规格商品,只有在没有现有数据时才初始化
- var currentStocks = parseInt(item.stocks) || 0;
- var skuId = item.sku_id || 0;
-
- discountData[item.id] = {
- id: item.id,
- sku_id: skuId,
- discount: defaultDiscount,
- discount_price: (item.price * defaultDiscount / 10).toFixed(2),
- stocks: currentStocks
- };
- console.log('初始化单规格商品:', item.id, 'SKU ID:', skuId, '库存:', currentStocks);
- }
- } else if (item.spec_type == 1) {
- // 多规格商品处理
- if (hasSelectedData) {
- // 优先使用服务器端的已选择数据
- var specs = {};
- $.each(hasSelectedData.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
- };
- });
-
- discountData[item.id] = {
- id: item.id,
- specs: specs,
- summary: hasSelectedData.summary
- };
-
- console.log('使用服务器端已选择的多规格商品数据:', item.id, discountData[item.id]);
- } else if (hasDiscountInfo && hasDiscountInfo.spec) {
- // 使用合并的折扣信息
- var specs = {};
- var summary = {
- participate_count: 0,
- avg_discount: 0,
- total_stocks: 0
- };
-
- var totalDiscount = 0;
- $.each(hasDiscountInfo.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.id] = {
- id: item.id,
- specs: specs,
- summary: summary
- };
-
- console.log('使用已保存的多规格商品折扣信息:', item.id, discountData[item.id]);
- }
- }
- });
-
- // 确保discount-data字段存在(兼容性)
- if (!$('#discount-data').length) {
- $('#goods-info').after('<input type="hidden" id="discount-data" value="">');
- }
- $('#discount-data').val(JSON.stringify(discountData));
-
- // 延迟处理事件绑定和数据回显
- setTimeout(function() {
- // 处理多规格商品的数据回显
- $('#selected-goods-table tbody tr').each(function() {
- var $row = $(this);
- var goodsId = $row.data('id');
-
- console.log('检查商品行:', goodsId, '折扣数据:', discountData[goodsId]);
-
- if (goodsId && discountData[goodsId]) {
- // 检查是否是多规格商品且有规格数据
- if (discountData[goodsId].specs || discountData[goodsId].spec) {
- console.log('回显多规格商品数据:', goodsId, discountData[goodsId]);
-
- // 设置多规格商品的数据属性
- $row.attr('data-has-discount-setting', 'true');
- $row.attr('data-discount-data', JSON.stringify(discountData[goodsId]));
-
- // 更新按钮显示为"已设置"状态
- var $btn = $row.find('.btn-spec-discount');
- if ($btn.length > 0) {
- $btn.html('规格折扣设置 <span class="label label-success">已设置</span>');
-
- // 显示汇总信息
- var summary = discountData[goodsId].summary;
- if (summary) {
- var infoText = '<i class="fa fa-check-circle text-success"></i> 已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件';
-
- // 检查是否已有汇总信息区域
- var $infoArea = $row.find('.spec-discount-info');
- if ($infoArea.length > 0) {
- $infoArea.html(infoText);
- } else {
- $btn.parent().append('<div class="spec-discount-info text-muted" style="margin-top:5px;">' + infoText + '</div>');
- }
- } else {
- // 如果没有summary,计算一个
- var specs = discountData[goodsId].specs || discountData[goodsId].spec || [];
- if (Array.isArray(specs) && specs.length > 0) {
- var totalDiscount = 0;
- var totalStocks = 0;
- var count = specs.length;
-
- $.each(specs, function(i, spec) {
- totalDiscount += parseFloat(spec.discount || 0);
- totalStocks += parseInt(spec.discount_stocks || spec.stocks || 0);
- });
-
- var avgDiscount = count > 0 ? (totalDiscount / count).toFixed(1) : '0';
- var infoText = '<i class="fa fa-check-circle text-success"></i> 已设置' + count + '个规格,平均' + avgDiscount + '折,共' + totalStocks + '件';
-
- var $infoArea = $row.find('.spec-discount-info');
- if ($infoArea.length > 0) {
- $infoArea.html(infoText);
- } else {
- $btn.parent().append('<div class="spec-discount-info text-muted" style="margin-top:5px;">' + infoText + '</div>');
- }
- }
- }
- }
- }
- }
- });
-
- // 绑定事件处理器
- Controller.bindGoodsEvents();
-
- // 同步更新商品详情信息
- updateGoodsInfo();
- }, 300);
- },
-
- // 绑定商品相关事件处理器
- bindGoodsEvents: function() {
- // 绑定折扣库存输入事件
- $(document).off('input', '.discount-stocks-input').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 {
- discountData[goodsId] = {
- id: goodsId,
- sku_id: 0,
- stocks: stocks
- };
- }
-
- $('#discount-data').val(JSON.stringify(discountData));
- updateGoodsInfo();
- });
-
- // 绑定折扣输入事件
- $(document).off('input', '.discount-input').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()) : {};
-
- // 保留已有的数据结构
- if (!discountData[goodsId]) {
- discountData[goodsId] = {
- id: goodsId,
- sku_id: 0
- };
- }
-
- discountData[goodsId].discount = discount;
- discountData[goodsId].discount_price = discountPrice;
-
- $('#discount-data').val(JSON.stringify(discountData));
- updateGoodsInfo();
- });
-
- // 处理规格设置按钮点击事件
- $(document).off('click', '.btn-spec-discount').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));
-
- // 更新按钮文字
- $row.find('.btn-spec-discount').html('规格折扣设置 <span class="label label-success">已设置</span>');
-
- // 计算并显示汇总信息
- 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 = '<i class="fa fa-check-circle text-success"></i> 已设置' + summary.participate_count + '个规格,平均' + summary.avg_discount + '折,共' + summary.total_stocks + '件';
-
- var $infoArea = $row.find('.spec-discount-info');
- if ($infoArea.length > 0) {
- $infoArea.html(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());
- }
- }
- });
- });
- },
-
- api: {
- // 解析Config中的JSON字符串的辅助函数
- parseConfigJson: function(configKey, defaultValue) {
- var configValue = Config[configKey] || defaultValue || {};
-
- // 如果是字符串,尝试解析JSON
- if (typeof configValue === 'string') {
- try {
- return JSON.parse(configValue);
- } catch (e) {
- return defaultValue || {};
- }
- }
-
- return configValue;
- },
-
- 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() {
- console.log('=== 开始更新商品信息 ===');
-
- // 获取表格中的所有商品数据
- var goodsInfo = [];
- var goodsIds = [];
- var table = $('#selected-goods-table').bootstrapTable('getData');
-
- if (!table || table.length === 0) {
- console.log('表格为空,清空隐藏字段');
- $('#goods-info').val('[]');
- $('#goods-ids').val('');
- return [];
- }
-
- console.log('表格商品数据:', table);
-
- // 获取当前所有折扣数据
- var discountData = $('#discount-data').val() ? JSON.parse($('#discount-data').val()) : {};
- console.log('当前折扣数据:', discountData);
-
- // 处理表格中的每个商品
- $.each(table, function(index, item) {
- var goodsId = item.id;
- goodsIds.push(goodsId);
-
- console.log('--- 处理商品:', goodsId, '规格类型:', item.spec_type);
-
- // 基础商品信息
- var goodsData = {
- goods_id: goodsId,
- title: item.title,
- stock: parseInt(item.stocks) || 0,
- spec_type: parseInt(item.spec_type) || 0
- };
-
- // 根据规格类型处理折扣信息
- if (item.spec_type == 0) {
- // 单规格商品处理
- console.log('处理单规格商品:', goodsId);
-
- // 从表格输入框获取当前值
- var $row = $('#selected-goods-table tbody tr[data-id="' + goodsId + '"]');
- var discount = parseFloat($row.find('.discount-input').val()) || 9;
- var discountStocks = parseInt($row.find('.discount-stocks-input').val()) || 0;
- var discountPrice = (item.price * discount / 10).toFixed(2);
-
- // 获取SKU ID
- var skuId = 0;
- if (discountData[goodsId] && discountData[goodsId].sku_id) {
- skuId = discountData[goodsId].sku_id;
- } else if (item.sku_id) {
- skuId = item.sku_id;
- }
-
- goodsData.sku_id = skuId;
- goodsData.discount = discount;
- goodsData.discount_price = discountPrice;
- goodsData.discount_stocks = discountStocks;
-
- console.log('单规格商品数据:', goodsData);
-
- } else if (item.spec_type == 1) {
- // 多规格商品处理
- console.log('处理多规格商品:', goodsId);
-
- var spec = [];
-
- // 检查是否有规格折扣设置
- if (discountData[goodsId] && discountData[goodsId].specs) {
- var specData = discountData[goodsId].specs;
- console.log('找到规格数据:', specData);
-
- // 提取已选中参与折扣的规格
- $.each(specData, function(skuId, specItem) {
- if (specItem && specItem.participate === true) {
- spec.push({
- sku_id: skuId,
- discount: parseFloat(specItem.discount) || 9,
- discount_price: parseFloat(specItem.discount_price).toFixed(2) || "0.00",
- discount_stocks: parseInt(specItem.stocks) || 0
- });
- console.log('添加规格:', skuId, specItem);
- }
- });
- } else {
- console.log('未找到多规格商品的规格设置数据');
- }
-
- goodsData.spec = spec;
- console.log('多规格商品最终数据:', goodsData);
- }
-
- goodsInfo.push(goodsData);
- });
-
- // 更新隐藏字段
- var goodsInfoJson = JSON.stringify(goodsInfo);
- var goodsIdsStr = goodsIds.join(',');
-
- $('#goods-info').val(goodsInfoJson);
- $('#goods-ids').val(goodsIdsStr);
-
- console.log('=== 更新完成 ===');
- console.log('最终 goods_info:', goodsInfoJson);
- console.log('最终 goods_ids:', goodsIdsStr);
-
- return goodsInfo;
- }
- return Controller;
- });
|