1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716 |
- 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: Controller.api.parseConfigJson("typeList"), formatter: Table.api.formatter.normal},
- {field: 'status', title: __('状态'), searchList: Controller.api.parseConfigJson("statusList"), formatter: Table.api.formatter.status},
- {field: 'lottery_type', title: __('开奖方式'), searchList: Controller.api.parseConfigJson("lotteryTypeList"), 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 () {
- Form.api.bindevent($("form[role=form]"));
- },
-
- // 初始化添加页面
- initAddPage: function() {
- // 初始化基础UI组件
- Controller.api.initBasicUI();
-
- // 初始化奖品数据管理器
- Controller.api.prizesDataManager.init();
-
- // 初始化规则数据管理器
- Controller.api.rulesDataManager.init();
-
- // 初始化奖品管理
- Controller.api.initPrizeManagement();
-
- // 初始化任务规则管理
- Controller.api.initTaskRuleManagement();
-
- // 清空奖品列表DOM,确保没有任何默认奖品
- $('.prize-list').empty();
-
- // 添加页面:用户手动添加所有奖品,不创建任何默认项
- console.log('添加页面初始化完成,奖品列表已清空,等待用户手动添加奖品');
-
- // 确保DOM渲染完成后再计算奖品数量
- setTimeout(function() {
- console.log('页面初始化 - 开始更新奖品计数');
- 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.updateRulesDataFromDOM();
- });
-
- // 条件值输入框变化事件
- $(document).on('input change', 'input[name^="condition"][name$="[condition_value]"]', function() {
- // 更新规则数据管理器
- Controller.api.updateRulesDataFromDOM();
- });
-
- // 初始化任务类型状态
- 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();
-
- // 更新规则数据管理器
- Controller.api.updateRulesDataFromDOM();
- },
-
- // 初始化任务类型状态
- 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() {
- // 添加自定义验证规则 - 验证奖品JSON数据
- if (typeof Nice !== 'undefined' && Nice.Validator) {
- Nice.Validator.addRule('prizesJson', function(val, el) {
- try {
- var prizes = JSON.parse(val || '[]');
-
- // 验证是否有奖品
- if (!prizes || prizes.length === 0) {
- return false;
- }
-
- var totalRate = 0;
-
- // 验证每个奖品的基本字段
- for (var i = 0; i < prizes.length; i++) {
- var prize = prizes[i];
-
- // 验证必填字段
- if (!prize.name || prize.name.trim() === '') {
- return false;
- }
-
- if (!prize.type) {
- return false;
- }
-
- // 验证奖品类型是否有效
- if (!prize.type || prize.type < 1 || prize.type > 8) {
- return false;
- }
-
- // 验证概率值
- if (typeof prize.rate !== 'number' || prize.rate < 0 || prize.rate > 100) {
- return false;
- }
-
- // 验证数量(未中奖项除外)
- if (prize.type !== 1 && (!prize.quantity || prize.quantity <= 0)) {
- return false;
- }
-
- // 统计总概率
- totalRate += parseFloat(prize.rate || 0);
- }
-
- // 验证总概率必须等于100%
- if (Math.abs(totalRate - 100) > 0.01) {
- return false;
- }
-
- return true;
- } catch (e) {
- return false;
- }
- }, '奖品数据不完整或格式错误,请检查:1.总概率必须等于100% 2.实物奖品数量必须大于0');
-
- // 添加自定义验证规则 - 验证规则JSON数据
- Nice.Validator.addRule('rulesJson', function(val, el) {
- try {
- var rules = JSON.parse(val || '{}');
-
- // 验证是否有规则
- if (!rules || Object.keys(rules).length === 0) {
- return false;
- }
-
- // 验证每个规则的基本字段
- for (var type in rules) {
- var rule = rules[type];
- if (!rule.type) {
- return false;
- }
-
- // 根据类型验证特定字段
- switch(parseInt(type)) {
- case 1: // 购买指定商品
- if (!rule.goods_ids || !Array.isArray(JSON.parse(rule.goods_ids || '[]'))) {
- return false;
- }
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- if (!rule.condition_value || parseFloat(rule.condition_value) <= 0) {
- return false;
- }
- break;
- }
- }
-
- return true;
- } catch (e) {
- return false;
- }
- }, '规则设置不完整或格式错误');
-
- // 添加自定义验证规则 - 验证条件JSON数据
- Nice.Validator.addRule('conditionsJson', function(val, el) {
- try {
- var conditions = JSON.parse(val || '{}');
-
- // 验证是否有条件
- if (!conditions || Object.keys(conditions).length === 0) {
- return false;
- }
-
- // 验证每个条件的基本字段
- for (var type in conditions) {
- var condition = conditions[type];
- if (!condition.type || condition.type != type) {
- return false;
- }
-
- // 根据类型验证特定字段
- switch(parseInt(type)) {
- case 1: // 购买指定商品
- var goodsIds = JSON.parse(condition.goods_ids || '[]');
- if (!goodsIds || goodsIds.length === 0) {
- return false;
- }
- if (!condition.goods_rule || (condition.goods_rule != 1 && condition.goods_rule != 2)) {
- return false;
- }
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- if (!condition.condition_value || parseFloat(condition.condition_value) <= 0) {
- return false;
- }
- break;
- }
- }
-
- return true;
- } catch (e) {
- return false;
- }
- }, '参与条件设置不完整或格式错误,请检查:1.购买指定商品需要选择商品 2.消费/充值条件需要输入有效金额');
- }
-
- // 监听表单提交事件
- $('form[role="form"]').on('submit', function(e) {
- console.log('表单提交开始');
-
- // 验证任务规则设置
- if (!Controller.api.validateTaskRules()) {
- e.preventDefault();
- return false;
- }
-
- // 收集并验证条件数据
- try {
- Controller.api.collectAndSaveRulesData();
-
- // 验证条件数据是否满足要求
- var conditionsData = Controller.api.rulesDataManager.getAllRules();
- if (!conditionsData || Object.keys(conditionsData).length === 0) {
- Toastr.error('请设置至少一种参与条件');
- e.preventDefault();
- return false;
- }
-
- console.log('条件数据验证通过:', conditionsData);
- } catch (error) {
- console.error('条件数据验证失败:', error);
- Toastr.error('参与条件设置有误:' + error.message);
- e.preventDefault();
- return false;
- }
-
- return true;
- });
- },
- // 初始化编辑页面
- initEditPage: function() {
- // 初始化基础UI组件
- Controller.api.initBasicUI();
-
- // 初始化奖品数据管理器
- Controller.api.prizesDataManager.init();
-
- // 初始化规则数据管理器
- Controller.api.rulesDataManager.init();
-
- // 初始化奖品管理
- Controller.api.initPrizeManagement();
-
- // 初始化任务规则管理
- Controller.api.initTaskRuleManagement();
-
- // 初始化已有的奖品数据
- Controller.api.initExistingPrizes();
-
- // 初始化已有的规则数据
- Controller.api.initExistingRules();
-
- // 初始化已有的条件数据
- Controller.api.initExistingConditions();
-
- // 确保所有概率输入框有正确的值
- setTimeout(function() {
- Controller.api.initDefaultPrizeRate();
- }, 100);
-
- // 初始化表单验证
- Controller.api.initFormValidation();
-
- console.log('编辑页面初始化完成');
- },
-
- // 同步DOM中现有的奖品数据到数据管理器
- syncExistingPrizesToDataManager: function() {
- console.log('开始同步DOM中现有的奖品数据到数据管理器');
-
- var existingPrizes = [];
-
- // 遍历DOM中现有的奖品项
- $('.prize-item').each(function(index) {
- var $item = $(this);
- var prizeData = Controller.api.extractPrizeDataFromDOM($item, index);
- if (prizeData) {
- existingPrizes.push(prizeData);
- console.log('提取到奖品数据:', prizeData);
- }
- });
-
- // 如果有奖品数据,同步到数据管理器
- if (existingPrizes.length > 0) {
- Controller.api.prizesDataManager.prizesData = existingPrizes;
- Controller.api.prizesDataManager.saveToHiddenField();
- console.log('已同步奖品数据到数据管理器,共', existingPrizes.length, '个奖品');
- } else {
- console.log('DOM中没有找到现有的奖品数据');
- }
- },
-
- // 从DOM中提取奖品数据
- extractPrizeDataFromDOM: function($item, index) {
- try {
- var isNoPrize = $item.attr('data-type') === 'no-prize';
- var prizeData = {
- id: $item.attr('data-prize-id') || ('prize_' + Date.now() + '_' + index),
- name: '',
- type: 1,
- image: '',
- quantity: 0,
- rate: 0
- };
-
- // 提取奖品名称
- if (isNoPrize) {
- // 系统默认未中奖项
- prizeData.name = $item.find('.prize-name-input').val() || $item.find('td:eq(1)').text().trim() || '谢谢参与';
- prizeData.type = parseInt($item.find('.prize-type-input').val() || 1);
- prizeData.image = $item.find('.prize-image-input').val() || '';
- // 如果隐藏域中没有图片,尝试从img标签获取(去掉CDN前缀)
- if (!prizeData.image) {
- var imgSrc = $item.find('.prize-image').attr('src') || '';
- if (imgSrc && typeof Fast !== 'undefined' && Fast.api && Fast.api.cdnurl) {
- // 去掉CDN前缀,获取相对路径
- prizeData.image = imgSrc.replace(/^https?:\/\/[^\/]+/, '');
- } else {
- prizeData.image = imgSrc;
- }
- }
- prizeData.quantity = 0; // 未中奖项数量固定为0
- prizeData.rate = parseFloat($item.find('.prize-rate').val() || $item.find('#no-prize-rate-input').val() || 50);
- } else {
- // 用户添加的奖品
- prizeData.name = $item.find('.prize-name').text().trim();
- prizeData.type = parseInt($item.find('.prize-type-input').val() || 2);
- prizeData.image = $item.find('.prize-image-input').val() || $item.find('.prize-image').attr('src') || '';
- prizeData.quantity = parseInt($item.find('.prize-quantity').val() || 1);
- prizeData.rate = parseFloat($item.find('.prize-rate').val() || 0);
- }
-
- // 根据奖品类型提取特定数据
- switch(prizeData.type) {
- case 3: // 积分
- prizeData.points = parseInt($item.find('.prize-points-input').val() || 0);
- break;
- case 4: // 余额
- prizeData.balance = parseFloat($item.find('.prize-balance-input').val() || 0);
- break;
- case 5: // 优惠券
- prizeData.coupon_id = $item.find('.prize-coupon-id-input').val();
- prizeData.couponId = prizeData.coupon_id;
- prizeData.coupon_name = $item.find('.prize-coupon-name').text() || '';
- break;
- case 6: // 红包
- prizeData.redpack_amount = parseFloat($item.find('.prize-redpack-input').val() || 0);
- break;
- case 7: // 兑换码
- prizeData.code_type = $item.find('.prize-code-type-input').val() || 'auto';
- prizeData.manual_codes = $item.find('.prize-manual-codes-input').val() || '';
- break;
- case 8: // 商城奖品
- prizeData.goods_id = $item.find('.prize-goods-id-input').val();
- prizeData.goodsId = prizeData.goods_id;
- prizeData.goods_name = $item.find('.prize-goods-name').text() || '';
- break;
- }
-
- console.log('提取奖品数据:', {
- index: index,
- isNoPrize: isNoPrize,
- extractedData: prizeData
- });
-
- return prizeData;
- } catch (e) {
- console.warn('提取奖品数据时出错:', e, $item);
- return null;
- }
- },
-
- // 初始化已有的奖品数据(重构版 - 使用数据管理器)
- initExistingPrizes: function() {
- // 直接从Config中获取奖品数据
- var existingPrizes = Controller.api.parseConfigJson('existingPrizes', []);
-
- // 检查是否有后台传递的奖品数据
- if (existingPrizes && existingPrizes.length > 0) {
- console.log('正在初始化已有奖品数据,共', existingPrizes.length, '个奖品');
-
- // 处理奖品数据,确保格式正确
- var processedPrizes = [];
- for (var i = 0; i < existingPrizes.length; i++) {
- var prize = existingPrizes[i];
- var processedPrize = {
- id: prize.id || ('prize_' + Date.now() + '_' + i),
- name: prize.name || '',
- type: parseInt(prize.type) || 1,
- image: prize.image || '',
- description: prize.description || '',
- quantity: parseInt(prize.quantity) || 0,
- rate: parseFloat(prize.rate) || 0,
- sort_order: parseInt(prize.sort_order) || i
- };
-
- // 根据奖品类型设置特定字段
- switch (processedPrize.type) {
- case 3: // 积分
- processedPrize.points = parseInt(prize.points) || 0;
- break;
- case 4: // 余额
- processedPrize.balance = parseFloat(prize.balance) || 0;
- break;
- case 5: // 优惠券
- processedPrize.coupon_id = prize.coupon_id || '';
- processedPrize.coupon_name = prize.coupon_name || '';
- break;
- case 6: // 红包
- processedPrize.redpack_amount = parseFloat(prize.redpack_amount) || 0;
- break;
- case 7: // 兑换码
- processedPrize.code_type = prize.code_type || 'auto';
- processedPrize.manual_codes = prize.manual_codes || '';
- break;
- case 8: // 商城奖品
- processedPrize.goods_id = prize.goods_id || '';
- processedPrize.goods_name = prize.goods_name || '';
- break;
- }
-
- processedPrizes.push(processedPrize);
- }
-
- // 将处理后的奖品数据加载到数据管理器
- Controller.api.prizesDataManager.prizesData = processedPrizes;
- Controller.api.prizesDataManager.saveToHiddenField();
-
- // 重新构建奖品列表
- Controller.api.rebuildPrizeList();
-
- // 更新奖品计数和概率统计
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
-
- console.log('奖品数据初始化完成,数据管理器已同步,共', processedPrizes.length, '个奖品');
- } else {
- console.log('编辑页面没有找到已有的奖品数据');
- }
- },
-
- // 初始化已有的规则数据
- initExistingRules: function() {
- // 直接从Config中获取规则数据
- var existingRulesData = Controller.api.parseConfigJson('existingRulesData', {});
-
- // 检查是否有后台传递的规则数据
- if (existingRulesData && Object.keys(existingRulesData).length > 0) {
- console.log('正在初始化已有规则数据:', existingRulesData);
-
- // 将已有规则数据加载到数据管理器
- Controller.api.rulesDataManager.rulesData = existingRulesData;
- Controller.api.rulesDataManager.saveToHiddenField();
-
- // 根据规则数据设置任务类型选择状态
- Controller.api.renderTaskTypesFromRules(existingRulesData);
-
- console.log('规则数据初始化完成');
- } else {
- console.log('没有找到已有的规则数据');
- }
- },
-
- // 根据规则数据渲染任务类型选择
- renderTaskTypesFromRules: function(rulesData) {
- console.log('根据规则数据渲染任务类型选择:', rulesData);
-
- // 取消所有任务类型的选中状态
- $('input[name="row[task_type][]"]').prop('checked', false);
-
- // 隐藏所有任务设置项
- $('.task-setting-item').hide();
-
- // 遍历规则数据,设置对应的任务类型
- for (var type in rulesData) {
- var rule = rulesData[type];
- var taskType = parseInt(type);
-
- // 勾选对应的任务类型
- var checkbox = $('input[name="row[task_type][]"][value="' + taskType + '"]');
- if (checkbox.length > 0) {
- checkbox.prop('checked', true);
-
- // 显示对应的任务设置
- $('#task-setting-' + taskType).show();
-
- // 根据任务类型设置具体的数据
- Controller.api.renderTaskSettingData(taskType, rule);
- }
- }
-
- // 更新复选框样式
- Controller.api.handleTaskTypeChange();
- },
-
- // 渲染任务设置数据
- renderTaskSettingData: function(taskType, ruleData) {
- console.log('渲染任务设置数据:', taskType, ruleData);
-
- switch (parseInt(taskType)) {
- case 1: // 购买指定商品
- // 设置商品规则
- if (ruleData.goods_rule) {
- $('input[name="condition[' + taskType + '][goods_rule]"][value="' + ruleData.goods_rule + '"]').prop('checked', true);
- Controller.api.updateGoodsRuleDisplay($('input[name="condition[' + taskType + '][goods_rule]"]:checked'));
- }
-
- // 设置商品选择
- if (ruleData.goods_ids) {
- var goodsIds = JSON.parse(ruleData.goods_ids || '[]');
- if (goodsIds.length > 0) {
- // 更新隐藏字段
- $('#task-goods-ids-' + taskType).val(ruleData.goods_ids);
-
- // 调用商品信息API来渲染商品列表
- Controller.api.loadAndRenderTaskGoods(taskType, goodsIds);
- }
- }
- break;
-
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- // 设置条件值
- if (ruleData.condition_value) {
- var amountInput = $('input[name="condition[' + taskType + '][condition_value]"]');
- if (amountInput.length > 0) {
- amountInput.val(ruleData.condition_value);
- }
- }
- break;
- }
- },
-
- // 加载并渲染任务商品
- loadAndRenderTaskGoods: function(taskType, goodsIds) {
- if (!goodsIds || goodsIds.length === 0) return;
-
- console.log('加载任务商品数据:', taskType, goodsIds);
-
- // 调用商品信息API
- $.ajax({
- url: Fast.api.fixurl('shop/goods/getGoodsByIds'),
- type: 'POST',
- data: {
- ids: goodsIds.join(',')
- },
- dataType: 'json',
- success: function(ret) {
- if (ret.code === 1 && ret.data && ret.data.length > 0) {
- // 更新商品显示
- Controller.api.updateSelectedGoods(ret.data, {
- container: '#selected-goods',
- template: 'goods-list-template'
- });
-
- // 绑定删除事件
- Controller.api.bindTaskGoodsEvents();
-
- console.log('任务商品数据渲染完成:', ret.data);
- } else {
- console.warn('加载任务商品数据失败:', ret);
- // 显示友好的错误提示
- $('#selected-goods').html(
- '<div class="alert alert-warning" style="margin-top: 10px;">' +
- '<i class="fa fa-warning"></i> 部分商品数据加载失败,请重新选择商品' +
- '</div>'
- );
- }
- },
- error: function(xhr, status, error) {
- console.error('加载任务商品数据失败:', error);
- $('#selected-goods').html(
- '<div class="alert alert-danger" style="margin-top: 10px;">' +
- '<i class="fa fa-exclamation-circle"></i> 商品数据加载失败,请检查网络连接' +
- '</div>'
- );
- }
- });
- },
-
- // 初始化已有的条件数据(已合并到initExistingRules中)
- initExistingConditions: function() {
- console.log('条件数据初始化已合并到规则数据管理器中');
- },
-
-
-
- // 验证任务规则设置
- 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() {
- console.log('初始化奖品管理模块');
-
- // 初始化拖拽排序
- Controller.api.initPrizeSort();
-
- // 初始化概率计算
- Controller.api.updateTotalRate();
-
- // 绑定奖品相关事件
- Controller.api.bindPrizeEvents();
-
- // 初始化表单验证
- Controller.api.initPrizeFormValidation();
-
- console.log('奖品管理模块初始化完成');
- },
-
- // 添加奖品
- addPrize: function() {
- var totalCount = $('.prize-item').length; // 总奖品数
- var maxCount = 10; // 最多10个奖品
-
- if (totalCount >= maxCount) {
- Toastr.error('最多只能添加' + maxCount + '个奖品');
- return;
- }
-
- // 使用通用表单,添加模式
- Controller.api.openPrizeForm({
- mode: 'add',
- title: '添加奖品'
- });
- },
-
- // 初始化奖品表单验证
- initPrizeFormValidation: function() {
- console.log('初始化奖品表单验证');
-
- // FastAdmin使用Nice-validator,验证规则通过data-rule属性定义
- // 无需额外的自定义验证方法,表单验证会在Form.api.bindevent中自动处理
- console.log('FastAdmin表单验证已通过data-rule属性配置');
- },
-
- // 通用奖品表单 - 重构版
- openPrizeForm: function(options) {
- var defaults = {
- mode: 'add', // 'add' 或 'edit'
- title: '奖品表单',
- prizeItem: null,
- 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,
- prizeTypes: prizeTypes,
- selectedType: selectedType
- });
-
- // 弹出表单
- Layer.open({
- type: 1,
- title: config.title,
- area: isEditMode ? ['80%', '80%'] : ['80%', '80%'],
- content: formHtml,
- btn: [isEditMode ? '保存' : '确定', '取消'],
- success: function(layero, index) {
- var $form = layero.find('.prize-form');
-
- // 初始化FastAdmin表单组件
- Form.api.bindevent($form);
-
- // 编辑模式需要设置表单数据
- if (isEditMode) {
- Controller.api.setFormData($form, config);
- } else {
- // 添加模式:设置默认奖品类型并触发相应逻辑
- var defaultType = selectedType || 2; // 默认实物奖品
- $form.find('input[name="row[prize_type]"][value="' + defaultType + '"]').prop('checked', true);
-
- // 设置默认图片
- Controller.api.setPrizeDefaultImage($form, defaultType);
-
- // 触发奖品类型改变事件
- $form.find('input[name="row[prize_type]"]').trigger('change');
- }
-
- // 设置正确的字数统计初始值
- var currentName = $form.find('input[name="prize_name"]').val();
- var currentLength = currentName ? currentName.length : 0;
- $form.find('#prize-name-count').text(currentLength + '/20');
-
- // 绑定自定义事件
- Controller.api.bindPrizeFormEvents($form, config);
-
- // 初始化字数统计
- Controller.api.initNameCounter($form);
-
- // 优化表单样式,使其更紧凑
- Controller.api.optimizePrizeFormStyle($form);
-
- console.log('奖品表单初始化完成');
- },
- yes: function(index, layero) {
- var $form = layero.find('.prize-form');
-
- var success = false;
- if (isEditMode) {
- success = Controller.api.updatePrize($form, config);
- } else {
- success = Controller.api.savePrize($form);
- }
-
- if (success) {
- Layer.close(index);
- }
-
- // 如果验证失败,success会是false,Layer不会关闭
- return success;
- }
- });
- },
-
- // 设置默认表单数据(添加模式)
- setDefaultFormData: function($form, config) {
- console.log('设置默认表单数据');
-
- // 设置默认奖品类型
- var defaultType = config.data.type || 2;
- $form.find('input[name="row[prize_type]"][value="' + defaultType + '"]').prop('checked', true);
-
- // 设置默认图片
- Controller.api.setPrizeDefaultImage($form, defaultType);
-
- // 初始化图片上传组件
- Controller.api.initImageUpload($form);
-
- // 触发奖品类型改变事件
- $form.find('input[name="row[prize_type]"]').trigger('change');
-
- console.log('默认表单数据设置完成');
- },
-
- // 初始化名称字符计数
- initNameCounter: function($form) {
- var $nameInput = $form.find('input[name="prize_name"]');
- var $counter = $form.find('#prize-name-count');
-
- // 初始化计数
- var currentLength = $nameInput.val().length;
- $counter.text(currentLength + '/20');
-
- // 绑定输入事件
- $nameInput.on('input', function() {
- var length = $(this).val().length;
- $counter.text(length + '/20');
- });
- },
-
- // 优化奖品表单样式,使其更紧凑
- optimizePrizeFormStyle: function($form) {
- // 减少表单组的间距
- $form.find('.form-group').css({
- 'margin-bottom': '15px'
- });
-
- // 减少奖励设置区域的间距
- $form.find('.reward-group').css({
- 'margin-bottom': '10px'
- });
-
- // 减少表单区块的间距
- $form.find('.form-section').css({
- 'margin-bottom': '20px'
- });
-
- // 减少帮助文本的上边距
- $form.find('.help-block').css({
- 'margin-top': '5px',
- 'margin-bottom': '0px'
- });
-
- // 优化警告框的间距
- $form.find('.alert').css({
- 'margin-top': '10px',
- 'margin-bottom': '10px',
- 'padding': '10px'
- });
-
- // 减少图片预览区域的间距
- $form.find('.plupload-preview').css({
- 'margin-top': '10px'
- });
-
- console.log('表单样式优化完成');
- },
-
- // 初始化图片上传组件
- initImageUpload: function($form) {
- console.log('初始化图片上传组件');
-
- // 使用FastAdmin的Form组件来重新初始化表单内的上传组件
- Form.api.bindevent($form);
-
- // 绑定图片输入框的变化事件,实现预览功能
- $form.find('input[name="prize_image"]').on('change', function() {
- var imageUrl = $(this).val();
- if (imageUrl) {
- // 生成预览HTML
- var previewHtml = '<li class="col-xs-3">' +
- '<img src="' + (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(imageUrl) : imageUrl) + '" ' +
- 'class="img-responsive img-thumbnail" style="max-width: 100px; max-height: 100px;">' +
- '</li>';
-
- // 更新预览区域
- $form.find('#p-prize-image').html(previewHtml);
- } else {
- // 清空预览
- $form.find('#p-prize-image').empty();
- }
- });
-
- console.log('图片上传组件初始化完成');
- },
-
- // 设置表单数据(编辑模式) - 重构版
- setFormData: function($form, config) {
- console.log('设置编辑表单数据', config.data);
- 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 || '1');
- $form.find('input[name="prize_rate"]').val(parseFloat(data.rate || 0).toFixed(2));
-
- // 设置奖品类型
- $form.find('input[name="row[prize_type]"][value="' + data.type + '"]').prop('checked', true);
-
- // 根据奖品类型处理特殊字段
- switch(parseInt(data.type)) {
- case 3: // 积分
- if (data.points) {
- $form.find('input[name="reward_value_integral"]').val(data.points);
- }
- break;
- case 4: // 余额
- if (data.balance) {
- $form.find('input[name="reward_value_balance"]').val(data.balance);
- }
- break;
- case 5: // 优惠券
- // 支持两种字段名格式
- var couponId = data.couponId || data.coupon_id;
- if (couponId) {
- $form.find('input[name="coupon_id"]').val(couponId);
- Controller.api.loadCouponInfo($form, couponId);
- }
- break;
- case 6: // 红包
- if (data.redpack_amount) {
- $form.find('input[name="reward_value_redpack"]').val(data.redpack_amount);
- }
- break;
- case 7: // 兑换码
- if (data.code_type) {
- $form.find('input[name="code_type"][value="' + data.code_type + '"]').prop('checked', true);
- }
- if (data.manual_codes) {
- $form.find('textarea[name="manual_codes"]').val(data.manual_codes);
- }
- break;
- case 8: // 商城奖品
- // 支持两种字段名格式
- var goodsId = data.goodsId || data.goods_id;
- if (goodsId) {
- $form.find('input[name="goods_id"]').val(goodsId);
- Controller.api.loadGoodsInfo($form, goodsId);
- }
- break;
- }
-
- // 触发奖品类型改变事件以显示对应的奖励设置
- $form.find('input[name="row[prize_type]"]').trigger('change');
-
- // 初始化图片上传组件
- Controller.api.initImageUpload($form);
-
- // 触发图片预览更新
- if (data.image) {
- $form.find('input[name="prize_image"]').trigger('change');
- }
-
- console.log('编辑表单数据设置完成');
- },
-
- // 绑定奖品表单事件 - 重构版
- bindPrizeFormEvents: function($form, config) {
- console.log('绑定奖品表单事件');
- var isEditMode = config && config.mode === 'edit';
-
- // 奖品类型切换事件
- $form.find('input[name="row[prize_type]"]').off('change.prizeType').on('change.prizeType', function() {
- var type = parseInt($(this).val());
- console.log('奖品类型切换至:', type);
-
- // 显示/隐藏对应的奖励设置
- Controller.api.toggleRewardSettings($form, type);
-
- // 非编辑模式时设置默认图片
- if (!isEditMode) {
- Controller.api.setPrizeDefaultImage($form, type);
- }
- });
-
- // 商品选择按钮
- $form.find('#select-goods-btn').off('click.selectGoods').on('click.selectGoods', function() {
- Controller.api.openGoodsSelector($form);
- });
-
- // 优惠券选择按钮
- $form.find('#select-coupon-btn').off('click.selectCoupon').on('click.selectCoupon', function() {
- Controller.api.openCouponSelector($form);
- });
-
- // 兑换码类型切换
- $form.find('input[name="code_type"]').off('change.codeType').on('change.codeType', function() {
- var codeType = $(this).val();
- Controller.api.toggleManualCodesInput($form, codeType);
- });
-
- // 概率输入框格式化
- $form.find('input[name="prize_rate"]').off('blur.rateFormat').on('blur.rateFormat', function() {
- var value = parseFloat($(this).val()) || 0;
- $(this).val(value.toFixed(2));
- });
-
- // 删除选中项事件
- $form.find('.selected-display').off('click.removeItem').on('click.removeItem', '.remove-item', function() {
- var $item = $(this).closest('.selected-item');
- var $hiddenInput = $item.siblings('input[type="hidden"]');
-
- $item.remove();
- $hiddenInput.val('');
- });
-
- console.log('奖品表单事件绑定完成');
- },
-
- // 切换奖励设置显示
- toggleRewardSettings: function($form, type) {
- console.log('切换奖励设置显示:', type);
-
- // 隐藏所有奖励设置
- $form.find('.reward-group').removeClass('active').hide();
-
- // 根据类型显示对应的设置
- var rewardType = '';
- switch(parseInt(type)) {
- case 3:
- rewardType = 'integral';
- break;
- case 4:
- rewardType = 'balance';
- break;
- case 5:
- rewardType = 'coupon';
- break;
- case 6:
- rewardType = 'redpack';
- break;
- case 7:
- rewardType = 'code';
- break;
- case 8:
- rewardType = 'goods';
- break;
- }
-
- if (rewardType) {
- $form.find('.reward-group[data-type="' + rewardType + '"]').addClass('active').show();
- }
- },
-
- // 切换手动兑换码输入
- toggleManualCodesInput: function($form, codeType) {
- var $container = $form.find('.manual-codes-container');
- if (codeType === 'manual') {
- $container.show();
- } else {
- $container.hide();
- }
- },
-
-
- // 设置奖品默认图片
- setPrizeDefaultImage: function(form, type) {
- // 从后台配置获取默认图片
- var defaultImages = Controller.api.parseConfigJson('prizeDefaultImages', {});
- var defaultImage = defaultImages[type] || '/assets/img/default.png';
-
- // 设置图片路径并触发change事件以更新预览
- 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);
-
- // 设置商品图片为奖品图片并触发预览更新
- if (goods.image) {
- 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($form) {
- console.log('开始保存奖品');
-
- // 收集表单数据
- var prizeData = Controller.api.collectPrizeFormData($form);
- if (!prizeData) {
- return false; // 验证失败
- }
-
- // 使用数据管理器添加奖品
- var prizeId = Controller.api.prizesDataManager.addPrize(prizeData);
-
- // 添加奖品到显示列表(追加模式,不会覆盖现有奖品)
- Controller.api.appendPrizeToList(prizeData);
-
- // 更新相关统计
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
-
- console.log('奖品保存成功:', prizeData, '奖品ID:', prizeId);
- return true;
- },
-
- // 收集奖品表单数据
- collectPrizeFormData: function($form) {
- console.log('收集奖品表单数据');
-
- var name = $form.find('input[name="prize_name"]').val().trim();
- var type = parseInt($form.find('input[name="row[prize_type]"]:checked').val());
- var image = $form.find('input[name="prize_image"]').val();
- var quantity = parseInt($form.find('input[name="prize_quantity"]').val()) || 1;
- var rate = parseFloat($form.find('input[name="prize_rate"]').val()) || 0;
-
- // 基础验证 - FastAdmin的data-rule已经处理了大部分验证
- // 这里只做简单的空值检查,具体验证错误会由Nice-validator显示
- if (!name) {
- Toastr.error('请输入奖品名称');
- return null;
- }
- if (!type) {
- Toastr.error('请选择奖品类型');
- return null;
- }
- if (!image) {
- Toastr.error('请选择奖品图片');
- return null;
- }
-
- // 构建奖品数据
- var prizeData = {
- name: name,
- type: type,
- image: image,
- quantity: Controller.api.isNoPrizeType(type) ? 0 : quantity,
- rate: rate
- };
-
- // 根据奖品类型收集特定数据
- switch(type) {
- case 3: // 积分
- prizeData.points = parseInt($form.find('input[name="reward_value_integral"]').val()) || 0;
- break;
- case 4: // 余额
- prizeData.balance = parseFloat($form.find('input[name="reward_value_balance"]').val()) || 0;
- break;
- case 5: // 优惠券
- prizeData.coupon_id = $form.find('input[name="coupon_id"]').val();
- prizeData.couponId = prizeData.coupon_id; // 为模板提供一致的字段名
- // 从优惠券显示区域获取名称
- prizeData.coupon_name = $form.find('#selected-coupon-display').text().trim() ||
- $form.find('.selected-coupon-item span:first').text() || '';
- break;
- case 6: // 红包
- prizeData.redpack_amount = parseFloat($form.find('input[name="reward_value_redpack"]').val()) || 0;
- break;
- case 7: // 兑换码
- prizeData.code_type = $form.find('input[name="code_type"]:checked').val() || 'auto';
- if (prizeData.code_type === 'manual') {
- prizeData.manual_codes = $form.find('textarea[name="manual_codes"]').val() || '';
- }
- break;
- case 8: // 商城奖品
- prizeData.goods_id = $form.find('input[name="goods_id"]').val();
- prizeData.goodsId = prizeData.goods_id; // 为模板提供一致的字段名
- // 从商品显示区域获取名称
- prizeData.goods_name = $form.find('#selected-goods-display .goods-name-display').text() ||
- $form.find('#selected-goods-display .prize-goods-item .goods-name-display').text() ||
- $form.find('.prize-goods-item .goods-name-display').text() || '';
- break;
- }
-
- console.log('收集到的奖品数据:', prizeData);
- return prizeData;
- },
-
- // 统一的奖品数据处理方法
- processPrizeData: function(formData) {
- var prizeData = {
- name: formData.name || '',
- type: parseInt(formData.type) || 1,
- image: formData.image || '',
- description: formData.description || '',
- quantity: parseInt(formData.quantity) || 0,
- rate: parseFloat(formData.rate) || 0
- };
-
- // 未中奖项的特殊处理
- if (prizeData.type === 1) {
- prizeData.quantity = 0;
- prizeData.rate = prizeData.rate || 50; // 默认50%概率
- }
-
- // 根据奖品类型设置特定字段
- switch (prizeData.type) {
- case 3: // 积分
- prizeData.points = parseInt(formData.points) || 0;
- break;
- case 4: // 余额
- prizeData.balance = parseFloat(formData.balance) || 0;
- break;
- case 5: // 优惠券
- prizeData.coupon_id = formData.coupon_id || '';
- prizeData.coupon_name = formData.coupon_name || '';
- break;
- case 6: // 红包
- prizeData.redpack_amount = parseFloat(formData.redpack_amount) || 0;
- break;
- case 7: // 兑换码
- prizeData.code_type = formData.code_type || 'auto';
- prizeData.manual_codes = formData.manual_codes || '';
- break;
- case 8: // 商城奖品
- prizeData.goods_id = formData.goods_id || '';
- prizeData.goods_name = formData.goods_name || '';
- break;
- }
-
- return prizeData;
- },
-
- // 添加奖品到列表(编辑模式用)
- addPrizeToList: function(prize, index) {
- // 获取奖品类型信息
- var typeName = Controller.api.getPrizeTypeName(prize.type);
- var labelClass = Controller.api.getPrizeLabelClass(prize.type);
- var rewardText = Controller.api.getPrizeRewardText(prize);
-
- // 使用传入的索引
- var prizeIndex = typeof index !== 'undefined' ? index : $('.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,用于显示
-
- // 生成唯一的奖品ID
- var prizeId = prize.id || ('prize_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9));
-
- // 使用外部模板 - 重构为仅展示用途
- var prizeHtml = Template('prize-item-template', {
- index: prizeIndex,
- prizeId: prizeId,
- prizeType: prize.type, // 直接使用奖品类型
- name: prize.name, // 奖品名称
- description: prize.description || '', // 奖品描述
- type: prize.type, // 奖品类型
- typeName: typeName, // 类型显示名称
- labelClass: labelClass, // 标签样式类
- rewardText: rewardText, // 奖励文本
- imageUrl: imageDisplay, // CDN URL,用于显示
- quantity: prize.quantity || 0, // 奖品数量
- showQuantity: !Controller.api.isNoPrizeType(prize.type), // 是否显示数量
- rate: parseFloat(prize.rate || 0).toFixed(2), // 确保概率值格式化为两位小数
- isSystemPrize: false // 移除系统奖品概念
- });
-
- $('.prize-list').append(prizeHtml);
-
- console.log('已添加奖品到列表:', prize.name, '类型:', typeName);
- },
-
- // 添加奖品到列表(新增模式用)- 重构版
- appendPrizeToList: function(prize) {
- // 获取奖品类型信息
- var typeName = Controller.api.getPrizeTypeName(prize.type);
- var labelClass = Controller.api.getPrizeLabelClass(prize.type);
- var rewardText = Controller.api.getPrizeRewardText(prize);
-
- // 获取当前奖品索引,确保与数据管理器中的索引一致
- var prizeIndex = Controller.api.prizesDataManager.prizesData.length - 1;
-
- // 处理图片URL
- var imageDisplay = prize.image ? (typeof Fast !== 'undefined' && Fast.api ? Fast.api.cdnurl(prize.image) : prize.image) : '';
-
- // 生成唯一的奖品ID
- var prizeId = prize.id || ('prize_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9));
-
- // 使用外部模板 - 重构版(仅用于展示)
- var prizeHtml = Template('prize-item-template', {
- index: prizeIndex,
- prizeId: prizeId,
- prizeType: prize.type, // 奖品类型
- name: prize.name, // 奖品名称
- description: '', // 奖品描述(新增模式通常为空)
- type: prize.type, // 奖品类型
- typeName: typeName, // 类型显示名称
- labelClass: labelClass, // 标签样式类
- rewardText: rewardText, // 奖励文本
- imageUrl: imageDisplay, // CDN URL,用于显示
- quantity: prize.quantity || 0, // 奖品数量
- showQuantity: !Controller.api.isNoPrizeType(prize.type), // 是否显示数量
- rate: parseFloat(prize.rate || 0).toFixed(2), // 确保概率值格式化为两位小数
- isSystemPrize: false // 移除系统奖品概念
- });
-
- $('.prize-list').append(prizeHtml);
-
- // 重新初始化拖拽排序
- Controller.api.initPrizeSort();
-
- console.log('奖品已追加到列表,索引:', prizeIndex, '数据:', prize);
- },
-
-
- // 初始化默认奖品概率值
- initDefaultPrizeRate: function() {
- console.log('=== 开始初始化奖品概率值 ===');
-
- // 确保所有奖品概率输入框都有默认值
- $('.prize-rate').each(function() {
- var $this = $(this);
- var currentValue = $this.val();
- if (!currentValue || currentValue === '') {
- $this.val('0.00'); // 所有奖品默认概率为0
- }
- });
-
- // 初始化后更新总概率显示
- Controller.api.updateTotalRate();
-
- console.log('=== 奖品概率值初始化完成 ===');
- },
-
- // 绑定奖品相关事件(使用事件委托)
- bindPrizeEvents: function() {
- // 使用事件委托,避免重复绑定
- $(document).off('input.prizeManagement change.prizeManagement click.prizeManagement');
-
- // 概率输入框事件
- $(document).on('input.prizeManagement', '.prize-rate', function() {
- var $item = $(this).closest('.prize-item');
- var index = parseInt($item.attr('data-index'));
- var rate = parseFloat($(this).val()) || 0;
-
- // 更新数据管理器中的数据
- Controller.api.prizesDataManager.updatePrizeRate(index, rate);
-
- // 实时更新总概率
- Controller.api.updateTotalRate();
- });
-
- $(document).on('change.prizeManagement', '.prize-rate', function() {
- // 失去焦点时格式化为两位小数
- var value = parseFloat($(this).val()) || 0;
- $(this).val(value.toFixed(2));
- Controller.api.updateTotalRate();
- });
-
- // 奖品数量输入框事件
- $(document).on('input.prizeManagement change.prizeManagement', '.prize-quantity', function() {
- var $item = $(this).closest('.prize-item');
- var index = parseInt($item.attr('data-index'));
- var quantity = parseInt($(this).val()) || 0;
-
- // 更新数据管理器中的数据
- Controller.api.prizesDataManager.updatePrizeQuantity(index, quantity);
- });
-
- // 删除奖品按钮事件
- $(document).on('click.prizeManagement', '.delete-prize', function() {
- var $item = $(this).closest('.prize-item');
- var index = parseInt($item.attr('data-index'));
-
- // 直接删除奖品,不再有系统默认项的限制
- Controller.api.deletePrizeByIndex(index);
- });
-
- // 编辑奖品按钮事件
- $(document).on('click.prizeManagement', '.edit-prize', function() {
- var $item = $(this).closest('.prize-item');
- var index = parseInt($item.attr('data-index'));
- Controller.api.editPrizeByIndex(index);
- });
- },
-
- // 通过索引删除奖品
- deletePrizeByIndex: function(index) {
- // 从数据管理器中删除
- if (Controller.api.prizesDataManager.deletePrize(index)) {
- // 重新构建列表
- Controller.api.rebuildPrizeList();
-
- // 更新统计
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
-
- console.log('奖品已删除,索引:', index);
- }
- },
-
- // 通过索引编辑奖品
- editPrizeByIndex: function(index) {
- var prizeData = Controller.api.prizesDataManager.getPrize(index);
- if (!prizeData) {
- Toastr.error('奖品数据不存在');
- return;
- }
-
- // 使用通用表单,编辑模式
- Controller.api.openPrizeForm({
- mode: 'edit',
- title: '编辑奖品',
- prizeIndex: index,
- data: prizeData
- });
- },
-
- // 重新构建奖品列表
- rebuildPrizeList: function() {
- // 清空现有列表
- $('.prize-list').empty();
-
- // 获取所有奖品数据
- var allPrizes = Controller.api.prizesDataManager.getAllPrizes();
-
- // 重新渲染每个奖品
- for (var i = 0; i < allPrizes.length; i++) {
- Controller.api.addPrizeToList(allPrizes[i], i);
- }
-
- // 重新初始化拖拽排序
- Controller.api.initPrizeSort();
-
- console.log('奖品列表已重新构建,共', allPrizes.length, '个奖品');
- },
-
- // 奖品数据管理 - 使用单一JSON隐藏域
- prizesDataManager: {
- // 奖品数据数组
- prizesData: [],
-
- // 初始化奖品数据管理器
- init: function() {
- // 创建奖品数据隐藏域
- if ($('#prizes-data-json').length === 0) {
- $('<input>').attr({
- type: 'hidden',
- id: 'prizes-data-json',
- name: 'prizes_json',
- value: '[]',
- 'data-rule': 'required;prizesJson',
- 'data-msg-required': '请添加至少一个奖品',
- 'data-msg-prizesJson': '奖品数据格式不正确'
- }).appendTo('form[role="form"]');
- }
-
- // 初始化数据
- this.loadFromHiddenField();
- },
-
- // 验证奖品数据
- validatePrizeData: function(prizeData) {
- if (!prizeData.name || prizeData.name.trim() === '') {
- throw new Error('奖品名称不能为空');
- }
-
- if (!prizeData.type || !Controller.api.getAvailablePrizeTypes()[prizeData.type]) {
- throw new Error('请选择正确的奖品类型');
- }
-
- if (prizeData.type != 1 && (!prizeData.quantity || prizeData.quantity <= 0)) {
- throw new Error('奖品数量必须大于0');
- }
-
- if (prizeData.rate < 0 || prizeData.rate > 100) {
- throw new Error('中奖概率必须在0-100之间');
- }
-
- return true;
- },
-
- // 从隐藏域加载数据
- loadFromHiddenField: function() {
- var jsonData = $('#prizes-data-json').val();
- try {
- this.prizesData = JSON.parse(jsonData || '[]');
- } catch (e) {
- this.prizesData = [];
- console.warn('奖品数据格式错误,已重置为空数组');
- }
- },
-
- // 保存数据到隐藏域
- saveToHiddenField: function() {
- var jsonData = JSON.stringify(this.prizesData);
- $('#prizes-data-json').val(jsonData);
- console.log('奖品数据已保存到隐藏域:', this.prizesData);
- },
-
- // 添加奖品
- addPrize: function(prizeData) {
- // 验证奖品数据
- this.validatePrizeData(prizeData);
-
- // 生成唯一ID
- prizeData.id = 'prize_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
-
- // 设置默认值
- prizeData.description = prizeData.description || '';
- prizeData.sort_order = this.prizesData.length;
-
- this.prizesData.push(prizeData);
- this.saveToHiddenField();
- return prizeData.id;
- },
-
- // 更新奖品
- updatePrize: function(index, prizeData) {
- if (index >= 0 && index < this.prizesData.length) {
- // 验证奖品数据
- this.validatePrizeData(prizeData);
-
- // 保持原有ID和排序
- prizeData.id = this.prizesData[index].id;
- prizeData.sort_order = this.prizesData[index].sort_order;
-
- // 设置默认值
- prizeData.description = prizeData.description || '';
-
- this.prizesData[index] = prizeData;
- this.saveToHiddenField();
- return true;
- }
- return false;
- },
-
- // 删除奖品
- deletePrize: function(index) {
- if (index >= 0 && index < this.prizesData.length) {
- this.prizesData.splice(index, 1);
- this.saveToHiddenField();
- return true;
- }
- return false;
- },
-
- // 获取奖品数据
- getPrize: function(index) {
- if (index >= 0 && index < this.prizesData.length) {
- return this.prizesData[index];
- }
- return null;
- },
-
- // 获取所有奖品数据
- getAllPrizes: function() {
- return this.prizesData;
- },
-
- // 更新奖品数量
- updatePrizeQuantity: function(index, quantity) {
- if (index >= 0 && index < this.prizesData.length) {
- this.prizesData[index].quantity = parseInt(quantity) || 0;
- this.saveToHiddenField();
- return true;
- }
- return false;
- },
-
- // 更新奖品概率
- updatePrizeRate: function(index, rate) {
- if (index >= 0 && index < this.prizesData.length) {
- this.prizesData[index].rate = parseFloat(rate) || 0;
- this.saveToHiddenField();
- return true;
- }
- return false;
- },
-
- // 重新排序奖品
- reorderPrizes: function(newOrder) {
- var reorderedData = [];
- for (var i = 0; i < newOrder.length; i++) {
- var oldIndex = newOrder[i];
- if (oldIndex >= 0 && oldIndex < this.prizesData.length) {
- reorderedData.push(this.prizesData[oldIndex]);
- }
- }
- this.prizesData = reorderedData;
- this.saveToHiddenField();
- }
- },
-
- // 实时更新奖品隐藏域数据(重构版 - 使用奖品数据管理器)
- updatePrizeHiddenFields: function() {
- // 使用奖品数据管理器保存数据
- Controller.api.prizesDataManager.saveToHiddenField();
- },
-
- // 初始化奖品拖拽排序 - 重构版
- 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.updatePrizeOrderFromDOM();
- }
- });
- }
- });
- },
-
- // 从DOM更新奖品顺序到数据管理器
- updatePrizeOrderFromDOM: function() {
- var newOrder = [];
- $('.prize-list .prize-item').each(function(index) {
- var oldIndex = parseInt($(this).attr('data-index'));
- if (!isNaN(oldIndex)) {
- newOrder.push(oldIndex);
- }
- });
-
- // 重新排序数据管理器中的数据
- Controller.api.prizesDataManager.reorderPrizes(newOrder);
-
- // 重新构建列表以更新索引
- Controller.api.rebuildPrizeList();
-
- console.log('奖品拖拽排序完成,新顺序:', newOrder);
- },
-
- // 获取奖品类型名称
- getPrizeTypeName: function(type) {
- var prizeTypeMap = Controller.api.parseConfigJson('prizeTypeList', {});
- return prizeTypeMap[type] || '未知';
- },
-
- // 获取可用的奖品类型(显示所有奖品类型)
- getAvailablePrizeTypes: function() {
- // 返回所有奖品类型,不再限制
- return Controller.api.parseConfigJson('prizeTypeList', {});
- },
-
- // 获取奖品标签样式类
- 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').text().trim() ||
- form.find('.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() ||
- form.find('#selected-goods-display .prize-goods-item .goods-name-display').text() ||
- form.find('.prize-goods-item .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';
- }
- },
-
- // 判断是否为未中奖类型
- isNoPrizeType: function(type, element) {
- var typeValue = parseInt(type);
- var isNoPrizeByType = typeValue === 1;
- var isNoPrizeByAttr = element && $(element).attr('data-type') === 'no-prize';
-
- return isNoPrizeByType || isNoPrizeByAttr;
- },
-
- // 更新奖品数量统计
- updatePrizeCount: function() {
- // 从数据管理器获取准确的奖品数量
- var totalCount = Controller.api.prizesDataManager.prizesData.length;
-
- console.log('updatePrizeCount - 总奖品数:', totalCount);
-
- // 显示总奖品数
- $('#prize-count').text(totalCount);
-
- // 更新添加奖品按钮状态
- Controller.api.updateAddPrizeButtonState(totalCount);
- },
-
- // 更新添加奖品按钮状态
- updateAddPrizeButtonState: function(totalCount) {
- var maxCount = 10; // 最大奖品数量
- var addButton = $('#add-prize-btn');
- var remainingCount = maxCount - totalCount;
-
- console.log('updateAddPrizeButtonState - 奖品数:', totalCount, '最大允许:', maxCount, '剩余:', remainingCount);
-
- if (totalCount >= maxCount) {
- // 达到最大数量,禁用按钮
- addButton.prop('disabled', true).addClass('disabled');
- addButton.find('.btn-text').text('已达最大数量');
- // 更新按钮计数显示
- addButton.html('<i class="fa fa-plus"></i> 添加奖品 (10/10)');
- $('#prize-count-tip').text('已添加最大数量的奖品(' + maxCount + '个)').removeClass('text-muted').addClass('text-danger');
- console.log('按钮已禁用 - 达到最大数量');
- } else {
- // 未达到最大数量,启用按钮
- addButton.prop('disabled', false).removeClass('disabled');
- // 更新按钮计数显示
- addButton.html('<i class="fa fa-plus"></i> 添加奖品 (' + totalCount + '/10)');
- if (remainingCount <= 2) {
- $('#prize-count-tip').text('还可添加 ' + remainingCount + ' 个奖品').removeClass('text-muted text-danger').addClass('text-warning');
- } else {
- $('#prize-count-tip').text('还可添加 ' + remainingCount + ' 个奖品').removeClass('text-warning text-danger').addClass('text-muted');
- }
- console.log('按钮已启用 - 剩余数量:', remainingCount);
- }
- },
-
- // 计算总概率
- 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');
- }
- },
-
- // 编辑奖品(统一处理所有类型) - 已弃用,请使用 editPrizeByIndex
- editPrize: function(prizeItem) {
- // 获取奖品索引
- var prizeIndex = parseInt(prizeItem.attr('data-index'));
- if (isNaN(prizeIndex)) {
- Toastr.error('无法获取奖品索引');
- return;
- }
-
- // 调用新的编辑方法
- Controller.api.editPrizeByIndex(prizeIndex);
- },
-
- // 更新奖品信息(重构版 - 使用数据管理器)
- updatePrize: function($form, config) {
- console.log('updatePrize 调用参数:', {form: $form, config: config});
-
- // 验证config参数
- if (!config || typeof config !== 'object') {
- console.error('updatePrize: config参数无效:', config);
- Toastr.error('配置参数错误');
- return false;
- }
-
- // 验证prizeIndex
- if (typeof config.prizeIndex === 'undefined' || config.prizeIndex === null) {
- console.error('updatePrize: prizeIndex参数缺失:', config);
- Toastr.error('奖品索引参数缺失');
- return false;
- }
-
- // 收集表单数据
- var prizeData = Controller.api.collectPrizeFormData($form);
- if (!prizeData) {
- return false; // 验证失败
- }
-
- var prizeIndex = parseInt(config.prizeIndex);
- if (isNaN(prizeIndex) || prizeIndex < 0) {
- console.error('updatePrize: prizeIndex无效:', config.prizeIndex);
- Toastr.error('奖品索引无效');
- return false;
- }
-
- // 使用数据管理器更新奖品
- if (Controller.api.prizesDataManager.updatePrize(prizeIndex, prizeData)) {
- // 重新构建列表以反映更新
- Controller.api.rebuildPrizeList();
-
- // 更新统计
- Controller.api.updatePrizeCount();
- Controller.api.updateTotalRate();
-
- console.log('奖品更新成功:', prizeData, '索引:', prizeIndex);
- return true;
- } else {
- console.error('updatePrize: 数据管理器更新失败');
- Toastr.error('更新奖品失败');
- return false;
- }
- },
-
-
-
- // 在表单提交前收集条件数据 - 已弃用,改为使用规则数据管理器
- collectConditionData: function() {
- // 这个方法已经不再使用,改为使用规则数据管理器
- console.warn('collectConditionData方法已弃用,请使用规则数据管理器');
-
- 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 || '#selected-goods',
- template: 'goods-list-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();
-
- // 更新规则数据管理器
- Controller.api.updateRulesDataFromDOM();
- }
- }
- });
- },
-
- // 选择奖品商品(单选模式)
- 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();
-
- // 更新规则数据管理器
- Controller.api.updateRulesDataFromDOM();
- });
- },
-
- // 更新任务商品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);
- },
-
- // 规则数据管理器 - 类似奖品数据管理器
- rulesDataManager: {
- // 规则数据对象
- rulesData: {},
-
- // 初始化规则数据管理器
- init: function() {
- // 创建规则数据隐藏域
- if ($('#rules-data-json').length === 0) {
- $('<input>').attr({
- type: 'hidden',
- id: 'rules-data-json',
- name: 'conditions_json',
- value: '{}',
- 'data-rule': 'required;conditionsJson',
- 'data-msg-required': '请设置至少一种参与条件',
- 'data-msg-conditionsJson': '参与条件设置数据格式不正确'
- }).appendTo('form[role="form"]');
- }
-
- // 初始化数据
- this.loadFromHiddenField();
- },
-
- // 验证规则数据
- validateRuleData: function(type, ruleData) {
- if (!ruleData.type || ruleData.type !== type) {
- throw new Error('规则类型不匹配');
- }
-
- switch(parseInt(type)) {
- case 1: // 购买指定商品
- var goodsIds = JSON.parse(ruleData.goods_ids || '[]');
- if (!goodsIds || goodsIds.length === 0) {
- throw new Error('请选择参与商品');
- }
- if (!ruleData.goods_rule || (ruleData.goods_rule != 1 && ruleData.goods_rule != 2)) {
- throw new Error('请选择商品规则');
- }
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- if (!ruleData.condition_value || parseFloat(ruleData.condition_value) <= 0) {
- throw new Error('请输入有效的条件金额');
- }
- break;
- default:
- throw new Error('无效的规则类型');
- }
-
- return true;
- },
-
- // 从隐藏域加载数据
- loadFromHiddenField: function() {
- var jsonData = $('#rules-data-json').val();
- try {
- this.rulesData = JSON.parse(jsonData || '{}');
- } catch (e) {
- this.rulesData = {};
- console.warn('规则数据格式错误,已重置为空对象');
- }
- },
-
- // 保存数据到隐藏域
- saveToHiddenField: function() {
- var jsonData = JSON.stringify(this.rulesData);
- $('#rules-data-json').val(jsonData);
- console.log('规则数据已保存到隐藏域:', this.rulesData);
- },
-
- // 添加或更新规则数据
- updateRule: function(type, ruleData) {
- // 验证规则数据
- this.validateRuleData(type, ruleData);
-
- this.rulesData[type] = ruleData;
- this.saveToHiddenField();
- },
-
- // 删除规则
- deleteRule: function(type) {
- delete this.rulesData[type];
- this.saveToHiddenField();
- },
-
- // 获取规则数据
- getRule: function(type) {
- return this.rulesData[type] || null;
- },
-
- // 获取所有规则数据
- getAllRules: function() {
- return this.rulesData;
- },
-
- // 检查是否有规则数据
- hasRules: function() {
- return Object.keys(this.rulesData).length > 0;
- },
-
- // 清空所有规则
- clearAllRules: function() {
- this.rulesData = {};
- this.saveToHiddenField();
- }
- },
-
- // 收集规则数据并保存到隐藏域
- collectAndSaveRulesData: function() {
- var rulesData = {};
- var taskTypes = [];
-
- // 获取选中的任务类型
- $('input[name="row[task_type][]"]:checked').each(function() {
- taskTypes.push($(this).val());
- });
-
- // 为每个任务类型收集规则数据
- taskTypes.forEach(function(taskType) {
- var type = parseInt(taskType);
- var rule = {
- type: type
- };
-
- switch(type) {
- case 1: // 购买指定商品
- rule.goods_rule = $('input[name="condition[' + type + '][goods_rule]"]:checked').val() || 1;
- rule.goods_ids = $('#task-goods-ids-' + type).val() || '[]';
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- rule.condition_value = $('input[name="condition[' + type + '][condition_value]"]').val() || 0;
- break;
- }
-
- rulesData[type] = rule;
- });
-
- // 保存到规则数据管理器
- Controller.api.rulesDataManager.rulesData = rulesData;
- Controller.api.rulesDataManager.saveToHiddenField();
-
- console.log('规则数据已收集并保存:', rulesData);
- },
-
- // 从DOM更新规则数据
- updateRulesDataFromDOM: function() {
- // 在任务类型变化时同步更新规则数据
- Controller.api.collectAndSaveRulesData();
- }
- }
- };
-
- // 全局函数,供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);
- };
-
- // 暴露奖品数据管理器到全局
- window.Controller = Controller;
-
- return Controller;
- });
|