12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832 |
- define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {
- var Controller = {
- index: function () {
- // 初始化表格参数
- Table.api.init({
- extend: {
- index_url: 'lottery/activity/index' + location.search,
- add_url: 'lottery/activity/add',
- edit_url: 'lottery/activity/edit',
- del_url: 'lottery/activity/del',
- multi_url: 'lottery/activity/multi',
- import_url: 'lottery/activity/import',
- table: 'shop_lottery_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'), operate: false},
- {field: 'name', title: __('活动名称'), operate: 'LIKE'},
- {field: 'type', title: __('活动类型'), searchList: {"1":"消费抽奖"}, formatter: Table.api.formatter.normal},
- {field: 'status', title: __('状态'), searchList: {"0":"草稿","1":"进行中","2":"已结束","3":"已暂停"}, formatter: Table.api.formatter.status},
- {field: 'lottery_type', title: __('开奖方式'), searchList: {"1":"即抽即中","2":"按时间开奖","3":"按人数开奖"}, formatter: Table.api.formatter.normal},
- {field: 'start_time', title: __('开始时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
- {field: 'end_time', title: __('结束时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
- {field: 'total_people_count', title: __('参与人数'), operate: false},
- {field: 'total_draw_count', title: __('抽奖次数'), operate: false},
- {field: 'total_win_count', title: __('中奖次数'), operate: false},
- {field: 'createtime', title: __('Create time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
- {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
- buttons: [
- {
- name: 'prize',
- title: __('奖品管理'),
- classname: 'btn btn-xs btn-success btn-magic btn-ajax',
- icon: 'fa fa-gift',
- url: 'lottery/activity/prize',
- callback: function (data) {
- Layer.alert("接收到回传数据:" + JSON.stringify(data), {title: "回传数据"});
- },
- visible: function (row) {
- //返回true时按钮显示,返回false隐藏
- return true;
- }
- },
- {
- name: 'condition',
- title: __('参与条件'),
- classname: 'btn btn-xs btn-info btn-magic btn-ajax',
- icon: 'fa fa-tasks',
- url: 'lottery/activity/condition'
- },
- {
- name: 'records',
- title: __('抽奖记录'),
- classname: 'btn btn-xs btn-warning btn-magic btn-ajax',
- icon: 'fa fa-list',
- url: 'lottery/activity/records'
- },
- {
- name: 'statistics',
- title: __('统计数据'),
- classname: 'btn btn-xs btn-primary btn-magic btn-ajax',
- icon: 'fa fa-bar-chart',
- url: 'lottery/activity/statistics'
- }
- ],
- formatter: Table.api.formatter.operate
- }
- ]
- ]
- });
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- add: function () {
- Controller.api.bindevent();
- Controller.api.initAddPage();
- },
- edit: function () {
- Controller.api.bindevent();
- Controller.api.initEditPage();
- },
- 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 () {
- // 自定义验证规则
- $.validator.config({
- rules: {
- // 奖品设置验证
- prize_setting_check: function(element) {
- // 检查奖品数量(总共需要8个奖品,包含系统默认的未中奖项)
- var totalPrizeCount = $('.prize-item').length; // 总奖品数
- if (totalPrizeCount < 8) {
- var userPrizeCount = totalPrizeCount - 1; // 用户添加的奖品数
- var needCount = 8 - totalPrizeCount; // 还需要添加的奖品数
- return '奖品数量不足,还需要添加' + needCount + '个奖品(当前总共' + totalPrizeCount + '个奖品)';
- }
-
- // 检查总概率
- var totalRate = Controller.api.calculateTotalRate();
- if (Math.abs(totalRate - 100) > 0.01) {
- return '奖品总概率必须等于100.00%,当前为' + totalRate.toFixed(2) + '%';
- }
-
- // 检查每个奖品的概率是否大于0
- var hasZeroRate = false;
- $('.prize-rate').each(function() {
- var rate = parseFloat($(this).val()) || 0;
- if (rate <= 0) {
- hasZeroRate = true;
- return false;
- }
- });
-
- if (hasZeroRate) {
- return '所有奖品的中奖概率必须大于0%';
- }
-
- // 检查奖品数量设置
- var hasInvalidQuantity = false;
- $('.prize-item').each(function() {
- var prizeItem = $(this);
- if (prizeItem.attr('data-type') === 'no-prize') {
- return true;
- }
-
- var quantity = parseInt(prizeItem.find('.prize-quantity').val()) || 0;
- if (quantity <= 0) {
- hasInvalidQuantity = true;
- return false;
- }
- });
-
- if (hasInvalidQuantity) {
- return '所有奖品的数量必须大于0';
- }
-
- return true;
- }
- }
- });
-
- Form.api.bindevent($("form[role=form]"));
- },
-
- // 初始化添加页面
- initAddPage: function() {
- // 初始化基础UI组件
- Controller.api.initBasicUI();
-
- // 初始化奖品管理
- Controller.api.initPrizeManagement();
-
- // 初始化任务规则管理
- Controller.api.initTaskRuleManagement();
-
- // 确保DOM渲染完成后再计算奖品数量
- setTimeout(function() {
- Controller.api.updatePrizeCount();
- }, 50);
-
- // 初始化表单验证
- Controller.api.initFormValidation();
- },
-
- // 初始化基础UI组件
- initBasicUI: function() {
- // 活动名称字数统计
- $('#c-name').on('input', function(){
- var len = $(this).val().length;
- $('#activity-name-count').text(len + '/24');
- });
- },
-
- // 初始化任务规则管理
- initTaskRuleManagement: function() {
- // 任务类型切换(复选框)
- $(document).on('change', 'input[name="row[task_type][]"]', function() {
- Controller.api.handleTaskTypeChange();
- });
-
- // 商品规则切换
- $(document).on('change', 'input[name^="condition"][name$="[goods_rule]"]', function() {
- Controller.api.updateGoodsRuleDisplay($(this));
- });
-
- // 初始化任务类型状态
- Controller.api.initTaskTypeState();
- },
-
- // 处理任务类型变化
- handleTaskTypeChange: function() {
- var checkedTypes = $('input[name="row[task_type][]"]:checked');
-
- // 更新复选框样式
- $('input[name="row[task_type][]"]').each(function() {
- var label = $(this).closest('label');
- if ($(this).is(':checked')) {
- label.addClass('checked');
- } else {
- label.removeClass('checked');
- }
- });
-
- // 隐藏所有任务设置项
- $('.task-setting-item').hide();
-
- // 显示选中的任务设置项
- checkedTypes.each(function() {
- var type = parseInt($(this).val());
- $('#task-setting-' + type).show();
- });
-
- // 更新验证规则
- Controller.api.updateTaskValidation();
- },
-
- // 初始化任务类型状态
- initTaskTypeState: function() {
- var checkedTasks = $('input[name="row[task_type][]"]:checked');
-
- // 初始化复选框样式
- $('input[name="row[task_type][]"]').each(function() {
- var label = $(this).closest('label');
- if ($(this).is(':checked')) {
- label.addClass('checked');
- } else {
- label.removeClass('checked');
- }
- });
-
- // 初始化任务设置区域显示
- $('.task-setting-item').hide();
-
- checkedTasks.each(function() {
- var type = parseInt($(this).val());
- $('#task-setting-' + type).show();
- });
- },
-
- // 更新商品规则显示
- updateGoodsRuleDisplay: function($radio) {
- var container = $radio.closest('.task-setting-item');
- var rule = $radio.val();
- var helpText = container.find('.goods-description-box');
-
- if (rule == '1') {
- helpText.html('<span class="text-muted">指定商品下单后将自动触发抽奖活动且发放一次抽奖机会,若用户产生维权退款,已发放的奖励自动回收。</span>');
- } else {
- helpText.html('<span class="text-muted">除指定商品外的其他商品下单后将自动触发抽奖活动且发放一次抽奖机会。</span>');
- }
- },
-
- // 更新任务验证规则
- updateTaskValidation: function() {
- var checkedTypes = $('input[name="row[task_type][]"]:checked');
-
- // 移除旧的验证规则
- $('[name^="condition"]').removeAttr('data-rule');
-
- // 为选中的任务类型添加验证规则
- checkedTypes.each(function() {
- var type = parseInt($(this).val());
-
- switch(type) {
- case 1: // 购买指定商品
- // 商品选择验证会在选择商品时处理
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- $('[name="condition[' + type + '][condition_value]"]').attr('data-rule', 'required;number(0.01~999999.99)');
- break;
- }
- });
- },
-
- // 初始化表单验证
- initFormValidation: function() {
- // 自定义验证规则已在bindevent中定义
-
- // 监听表单提交事件
- $('form[role="form"]').on('submit', function(e) {
- console.log('表单提交开始');
-
- // 验证奖品设置
- if (!Controller.api.validatePrizes()) {
- e.preventDefault();
- return false;
- }
-
- // 验证任务规则设置
- if (!Controller.api.validateTaskRules()) {
- e.preventDefault();
- return false;
- }
-
- // 收集奖品数据并添加到表单
- var prizeData = Controller.api.collectPrizeData();
- if (prizeData.length > 0) {
- // 移除之前的隐藏字段
- $('form[role="form"] input[name^="prizes["]').remove();
-
- // 添加新的奖品数据
- for (var i = 0; i < prizeData.length; i++) {
- var prize = prizeData[i];
- for (var key in prize) {
- if (prize[key] !== null && prize[key] !== undefined) {
- $('<input>').attr({
- type: 'hidden',
- name: 'prizes[' + i + '][' + key + ']',
- value: prize[key]
- }).appendTo('form[role="form"]');
- }
- }
- }
- }
-
- // 收集条件数据并添加到表单
- var conditionResult = Controller.api.collectConditionData();
- var conditionData = conditionResult.conditionData;
- var taskTypes = conditionResult.taskTypes;
-
- if (conditionData.length > 0) {
- // 移除之前的隐藏字段
- $('form[role="form"] input[name^="condition["]').remove();
-
- // 添加新的条件数据
- for (var i = 0; i < conditionData.length; i++) {
- var condition = conditionData[i];
- for (var key in condition) {
- if (condition[key] !== null && condition[key] !== undefined) {
- var value = condition[key];
- if (Array.isArray(value)) {
- value = JSON.stringify(value);
- }
- $('<input>').attr({
- type: 'hidden',
- name: 'condition[' + i + '][' + key + ']',
- value: value
- }).appendTo('form[role="form"]');
- }
- }
- }
- }
-
- // 添加任务类型数据
- if (taskTypes.length > 0) {
- // 移除之前的task_type隐藏字段
- $('form[role="form"] input[type="hidden"][name^="task_type"]').remove();
-
- // 添加任务类型数据
- for (var i = 0; i < taskTypes.length; i++) {
- $('<input>').attr({
- type: 'hidden',
- name: 'task_type[' + i + ']',
- value: taskTypes[i]
- }).appendTo('form[role="form"]');
- }
- }
-
- console.log('表单验证通过,数据收集完成,准备提交');
- console.log('奖品数据:', prizeData);
- console.log('条件数据:', conditionData);
- console.log('任务类型:', taskTypes);
- return true;
- });
- },
-
- // 初始化编辑页面
- initEditPage: function() {
- Controller.api.initAddPage(); // 复用添加页面的初始化逻辑
- },
-
- // 验证奖品设置
- validatePrizes: function() {
- var prizeItems = $('.prize-item');
- var prizeCount = prizeItems.length;
-
- // 检查奖品数量
- if (prizeCount < 1) {
- Toastr.error('请至少设置一个奖品');
- return false;
- }
-
- // 检查奖品总概率
- var totalRate = 0;
- var hasValidPrize = false;
-
- prizeItems.each(function() {
- var type = $(this).attr('data-type');
- var rateInput = $(this).find('.prize-rate');
- var rate = parseFloat(rateInput.val()) || 0;
-
- totalRate += rate;
-
- // 检查非未中奖项是否有有效概率
- if (type !== 'no-prize' && rate > 0) {
- hasValidPrize = true;
- }
-
- // 检查奖品设置是否完整
- var nameInput = $(this).find('.prize-name');
- if (nameInput.length > 0 && !nameInput.val().trim()) {
- Toastr.error('请填写奖品名称');
- nameInput.focus();
- return false;
- }
-
- // 检查奖品数量(未中奖项除外)
- if (type !== 'no-prize') {
- var quantityInput = $(this).find('.prize-quantity');
- var quantity = parseInt(quantityInput.val()) || 0;
- if (quantity <= 0) {
- Toastr.error('奖品数量必须大于0');
- quantityInput.focus();
- return false;
- }
- }
- });
-
- // 检查是否有非未中奖的有效奖品
- if (!hasValidPrize) {
- Toastr.error('请至少设置一个有效的奖品(概率大于0)');
- return false;
- }
-
- // 检查总概率是否合理
- if (totalRate > 100) {
- Toastr.error('奖品总概率不能超过100%');
- return false;
- }
-
- return true;
- },
-
- // 验证任务规则设置
- validateTaskRules: function() {
- var checkedTypes = $('input[name="row[task_type][]"]:checked');
-
- // 检查是否选择了任务类型
- if (checkedTypes.length === 0) {
- Toastr.error('请选择至少一种参与条件');
- return false;
- }
-
- // 验证每个选中的任务类型
- var isValid = true;
- checkedTypes.each(function() {
- var type = parseInt($(this).val());
- var container = $('#task-setting-' + type);
-
- switch(type) {
- case 1: // 购买指定商品
- var goodsContainer = container.find('#selected-goods');
- if (goodsContainer.find('.goods-list-item').length === 0) {
- Toastr.error('请选择参与的商品');
- isValid = false;
- return false;
- }
- break;
-
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- var amountInput = container.find('input[name*="[condition_value]"]');
- var amount = parseFloat(amountInput.val()) || 0;
- if (amount <= 0) {
- var typeName = type === 2 ? '订单消费' : (type === 3 ? '充值' : '累计消费');
- Toastr.error('请填写' + typeName + '金额');
- amountInput.focus();
- isValid = false;
- return false;
- }
- break;
- }
- });
-
- return isValid;
- },
- // 初始化奖品管理
- initPrizeManagement: function() {
- // 初始化拖拽排序
- Controller.api.initPrizeSort();
-
- // 初始化概率计算
- Controller.api.updateTotalRate();
-
- // 绑定系统默认项的事件
- Controller.api.bindDefaultPrizeEvents();
- },
-
- // 绑定系统默认项的事件
- bindDefaultPrizeEvents: function() {
- // 绑定概率输入框事件
- $('.prize-rate').off('input blur').on('input', function() {
- Controller.api.updateTotalRate();
- }).on('blur', function() {
- // 失去焦点时格式化为两位小数
- var value = parseFloat($(this).val()) || 0;
- $(this).val(value.toFixed(2));
- Controller.api.updateTotalRate();
- });
-
- // 绑定编辑按钮事件
- $('.edit-prize').off('click').on('click', function() {
- var prizeItem = $(this).closest('.prize-item');
- // 统一使用editPrize处理所有类型
- Controller.api.editPrize(prizeItem);
- });
-
- // 绑定删除按钮事件
- $('.delete-prize').off('click').on('click', function() {
- var prizeItem = $(this).closest('.prize-item');
- // 检查是否是系统默认项
- if (prizeItem.attr('data-type') === 'no-prize') {
- Toastr.error('系统默认项不能删除');
- return;
- }
- prizeItem.remove();
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
- Controller.api.updatePrizeOrder(); // 更新奖品索引
- });
- },
-
- // 添加奖品
- addPrize: function() {
- var prizeCount = $('.prize-item').length - 1; // 减去未中奖项
- var maxCount = 8;
-
- if (prizeCount >= maxCount) {
- Toastr.error('最多只能添加' + maxCount + '个奖品');
- return;
- }
-
- // 使用通用表单,添加模式
- Controller.api.openPrizeForm({
- mode: 'add',
- title: '添加奖品'
- });
- },
-
- // 通用奖品表单
- openPrizeForm: function(options) {
- var defaults = {
- mode: 'add', // 'add' 或 'edit'
- title: '奖品表单',
- prizeItem: null,
- isSystemNoPrize: false,
- data: {
- name: '',
- image: '',
- type: '2', // 默认实物奖品
- quantity: '1',
- rate: '0.00'
- }
- };
-
- var config = $.extend({}, defaults, options);
- var isEditMode = config.mode === 'edit';
-
- // 获取奖品类型数据
- var prizeTypeMap = Controller.api.parseConfigJson('prizeTypeList', {});
- var prizeTypes = [];
-
- for (var key in prizeTypeMap) {
- if (prizeTypeMap.hasOwnProperty(key)) {
- // 添加模式和编辑模式都包含所有类型
- prizeTypes.push({
- value: parseInt(key),
- text: prizeTypeMap[key]
- });
- }
- }
-
- // 确定是否显示奖励设置区域
- var selectedType = parseInt(config.data.type) || (isEditMode ? 1 : 2);
- var rewardVisible = selectedType > 2;
- var rewardType = Controller.api.getRewardTypeByPrizeType(selectedType);
-
- // 生成表单HTML
- var formHtml = Template('prize-form-template', {
- mode: config.mode,
- name: config.data.name,
- image: config.data.image,
- quantity: config.data.quantity,
- rate: config.data.rate,
- prizeTypes: prizeTypes,
- selectedType: selectedType,
- rewardVisible: rewardVisible,
- rewardType: rewardType
- });
-
- // 弹出表单
- Layer.open({
- type: 1,
- title: config.title,
- area: isEditMode ? ['80%', '80%'] : ['80%', '80%'],
- content: formHtml,
- btn: [isEditMode ? '保存' : '确定', '取消'],
- success: function(layero, index) {
- // 编辑模式需要设置表单数据
- if (isEditMode) {
- Controller.api.setFormData(layero, config);
-
- // 系统默认未中奖项的特殊处理
- if (config.isSystemNoPrize) {
- // 隐藏奖品数量字段(未中奖不需要数量)
- layero.find('.prize-quantity-group').hide();
- // 禁用奖品类型选择(固定为未中奖)
- layero.find('input[name="row[prize_type]"]').prop('disabled', true);
- }
- } else {
- // 添加模式:设置默认奖品类型并触发相应逻辑
- var defaultType = selectedType || 2; // 默认实物奖品
- layero.find('input[name="row[prize_type]"][value="' + defaultType + '"]').prop('checked', true);
-
- // 设置默认图片
- Controller.api.setPrizeDefaultImage(layero.find('.prize-form'), defaultType);
- }
-
- // 设置正确的字数统计初始值
- var currentName = layero.find('input[name="prize_name"]').val();
- var currentLength = currentName ? currentName.length : 0;
- layero.find('#prize-name-count').text(currentLength + '/20');
-
- // 绑定表单事件
- Controller.api.bindPrizeFormEvents(layero, config);
- },
- yes: function(index, layero) {
- var success = false;
- if (isEditMode) {
- success = Controller.api.updatePrize(layero, config.prizeItem);
- } else {
- success = Controller.api.savePrize(layero);
- }
-
- if (success) {
- Layer.close(index);
- }
- }
- });
- },
-
- // 设置表单数据(编辑模式)
- setFormData: function(layero, config) {
- var form = layero.find('.prize-form');
- var data = config.data;
-
- // 设置基本字段
- form.find('input[name="prize_name"]').val(data.name);
- form.find('input[name="prize_image"]').val(data.image);
- form.find('input[name="prize_quantity"]').val(data.quantity);
- form.find('input[name="prize_rate"]').val(data.rate);
-
- // 设置奖品类型(单选框)
- form.find('input[name="row[prize_type]"][value="' + data.type + '"]').prop('checked', true);
-
- // 根据奖品类型处理特殊字段
- if (data.type == '8' && data.goodsId) {
- // 商城奖品:设置商品ID并获取商品信息
- form.find('input[name="goods_id"]').val(data.goodsId);
- Controller.api.loadGoodsInfo(form, data.goodsId, function() {
- // 商品信息加载完成,触发FastAdmin的表单更新
- setTimeout(function() {
- Form.api.bindevent(form);
- }, 100);
- });
- } else if (data.type == '5' && data.couponId) {
- // 优惠券:设置优惠券ID并获取优惠券信息
- form.find('input[name="coupon_id"]').val(data.couponId);
- Controller.api.loadCouponInfo(form, data.couponId);
- }
-
- // FastAdmin的动态显示会根据奖品类型自动处理字段显示
- // 无需手动控制显示逻辑
-
- // 触发上传组件的图片预览更新
- if (data.image) {
- form.find('input[name="prize_image"]').trigger('change');
- }
- },
-
- // 绑定奖品表单事件
- bindPrizeFormEvents: function(layero, config) {
- var form = layero.find('.prize-form');
- var isEditMode = config && config.mode === 'edit';
-
- // 奖品名称字数统计
- form.find('input[name="prize_name"]').on('input', function(){
- var len = $(this).val().length;
- form.find('#prize-name-count').text(len + '/20');
- });
-
- // 奖品类型切换
- form.find('input[name="row[prize_type]"]').change(function() {
- var type = $(this).val();
-
- // 根据模式设置默认图片
- if (!isEditMode) {
- // 添加模式:设置默认图片
- Controller.api.setPrizeDefaultImage(form, type);
- }
- // 编辑模式:不改变图片,保持原有图片
-
- // FastAdmin的动态显示会自动处理字段的显示/隐藏和验证
- // 无需手动控制显示逻辑
- });
-
- // 商品选择按钮
- form.find('#select-goods-btn').click(function() {
- Controller.api.openGoodsSelector(form);
- });
-
- // 优惠券选择按钮
- form.find('#select-coupon-btn').click(function() {
- Controller.api.openCouponSelector(form);
- });
-
- // 兑换码类型切换(FastAdmin动态显示会自动处理)
- // 无需手动控制显示逻辑
-
- // 概率输入框格式化
- form.find('input[name="prize_rate"]').on('blur', function() {
- var value = parseFloat($(this).val()) || 0;
- $(this).val(value.toFixed(2));
- });
-
- // 初始化上传组件
- Form.api.bindevent(form);
- },
-
-
- // 设置奖品默认图片
- setPrizeDefaultImage: function(form, type) {
- // 从后台配置获取默认图片
- var defaultImages = Controller.api.parseConfigJson('prizeDefaultImages', {});
- var defaultImage = defaultImages[type] || '/assets/img/default.png';
-
- form.find('input[name="prize_image"]').val(defaultImage).trigger('change');
- },
-
- // 加载商品信息用于编辑模式回显
- loadGoodsInfo: function(form, goodsId, callback) {
- if (!goodsId) {
- console.warn('loadGoodsInfo: 商品ID为空');
- if (callback) callback();
- return;
- }
-
- console.log('正在加载商品信息,ID:', goodsId);
-
- // 通过Ajax获取商品信息
- $.ajax({
- url: Fast.api.fixurl('shop/goods/info'),
- type: 'POST',
- data: {id: goodsId},
- dataType: 'json',
- success: function(data) {
- console.log('商品信息API响应:', data);
-
- if (data.code === 1 && data.data) {
- var goods = data.data; // 标准FastAdmin响应格式
- console.log('成功获取商品信息:', goods);
-
- // 处理商品数据
- var processedGoods = {
- id: goods.id,
- name: goods.name || goods.title,
- title: goods.title || goods.name,
- image: goods.image ? Fast.api.cdnurl(goods.image) : '',
- price: goods.price || goods.sellprice || '',
- goods_sn: goods.goods_sn || '',
- spec_type: goods.spec_type !== undefined ? goods.spec_type : null,
- category: goods.category || null,
- type_name: Controller.api.getGoodsTypeName(goods),
- type_text: Controller.api.getGoodsTypeText(goods)
- };
-
- // 使用商品模板显示
- var html = Template('prize-goods-template', processedGoods);
- form.find('#selected-goods-display').html(html).show();
-
- // 绑定删除事件
- form.find('.remove-prize-goods').off('click').on('click', function() {
- $(this).closest('.prize-goods-item').remove();
- form.find('input[name="goods_id"]').val('');
- });
-
- console.log('商品信息已成功显示');
-
- // 执行回调
- if (callback) callback();
- } else {
- console.warn('商品信息API返回异常:', data);
- // 显示友好的提示信息
- var errorMsg = data.msg || '获取商品信息失败';
- form.find('#selected-goods-display').html(
- '<div class="alert alert-warning" style="margin-top: 10px;">' +
- '<i class="fa fa-warning"></i> ' + errorMsg +
- ' (商品ID: ' + goodsId + ')' +
- '</div>'
- ).show();
-
- // 即使失败也执行回调
- if (callback) callback();
- }
- },
- error: function(xhr, status, error) {
- console.error('加载商品信息失败 - 详细信息:');
- console.error('- 商品ID:', goodsId);
- console.error('- HTTP状态:', xhr.status);
- console.error('- 错误信息:', error);
- console.error('- 响应内容:', xhr.responseText);
-
- // 显示友好的错误提示
- var errorHtml = '<div class="alert alert-danger" style="margin-top: 10px;">' +
- '<i class="fa fa-exclamation-circle"></i> 加载商品信息失败<br>' +
- '<small>商品ID: ' + goodsId + '</small><br>' +
- '<small>错误: ' + (xhr.status === 404 ? '商品不存在或已删除' :
- xhr.status === 403 ? '无权限访问' :
- '网络错误,请稍后重试') + '</small>' +
- '</div>';
- form.find('#selected-goods-display').html(errorHtml).show();
-
- // 错误时也执行回调
- if (callback) callback();
- }
- });
- },
-
- // 加载优惠券信息用于编辑模式回显
- loadCouponInfo: function(form, couponId) {
- if (!couponId) {
- console.warn('loadCouponInfo: 优惠券ID为空');
- return;
- }
-
- console.log('正在加载优惠券信息,ID:', couponId);
-
- // 暂时显示一个简单的占位信息,提醒需要重新选择
- var placeholderHtml = '<div class="alert alert-info" style="margin-top: 10px;">' +
- '<i class="fa fa-info-circle"></i> 编辑模式下需要重新选择优惠券<br>' +
- '<small>优惠券ID: ' + couponId + '</small>' +
- '</div>';
- form.find('#selected-coupon-display').html(placeholderHtml).show();
-
- console.log('优惠券占位信息已显示,用户需要重新选择');
- },
-
-
- // 打开商品选择器
- openGoodsSelector: function(form) {
- Fast.api.open('shop/goods/select?selectMode=single', '选择商品', {
- callback: function(data) {
- if (data.length > 0) {
- var goods = data[0]; // 取第一个选中的商品
-
- // 处理商品数据,确保格式完整
- var processedGoods = {
- id: goods.id,
- name: goods.name || goods.title,
- title: goods.title || goods.name,
- image: goods.image ? (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(goods.image) : goods.image) : '',
- price: goods.price || goods.sellprice || '',
- goods_sn: goods.goods_sn || '',
- spec_type: goods.spec_type !== undefined ? goods.spec_type : null,
- category: goods.category || null,
- type_name: Controller.api.getGoodsTypeName(goods),
- type_text: Controller.api.getGoodsTypeText(goods)
- };
-
- // 使用奖品商品模板
- var html = Template('prize-goods-template', processedGoods);
-
- form.find('#selected-goods-display').html(html).show();
-
- // 设置隐藏域的值以触发验证
- form.find('input[name="goods_id"]').val(goods.id);
-
- // 设置商品图片为奖品图片
- form.find('input[name="prize_image"]').val(goods.image).trigger('change');
-
- // 绑定删除事件
- form.find('.remove-prize-goods').off('click').on('click', function() {
- $(this).closest('.prize-goods-item').remove();
- form.find('input[name="goods_id"]').val(''); // 清空隐藏域
- });
- }
- }
- });
- },
-
- // 打开优惠券选择器
- openCouponSelector: function(form) {
- Fast.api.open('shop/coupon/select', '选择优惠券', {
- callback: function(data) {
- if (data.length > 0) {
- var coupon = data[0]; // 取第一个选中的优惠券
-
- // 直接使用模板ID
- var html = Template('selected-coupon-template', {
- name: coupon.name,
- type_text: coupon.type_text || '优惠券',
- id: coupon.id
- });
-
- form.find('#selected-coupon-display').html(html).show();
-
- // 设置隐藏域的值以触发验证
- form.find('input[name="coupon_id"]').val(coupon.id);
- }
- }
- });
- },
-
- // 保存奖品
- savePrize: function(layero) {
- var form = layero.find('.prize-form');
- var name = form.find('input[name="prize_name"]').val().trim();
- var type = form.find('input[name="row[prize_type]"]:checked').val();
- var image = form.find('input[name="prize_image"]').val();
- var quantity = form.find('input[name="prize_quantity"]').val();
-
- // 根据奖品类型获取对应的奖励值
- var rewardValue = '';
- if (type == 3) { // 积分
- rewardValue = form.find('input[name="reward_value_integral"]').val();
- } else if (type == 4) { // 余额
- rewardValue = form.find('input[name="reward_value_balance"]').val();
- } else if (type == 6) { // 红包
- rewardValue = form.find('input[name="reward_value_redpack"]').val();
- }
-
- var goodsId = form.find('input[name="goods_id"]').val();
- var couponId = form.find('input[name="coupon_id"]').val();
-
- if (!name) {
- Toastr.error('请输入奖品名称');
- return false;
- }
- if (!type) {
- Toastr.error('请选择奖品类型');
- return false;
- }
- if (!image) {
- Toastr.error('请选择奖品图片');
- return false;
- }
- // 未中奖类型不需要验证数量
- if (type != 1 && (!quantity || quantity < 1)) {
- Toastr.error('请输入正确的奖品数量');
- return false;
- }
-
- // 验证积分数量
- if (type == 3 && !rewardValue) {
- Toastr.error('请输入积分数量');
- return false;
- }
-
- // 验证余额金额
- if (type == 4 && !rewardValue) {
- Toastr.error('请输入余额金额');
- return false;
- }
-
- // 验证优惠券选择
- if (type == 5 && !couponId) {
- Toastr.error('请选择优惠券');
- return false;
- }
-
- // 验证红包金额
- if (type == 6 && !rewardValue) {
- Toastr.error('请输入红包金额');
- return false;
- }
-
- // 验证商品选择(只有商城奖品需要选择商品)
- if (type == 8 && !goodsId) {
- Toastr.error('请选择商品');
- return false;
- }
-
- // 验证兑换码设置
- if (type == 7) {
- var codeType = form.find('input[name="code_type"]:checked').val();
- if (codeType === 'manual') {
- var manualCodes = form.find('textarea[name="manual_codes"]').val().trim();
- if (!manualCodes) {
- Toastr.error('请输入兑换码列表');
- return false;
- }
- }
- }
-
- // 构建奖品数据
- var prizeData = {
- name: name,
- type: parseInt(type),
- image: image,
- quantity: type == 1 ? 0 : parseInt(quantity), // 未中奖类型数量为0
- rate: 0
- };
-
- // 根据奖品类型添加特定数据
- switch(parseInt(type)) {
- case 3: // 积分
- prizeData.points = parseInt(rewardValue);
- break;
- case 4: // 余额
- prizeData.balance = parseFloat(rewardValue);
- break;
- case 5: // 优惠券
- prizeData.coupon_id = couponId;
- prizeData.coupon_name = form.find('#selected-coupon-display .selected-coupon-item span:first').text();
- break;
- case 6: // 红包
- prizeData.redpack_amount = parseFloat(rewardValue);
- break;
- case 7: // 兑换码
- prizeData.code_type = form.find('input[name="code_type"]:checked').val();
- if (prizeData.code_type === 'manual') {
- prizeData.manual_codes = form.find('textarea[name="manual_codes"]').val();
- }
- break;
- case 8: // 商城奖品
- prizeData.goods_id = goodsId;
- // 使用简化的选择器获取商品名称
- prizeData.goods_name = form.find('#selected-goods-display .goods-name-display').text() || '';
- break;
- }
-
- // 添加奖品到列表
- Controller.api.appendPrizeToList(prizeData);
-
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
- Controller.api.updatePrizeOrder(); // 更新奖品索引
-
- return true;
- },
-
- // 添加奖品到列表
- appendPrizeToList: function(prize) {
- // 获取奖品类型信息
- var typeName = Controller.api.getPrizeTypeName(prize.type);
- var labelClass = Controller.api.getPrizeLabelClass(prize.type);
- var rewardText = Controller.api.getPrizeRewardText(prize);
-
- // 获取当前奖品索引 (跳过未中奖项,从1开始)
- var prizeIndex = $('.prize-list .prize-item').length;
-
- // 处理图片URL
- var imageRelative = prize.image; // 相对路径,用于表单提交
- var imageDisplay = prize.image ? (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(prize.image) : prize.image) : ''; // CDN URL,用于显示
-
- // 使用外部模板
- var prizeHtml = Template('prize-item-template', {
- index: prizeIndex,
- name: prize.name,
- type: prize.type,
- typeName: typeName,
- labelClass: labelClass,
- rewardText: rewardText,
- imageRelative: imageRelative, // 相对路径
- imageDisplay: imageDisplay, // CDN URL
- quantity: prize.quantity || 0,
- rate: prize.rate || 0,
- goodsId: prize.goods_id || '',
- couponId: prize.coupon_id || ''
- });
-
- $('.prize-list').append(prizeHtml);
-
- // 绑定事件
- $('.prize-rate').off('input blur').on('input', function() {
- Controller.api.updateTotalRate();
- }).on('blur', function() {
- // 失去焦点时格式化为两位小数
- var value = parseFloat($(this).val()) || 0;
- $(this).val(value.toFixed(2));
- Controller.api.updateTotalRate();
- });
-
- $('.delete-prize').off('click').on('click', function() {
- var prizeItem = $(this).closest('.prize-item');
- // 检查是否是系统默认项
- if (prizeItem.attr('data-type') === 'no-prize') {
- Toastr.error('系统默认项不能删除');
- return;
- }
- prizeItem.remove();
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
- Controller.api.updatePrizeOrder(); // 更新奖品索引
- });
-
- $('.edit-prize').off('click').on('click', function() {
- var prizeItem = $(this).closest('.prize-item');
- // 统一使用editPrize处理所有类型
- Controller.api.editPrize(prizeItem);
- });
-
- // 重新初始化拖拽排序
- Controller.api.initPrizeSort();
- },
-
- // 初始化奖品拖拽排序
- initPrizeSort: function() {
- require(['../libs/Sortable/Sortable'], function(Sortable) {
- var prizeListEl = document.querySelector('.prize-list');
- if (prizeListEl) {
- // 如果已经初始化过,先销毁
- if (prizeListEl.sortableInstance) {
- prizeListEl.sortableInstance.destroy();
- }
-
- // 创建新的 Sortable 实例
- prizeListEl.sortableInstance = new Sortable(prizeListEl, {
- handle: '.prize-sort-handle',
- animation: 150,
- onUpdate: function(evt) {
- Controller.api.updatePrizeOrder();
- }
- });
- }
- });
- },
-
- // 获取奖品类型名称
- getPrizeTypeName: function(type) {
- var prizeTypeMap = Controller.api.parseConfigJson('prizeTypeList', {});
- return prizeTypeMap[type] || '未知';
- },
-
- // 获取奖品标签样式类
- getPrizeLabelClass: function(type) {
- var classMap = {
- 1: 'default', // 未中奖 - 灰色
- 2: 'primary', // 实物奖品 - 蓝色
- 3: 'warning', // 积分 - 橙色
- 4: 'info', // 余额 - 浅蓝色
- 5: 'success', // 优惠券 - 绿色
- 6: 'danger', // 红包 - 红色
- 7: 'default', // 兑换码 - 灰色
- 8: 'primary' // 商城奖品 - 蓝色
- };
- return classMap[type] || 'default';
- },
-
- // 获取奖品奖励文本
- getPrizeRewardText: function(prize) {
- if (!prize.type || prize.type == 1) {
- return ''; // 未中奖不显示奖励文本
- }
-
- switch(parseInt(prize.type)) {
- case 2: // 实物奖品
- return '';
- case 3: // 积分
- return prize.points ? (prize.points + ' 积分') : '';
- case 4: // 余额
- return prize.balance ? (prize.balance + ' 余额') : '';
- case 5: // 优惠券
- return prize.coupon_name ? prize.coupon_name : '';
- case 6: // 红包
- return prize.redpack_amount ? (prize.redpack_amount + ' 元红包') : '';
- case 7: // 兑换码
- return prize.code_type == 'manual' ? '手动兑换码' : '自动兑换码';
- case 8: // 商城奖品
- return prize.goods_name ? prize.goods_name : '';
- default:
- return '';
- }
- },
-
- // 从表单获取奖品奖励文本
- getPrizeRewardTextFromForm: function(form, type) {
- if (!type || type == 1) {
- return ''; // 未中奖不显示奖励文本
- }
-
- switch(parseInt(type)) {
- case 2: // 实物奖品
- return '';
- case 3: // 积分
- var points = form.find('input[name="reward_value_integral"]').val();
- return points ? (points + ' 积分') : '';
- case 4: // 余额
- var balance = form.find('input[name="reward_value_balance"]').val();
- return balance ? (balance + ' 余额') : '';
- case 5: // 优惠券
- var couponName = form.find('#selected-coupon-display .selected-coupon-item span:first').text();
- return couponName || '';
- case 6: // 红包
- var amount = form.find('input[name="reward_value_redpack"]').val();
- return amount ? (amount + ' 元红包') : '';
- case 7: // 兑换码
- var codeType = form.find('input[name="code_type"]:checked').val();
- return codeType == 'manual' ? '手动兑换码' : '自动兑换码';
- case 8: // 商城奖品
- // 使用简化的选择器获取商品名称
- return form.find('#selected-goods-display .goods-name-display').text() || '';
- default:
- return '';
- }
- },
-
- // 根据奖品类型获取奖励类型
- getRewardTypeByPrizeType: function(prizeType) {
- switch(parseInt(prizeType)) {
- case 3: return 'integral'; // 积分
- case 4: return 'balance'; // 余额
- case 5: return 'coupon'; // 优惠券
- case 6: return 'redbag'; // 红包
- case 7: return 'code'; // 兑换码
- case 8: return 'goods'; // 商城奖品
- default: return 'none';
- }
- },
-
- // 更新奖品数量统计
- updatePrizeCount: function() {
- var totalCount = $('.prize-item').length; // 总奖品数(包含未中奖项)
- var userCount = totalCount - 1; // 用户添加的奖品数(减去未中奖项)
-
- // 显示总奖品数(包含系统默认的未中奖项)
- $('#prize-count').text(totalCount);
-
- // 更新添加奖品按钮状态(基于用户可添加的奖品数)
- Controller.api.updateAddPrizeButtonState(userCount);
-
- // 更新验证状态
- $('input[name="prize_setting_check"]').val('1').trigger('change');
- },
-
- // 更新添加奖品按钮状态
- updateAddPrizeButtonState: function(userCount) {
- var maxUserCount = 8; // 用户最大可添加奖品数量
- var addButton = $('#add-prize-btn');
- var remainingCount = maxUserCount - userCount;
-
- if (userCount >= maxUserCount) {
- // 达到最大数量,禁用按钮
- addButton.prop('disabled', true).addClass('disabled');
- addButton.find('.btn-text').text('已达最大数量');
- $('#prize-count-tip').text('已添加最大数量的奖品').removeClass('text-muted').addClass('text-danger');
- } else {
- // 未达到最大数量,启用按钮
- addButton.prop('disabled', false).removeClass('disabled');
- addButton.find('.btn-text').text('添加奖品');
- if (remainingCount <= 2) {
- $('#prize-count-tip').text('还可添加 ' + remainingCount + ' 个奖品').removeClass('text-muted text-danger').addClass('text-warning');
- } else {
- // 当用户还没添加奖品时,显示还需添加多少个才能满足最低要求
- var minRequired = Math.max(0, 7 - userCount); // 至少需要7个用户奖品(总共8个,已有1个系统默认)
- if (minRequired > 0) {
- $('#prize-count-tip').text('还需添加 ' + minRequired + ' 个奖品').removeClass('text-warning text-danger').addClass('text-muted');
- } else {
- $('#prize-count-tip').text('还可添加 ' + remainingCount + ' 个奖品').removeClass('text-warning text-danger').addClass('text-muted');
- }
- }
- }
- },
-
- // 计算总概率
- calculateTotalRate: function() {
- var total = 0;
- $('.prize-rate').each(function() {
- total += parseFloat($(this).val()) || 0;
- });
- // 保留两位小数
- return Math.round(total * 100) / 100;
- },
-
- // 更新总概率显示
- updateTotalRate: function() {
- var total = Controller.api.calculateTotalRate();
- // 格式化显示为两位小数
- $('#total-rate').text(total.toFixed(2) + '%');
-
- // 根据概率设置颜色
- if (total > 100) {
- $('#total-rate').removeClass('text-success text-warning').addClass('text-danger');
- } else if (total === 100) {
- $('#total-rate').removeClass('text-danger text-warning').addClass('text-success');
- } else {
- $('#total-rate').removeClass('text-danger text-success').addClass('text-warning');
- }
-
- // 更新验证状态
- $('input[name="prize_setting_check"]').val('1').trigger('change');
- },
-
- // 编辑奖品(统一处理所有类型)
- editPrize: function(prizeItem) {
- // 判断是否为系统默认未中奖项
- var isSystemNoPrize = prizeItem.attr('data-type') === 'no-prize';
-
- // 获取奖品信息
- var name, imageRelative, type, quantity, rate, goodsId, couponId;
-
- if (isSystemNoPrize) {
- // 系统默认项从不同位置获取数据
- name = prizeItem.find('td:eq(1)').text().trim(); // 去除空格
- imageRelative = prizeItem.find('.prize-image-input').val();
- type = prizeItem.find('.prize-type-input').val() || '1';
- quantity = 0; // 未中奖项数量固定为0
- rate = prizeItem.find('.prize-rate').val();
- } else {
- // 普通奖品从标准位置获取数据
- name = prizeItem.find('.prize-name').text().trim(); // 去除空格
- imageRelative = prizeItem.find('.prize-image-input').val();
- type = prizeItem.find('.prize-type-input').val();
- quantity = prizeItem.find('.prize-quantity').val();
- rate = prizeItem.find('.prize-rate').val();
-
- // 获取商品ID和优惠券ID(如果存在)
- goodsId = prizeItem.find('.prize-goods-id-input').val();
- couponId = prizeItem.find('.prize-coupon-id-input').val();
- }
-
- var title = isSystemNoPrize ? '编辑未中奖项' : '编辑奖品';
-
- // 使用通用表单,编辑模式
- Controller.api.openPrizeForm({
- mode: 'edit',
- title: title,
- prizeItem: prizeItem,
- isSystemNoPrize: isSystemNoPrize,
- data: {
- name: name,
- image: imageRelative,
- type: type,
- quantity: quantity,
- rate: rate,
- goodsId: goodsId,
- couponId: couponId
- }
- });
- },
-
- // 更新奖品信息
- updatePrize: function(layero, prizeItem) {
- var form = layero.find('.prize-form');
- var name = form.find('input[name="prize_name"]').val().trim();
- var type = form.find('input[name="row[prize_type]"]:checked').val();
- var image = form.find('input[name="prize_image"]').val();
- var quantity = form.find('input[name="prize_quantity"]').val();
- var rate = form.find('input[name="prize_rate"]').val();
-
- if (!name) {
- Toastr.error('请输入奖品名称');
- return false;
- }
- if (!image) {
- Toastr.error('请选择奖品图片');
- return false;
- }
- // 未中奖类型不需要验证数量
- if (type != 1 && (!quantity || quantity < 1)) {
- Toastr.error('请输入正确的奖品数量');
- return false;
- }
-
- // 更新界面显示
- var imageDisplay = image ? (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(image) : image) : '';
-
- // 检查是否是系统默认项
- if (prizeItem.attr('data-type') === 'no-prize') {
- // 系统默认项直接更新文本
- prizeItem.find('td:eq(1)').text(name);
- } else {
- // 普通奖品更新显示元素和隐藏域
- prizeItem.find('.prize-name').text(name);
- prizeItem.find('.prize-name-input').val(name);
- prizeItem.find('.prize-quantity').val(quantity);
-
- // 更新奖品类型隐藏域
- prizeItem.find('.prize-type-input').val(type);
-
- // 更新奖品类型显示标签
- var typeName = Controller.api.getPrizeTypeName(type);
- var labelClass = Controller.api.getPrizeLabelClass(type);
- var typeLabel = prizeItem.find('td:eq(2) .label');
- typeLabel.removeClass().addClass('label label-' + labelClass).text(typeName);
-
- // 更新奖励文本显示
- var rewardText = Controller.api.getPrizeRewardTextFromForm(form, type);
- var rewardDiv = prizeItem.find('td:eq(2) div');
- if (rewardText) {
- if (rewardDiv.length === 0) {
- // 如果没有奖励文本div,创建一个
- prizeItem.find('td:eq(2)').append('<div style="font-size: 11px; color: #666; margin-top: 2px;">' + rewardText + '</div>');
- } else {
- // 更新现有的奖励文本
- rewardDiv.text(rewardText);
- }
- } else {
- // 删除奖励文本
- rewardDiv.remove();
- }
- }
-
- // 更新图片显示和隐藏域
- prizeItem.find('img').attr('src', imageDisplay);
- prizeItem.find('.prize-image-input').val(image); // 隐藏域存储相对路径
- prizeItem.find('.prize-rate').val(rate);
-
- Controller.api.updateTotalRate();
-
- return true;
- },
-
- // 更新奖品排序
- updatePrizeOrder: function() {
- // 重新编号所有奖品的隐藏域name属性
- $('.prize-list .prize-item').each(function(index) {
- var $item = $(this);
- var prizeIndex = index; // 按实际位置索引
-
- // 更新隐藏域的name属性
- $item.find('.prize-name-input').attr('name', 'prizes[' + prizeIndex + '][name]');
- $item.find('.prize-type-input').attr('name', 'prizes[' + prizeIndex + '][type]');
- $item.find('.prize-image-input').attr('name', 'prizes[' + prizeIndex + '][image]');
-
- // 更新商品ID和优惠券ID的隐藏域name属性
- $item.find('.prize-goods-id-input').attr('name', 'prizes[' + prizeIndex + '][goods_id]');
- $item.find('.prize-coupon-id-input').attr('name', 'prizes[' + prizeIndex + '][coupon_id]');
-
- // 更新其他表单字段的name属性
- $item.find('.prize-quantity').attr('name', 'prizes[' + prizeIndex + '][quantity]');
- $item.find('.prize-rate').attr('name', 'prizes[' + prizeIndex + '][rate]');
-
- // 更新奖品特定字段的name属性
- var prizeType = parseInt($item.find('.prize-type-input').val());
- switch(prizeType) {
- case 3: // 积分
- $item.find('.prize-points-input').attr('name', 'prizes[' + prizeIndex + '][points]');
- break;
- case 4: // 余额
- $item.find('.prize-balance-input').attr('name', 'prizes[' + prizeIndex + '][balance]');
- break;
- case 6: // 红包
- $item.find('.prize-redpack-input').attr('name', 'prizes[' + prizeIndex + '][redpack_amount]');
- break;
- case 7: // 兑换码
- $item.find('.prize-codes-input').attr('name', 'prizes[' + prizeIndex + '][manual_codes]');
- break;
- }
- });
-
- console.log('奖品排序已更新');
- },
-
- // 在表单提交前收集奖品数据
- collectPrizeData: function() {
- var prizesData = [];
-
- $('.prize-list .prize-item').each(function(index) {
- var $item = $(this);
- var prizeType = parseInt($item.find('.prize-type-input').val());
-
- var prizeData = {
- name: $item.find('.prize-name-input').val() || $item.find('.prize-name').text() || $item.find('td:eq(1)').text(),
- type: prizeType,
- image: $item.find('.prize-image-input').val(),
- quantity: $item.find('.prize-quantity').val() || 0,
- rate: $item.find('.prize-rate').val() || 0
- };
-
- // 根据奖品类型添加特定字段
- switch(prizeType) {
- case 3: // 积分
- var pointsInput = $item.find('.prize-points-input');
- if (pointsInput.length === 0) {
- // 如果隐藏域不存在,从表单中获取
- pointsInput = $('input[name="reward_value_integral"]');
- }
- prizeData.points = pointsInput.val() || 0;
- break;
- case 4: // 余额
- var balanceInput = $item.find('.prize-balance-input');
- if (balanceInput.length === 0) {
- balanceInput = $('input[name="reward_value_balance"]');
- }
- prizeData.balance = balanceInput.val() || 0;
- break;
- case 5: // 优惠券
- prizeData.coupon_id = $item.find('.prize-coupon-id-input').val() || 0;
- break;
- case 6: // 红包
- var redpackInput = $item.find('.prize-redpack-input');
- if (redpackInput.length === 0) {
- redpackInput = $('input[name="reward_value_redpack"]');
- }
- prizeData.redpack_amount = redpackInput.val() || 0;
- break;
- case 7: // 兑换码
- var codesInput = $item.find('.prize-codes-input');
- if (codesInput.length === 0) {
- codesInput = $('textarea[name="manual_codes"]');
- }
- prizeData.manual_codes = codesInput.val() || '';
- break;
- case 8: // 商城奖品
- prizeData.goods_id = $item.find('.prize-goods-id-input').val() || 0;
- break;
- }
-
- prizesData.push(prizeData);
- });
-
- return prizesData;
- },
-
- // 在表单提交前收集条件数据
- collectConditionData: function() {
- var conditionData = {};
- var taskTypes = [];
-
- // 获取选中的任务类型
- $('input[name="row[task_type][]"]:checked').each(function() {
- taskTypes.push($(this).val());
- });
-
- // 为每个任务类型收集条件数据
- taskTypes.forEach(function(taskType) {
- var type = parseInt(taskType);
- var condition = {};
-
- switch(type) {
- case 1: // 购买指定商品
- condition.type = type;
- condition.goods_rule = $('input[name="condition[' + type + '][goods_rule]"]:checked').val() || 1;
- condition.goods_ids = $('#task-goods-ids-' + type).val() || '[]';
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- condition.type = type;
- condition.condition_value = $('input[name="condition[' + type + '][condition_value]"]').val() || 0;
- break;
- }
-
- conditionData[type] = condition;
- });
-
- return {
- conditionData: conditionData,
- taskTypes: taskTypes
- };
- },
- // 选择商品 - 通用方法,支持单选和多选
- selectGoods: function(options) {
- var defaults = {
- mode: 'single', // 'single' 单选, 'multiple' 多选
- title: '选择商品',
- container: '#selected-goods',
- template: 'goods-list-template', // 统一使用goods-list-template
- maxSelect: 0, // 最大选择数量,0表示无限制
- callback: null
- };
-
- var config = $.extend({}, defaults, options);
-
- // 构建URL参数
- var urlParams = [];
-
- // 添加选择模式参数
- if (config.mode === 'single') {
- urlParams.push('selectMode=single');
- } else {
- urlParams.push('selectMode=multiple');
- // 如果有最大选择限制,添加参数
- if (config.maxSelect > 0) {
- urlParams.push('maxSelect=' + config.maxSelect);
- }
- }
-
- // 构建完整URL
- var url = 'shop/goods/select';
- if (urlParams.length > 0) {
- url += '?' + urlParams.join('&');
- }
-
- Fast.api.open(url, config.title, {
- callback: function(data) {
- if (data && data.length > 0) {
- // 单选模式只取第一个
- if (config.mode === 'single' && data.length > 1) {
- data = [data[0]];
- }
-
- Controller.api.updateSelectedGoods(data, config);
-
- // 执行回调
- if (typeof config.callback === 'function') {
- config.callback(data);
- }
- } else {
- Toastr.error('请选择商品');
- }
- }
- });
- },
-
- // 选择任务商品(多选模式)
- selectTaskGoods: function(container) {
- Controller.api.selectGoods({
- mode: 'multiple',
- title: '选择参与商品',
- container: container || '#task-goods-container',
- template: 'task-goods-template',
- callback: function(data) {
- // 如果是购买指定商品任务,更新隐藏字段
- if (container === '#selected-goods' && data && data.length > 0) {
- var goodsIds = data.map(function(item) {
- return item.id;
- });
- // 更新隐藏字段,存储JSON格式的商品IDs
- $('#task-goods-ids-1').val(JSON.stringify(goodsIds));
- console.log('购买指定商品任务 - 商品IDs已更新:', goodsIds);
-
- // 绑定删除事件
- Controller.api.bindTaskGoodsEvents();
- }
- }
- });
- },
-
- // 选择奖品商品(单选模式)
- selectPrizeGoods: function(container) {
- Controller.api.selectGoods({
- mode: 'single',
- title: '选择奖品商品',
- container: container || '#prize-goods-container',
- template: 'goods-list-template' // 使用统一的商品选择模板
- });
- },
-
- // 更新已选商品
- updateSelectedGoods: function(goods, config) {
- config = config || {};
- var container = config.container || '#selected-goods';
- var template = config.template || 'goods-list-template';
-
- // 预处理商品数据
- var processedGoods = Controller.api.processGoodsData(goods);
-
- var html = '';
-
- if (template === 'goods-list-template') {
- // 商品列表(支持单选和多选)
- html = Template(template, {
- goods: processedGoods
- });
-
- $(container).html(html);
-
- // 绑定删除事件
- $('.remove-goods-item').off('click').on('click', function() {
- $(this).closest('.goods-list-item').remove();
- });
-
- } else if (template === 'prize-goods-template') {
- // 奖品商品(单选)
- if (processedGoods.length > 0) {
- html = Template(template, processedGoods[0]);
- $(container).html(html);
-
- // 绑定删除事件
- $('.remove-prize-goods').off('click').on('click', function() {
- $(this).closest('.prize-goods-item').remove();
- });
- }
-
- } else {
- // 其他模板(向后兼容)
- html = Template(template, {
- goods: processedGoods
- });
-
- $(container).html(html);
- }
- },
-
- // 处理商品数据
- processGoodsData: function(goods) {
- var processedGoods = [];
- if (goods && goods.length) {
- for (var i = 0; i < goods.length; i++) {
- var item = goods[i];
- var processedItem = {
- id: item.id,
- name: item.name || item.title,
- title: item.title || item.name,
- image: item.image ? (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(item.image) : item.image) : '',
- price: item.price || item.sellprice || '',
- goods_sn: item.goods_sn || '',
- spec_type: item.spec_type !== undefined ? item.spec_type : null,
- category: item.category || null,
- type_name: Controller.api.getGoodsTypeName(item),
- type_text: Controller.api.getGoodsTypeText(item)
- };
- processedGoods.push(processedItem);
- }
- }
- return processedGoods;
- },
-
- // 获取商品类型文本(用于显示标签)
- getGoodsTypeText: function(goods) {
- // 根据商品类型返回相应的标签文本
- if (goods.type == 2) {
- return '密'; // 虚拟商品显示"密"
- }
- if (goods.isrecom == 1) {
- return '荐'; // 推荐商品显示"荐"
- }
- if (goods.ishot == 1) {
- return '热'; // 热门商品显示"热"
- }
- if (goods.isnew == 1) {
- return '新'; // 新品显示"新"
- }
- return ''; // 默认无标签
- },
-
- // 获取商品类型名称
- getGoodsTypeName: function(goods) {
- // 根据商品类型返回类型名称
- if (goods.type == 1) {
- return '普通商品';
- } else if (goods.type == 2) {
- return '虚拟商品';
- } else if (goods.type == 3) {
- return '服务商品';
- }
- return '普通商品'; // 默认类型
- },
-
- // 绑定任务商品删除事件
- bindTaskGoodsEvents: function() {
- $('.remove-task-goods').off('click').on('click', function() {
- var goodsId = $(this).data('id');
- var $item = $(this).closest('.goods-list-item');
-
- // 从DOM中移除商品项
- $item.remove();
-
- // 更新隐藏字段中的商品IDs
- Controller.api.updateTaskGoodsIds();
- });
- },
-
- // 更新任务商品IDs隐藏字段
- updateTaskGoodsIds: function() {
- var goodsIds = [];
- $('#selected-goods .goods-list-item').each(function() {
- var goodsId = $(this).data('id');
- if (goodsId) {
- goodsIds.push(goodsId);
- }
- });
-
- // 更新隐藏字段
- $('#task-goods-ids-1').val(JSON.stringify(goodsIds));
- console.log('任务商品IDs已更新:', goodsIds);
- }
- }
- };
-
- // 全局函数,供HTML调用
- window.addPrize = function() {
- Controller.api.addPrize();
- };
-
- // 默认商品选择(针对购买指定商品任务,使用多选模式)
- window.selectGoods = function() {
- Controller.api.selectGoods({
- mode: 'multiple',
- title: '选择参与商品',
- container: '#selected-goods',
- template: 'goods-list-template'
- });
- };
-
- // 任务商品选择(多选)
- window.selectTaskGoods = function(container) {
- Controller.api.selectTaskGoods(container);
- };
-
- // 奖品商品选择(单选)
- window.selectPrizeGoods = function(container) {
- Controller.api.selectPrizeGoods(container);
- };
-
- return Controller;
- });
|