12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137 |
- define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
- //设置弹窗宽高
- Fast.config.openArea = ['80%', '80%'];
- var vm, si;
- var Controller = {
- index: function () {
- // 解析JSON格式的Config数据
- var statusList = {};
- var specTypeList = {};
- var goodsTypeList = {};
-
- try {
- statusList = Config.statusList ? JSON.parse(Config.statusList) : {};
- specTypeList = Config.specTypeList ? JSON.parse(Config.specTypeList) : {};
- goodsTypeList = Config.goodsTypeList ? JSON.parse(Config.goodsTypeList) : {};
- } catch (e) {
- console.error('解析Config数据失败:', e);
- statusList = {"normal": "正常", "hidden": "隐藏", "soldout": "售罄"};
- specTypeList = {0: "单规格", 1: "多规格"};
- goodsTypeList = {1: "普通商品"};
- }
-
- // 调试输出Config数据
- console.log('解析后的Config数据:', {
- statusList: statusList,
- specTypeList: specTypeList,
- goodsTypeList: goodsTypeList
- });
-
- // 添加列表样式优化
- $('<style>')
- .prop('type', 'text/css')
- .html(`
- .bootstrap-table .fixed-table-container {
- border: 1px solid #ddd;
- }
- .bootstrap-table .table th {
- background-color: #f8f9fa;
- font-weight: 600;
- border-bottom: 2px solid #dee2e6;
- }
- .bootstrap-table .table td {
- vertical-align: middle;
- padding: 4px 6px;
- min-height: 75px;
- }
- .bootstrap-table .table tr {
- border-bottom: 1px solid #f1f3f4;
- }
- .bootstrap-table .table tbody tr:hover {
- background-color: #f8f9fa;
- }
- .label-xs {
- font-size: 10px;
- padding: 2px 6px;
- }
- .goods-info-cell {
- word-wrap: break-word;
- padding: 3px 5px !important;
- max-width: 280px;
- overflow: hidden;
- }
- .goods-info-cell:hover {
- background-color: #fafbfc;
- }
- .goods-info-cell .goods-title {
- transition: color 0.3s ease;
- }
- .goods-info-cell:hover .goods-title {
- color: #3498db;
- }
- .price-cell {
- text-align: center;
- font-family: 'Arial', sans-serif;
- }
- .stock-cell {
- text-align: center;
- }
-
- /* 响应式优化 */
- @media (max-width: 1200px) {
- .goods-info-cell {
- max-width: 220px;
- }
- }
-
- @media (max-width: 768px) {
- .bootstrap-table .table td {
- padding: 3px 4px;
- font-size: 11px;
- min-height: 65px;
- }
- .goods-info-cell {
- max-width: 180px;
- }
- .goods-info-cell .goods-img {
- width: 40px !important;
- height: 40px !important;
- }
- .goods-info-cell .goods-title {
- font-size: 11px !important;
- }
- }
-
- /* 图片优化 */
- .bootstrap-table .table .img-center img {
- max-width: 80px;
- max-height: 80px;
- object-fit: cover;
- border-radius: 6px;
- border: 1px solid #ddd;
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
- }
-
- /* 标签优化 */
- .label {
- display: inline-block;
- margin: 1px;
- line-height: 1.2;
- }
- `)
- .appendTo('head');
- // 初始化表格参数配置
- Table.api.init({
- extend: {
- index_url: 'shop/goods/index' + location.search,
- add_url: 'shop/goods/add',
- edit_url: 'shop/goods/edit?dialog=1',
- del_url: 'shop/goods/del',
- multi_url: 'shop/goods/multi',
- import_url: 'shop/goods/import',
- table: 'shop_goods',
- }
- });
- Table.config.dragsortfield = '';
- 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', width: 60, sortable: true},
- {field: 'image', title: '图片', width: 100, operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
- {
- field: 'title',
- title: '商品信息',
- width: 300,
- operate: 'LIKE',
- formatter: function (value, row, index) {
- var html = '<div style="width: 280px; padding: 8px 0; line-height: 1.4; word-wrap: break-word;">';
-
- // 商品名称、编码、品牌在一行 - 固定宽度,超出换行
- html += '<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; width: 100%;">';
-
- // 商品标题
- html += '<span style="font-weight: 600; color: #2c3e50; font-size: 14px; word-break: break-all;" title="' + (value || '') + '">' + (value || '') + '</span>';
-
- // 分隔符
- html += '<span style="color: #ddd; font-size: 12px; flex-shrink: 0;">|</span>';
-
- // 商品编码
- html += '<div style="display: flex; align-items: center; flex-shrink: 0;">';
- html += '<i class="fa fa-barcode" style="margin-right: 3px; color: #999; font-size: 10px;"></i>';
- html += '<span style="font-size: 11px; color: #666; word-break: break-all;">' + (row.goods_sn || '-') + '</span>';
- html += '</div>';
-
- // 品牌信息
- if (row.brand && row.brand.name) {
- html += '<span style="color: #ddd; font-size: 12px; flex-shrink: 0;">|</span>';
- html += '<div style="display: flex; align-items: center; flex-shrink: 0;">';
- html += '<i class="fa fa-tag" style="margin-right: 3px; color: #999; font-size: 10px;"></i>';
- html += '<span style="font-size: 11px; color: #666; word-break: break-all;">' + row.brand.name + '</span>';
- html += '</div>';
- }
-
- html += '</div>';
-
- // 副标题
- if (row.subtitle) {
- html += '<div style="font-size: 11px; color: #999; line-height: 1.4; word-wrap: break-word; word-break: break-all;" title="' + row.subtitle + '">' + row.subtitle + '</div>';
- }
-
- // 显示规格信息(如果是多规格商品且有默认SKU)
- if (row.spec_type == 1 && row.default_sku && row.default_sku.sku_attr) {
- html += '<div style="font-size: 10px; color: #888; margin-top: 4px; padding: 2px 6px; background-color: #f5f5f5; border-radius: 3px;">';
- html += '<i class="fa fa-list-alt" style="margin-right: 3px;"></i>';
- html += '默认规格: ' + Controller.formatSkuAttr(row.default_sku.sku_attr);
- html += '</div>';
- }
-
- html += '</div>';
- return html;
- }
- },
- {
- field: 'type',
- title: '商品类型',
- width: 100,
- searchList: goodsTypeList,
- formatter: function (value, row, index) {
- var text = (goodsTypeList && goodsTypeList[value]) ? goodsTypeList[value] : '未知';
- var className = 'label-primary';
- var icon = 'fa-cube';
-
- switch(parseInt(value)) {
- case 1: className = 'label-primary'; icon = 'fa-cube'; break; // 普通商品
- case 2: className = 'label-info'; icon = 'fa-key'; break; // 卡密/网盘
- case 3: className = 'label-warning'; icon = 'fa-cloud'; break; // 虚拟商品
- case 4: className = 'label-success'; icon = 'fa-ticket'; break; // 次卡商品
- }
-
- return '<span class="label ' + className + '"><i class="fa ' + icon + '"></i> ' + text + '</span>';
- }
- },
- {
- field: 'spec_type',
- title: '规格',
- width: 80,
- searchList: specTypeList,
- formatter: function (value, row, index) {
- var label = (specTypeList && specTypeList[value]) ? specTypeList[value] : (value == 1 ? '多规格' : '单规格');
- var className = value == 1 ? 'label-info' : 'label-success';
- return '<span class="label ' + className + '"><i class="fa ' + (value == 1 ? 'fa-list' : 'fa-square') + '"></i> ' + label + '</span>';
- }
- },
- {field: 'price', title: '价格', width: 80, operate: 'BETWEEN', sortable: true},
- {field: 'stocks', title: '库存', width: 80, operate: 'BETWEEN', sortable: true},
- {field: 'sales', title: '销量', width: 80, operate: 'BETWEEN', sortable: true},
- {field: 'views', title: '浏览量', width: 80, operate: 'BETWEEN', sortable: true},
- {
- field: 'status',
- title: '状态',
- width: 80,
- searchList: statusList,
- formatter: function (value, row, index) {
- // 状态样式映射 - 根据GoodsEnum中的状态值
- var statusStyles = {
- 0: {class: 'label-warning', icon: 'fa-warehouse'}, // 仓库中(未上架)
- 1: {class: 'label-success', icon: 'fa-check-circle'}, // 销售中(已上架)
- 2: {class: 'label-danger', icon: 'fa-times-circle'}, // 已售罄
- 3: {class: 'label-default', icon: 'fa-eye-slash'} // 已下架
- };
-
- // 直接使用后台statusList数据
- var text = statusList && statusList[value] ? statusList[value] : '未知';
- var style = statusStyles[value] || {class: 'label-default', icon: 'fa-question'};
-
- return '<span class="label ' + style.class + '"><i class="fa ' + style.icon + '"></i> ' + text + '</span>';
- }
- },
- {field: 'createtime', title: '创建时间', width: 120, operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime, visible: false},
- {field: 'updatetime', title: '更新时间', width: 120, operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime, visible: false},
-
- // 隐藏字段用于搜索
- {field: 'brand_id', title: '品牌', visible: false, searchList: $.getJSON("shop/brand/getList")},
- {field: 'goods_sn', title: '商品编码', visible: false, operate: 'LIKE'},
- {field: 'title', title: '商品标题', visible: false, operate: 'LIKE'},
-
- {
- field: 'operate',
- title: '操作',
- width: 120,
- table: table,
- events: Table.api.events.operate,
- formatter: Table.api.formatter.operate,
- buttons: [
- {
- name: 'edit',
- title: '编辑',
- classname: 'btn btn-xs btn-success btn-dialog',
- icon: 'fa fa-pencil',
- url: 'shop/goods/edit'
- }
- // {
- // name: 'preview',
- // title: '预览',
- // classname: 'btn btn-xs btn-info',
- // icon: 'fa fa-eye',
- // url: function(row) {
- // return row.url;
- // },
- // target: '_blank'
- // }
- ]
- }
- ]
- ]
- });
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- select: function () {
- // 解析JSON格式的Config数据
- var specTypeList = {};
- try {
- specTypeList = Config.specTypeList ? JSON.parse(Config.specTypeList) : {0: "单规格", 1: "多规格"};
- } catch (e) {
- console.error('解析Config数据失败:', e);
- specTypeList = {0: "单规格", 1: "多规格"};
- }
-
- // 从URL参数中获取选择模式,默认为多选
- var urlParams = new URLSearchParams(window.location.search);
- var selectMode = urlParams.get('selectMode') || 'multiple'; // 'single' 或 'multiple'
- var maxSelect = parseInt(urlParams.get('maxSelect')) || 0; // 最大选择数量,0表示无限制
-
- // 初始化表格参数配置
- Table.api.init({
- extend: {
- index_url: 'shop/goods/index' + location.search,
- table: 'shop_goods',
- }
- });
- Table.config.dragsortfield = '';
- var table = $("#table");
- // 根据选择模式配置表格列
- var columns = [
- {field: 'id', title: 'ID', width: 60},
- {field: 'image', title: '图片', width: 120, operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
- {
- field: 'title',
- title: '商品信息',
- operate: 'LIKE',
- formatter: function (value, row, index) {
- var html = '<div>';
- html += '<div style="font-weight: bold; margin-bottom: 2px;">' + value + '</div>';
- html += '<div style="font-size: 12px; color: #999;">';
- html += '编码: ' + (row.goods_sn || '-');
- if (row.category && row.category.name) {
- html += ' | 分类: ' + row.category.name;
- }
- html += '</div>';
- html += '</div>';
- return html;
- }
- },
- {field: 'spec_type', title: '规格', width: 80, searchList: specTypeList, formatter: Table.api.formatter.label},
- {
- field: 'price',
- title: '价格',
- width: 100,
- operate: 'BETWEEN',
- formatter: function (value, row, index) {
- return '<span style="color: #e74c3c; font-weight: bold;">¥' + (value || '0.00') + '</span>';
- }
- },
- {field: 'stocks', title: '库存', width: 80},
-
- // 操作列 - 添加选择按钮
- {
- field: 'operate',
- title: selectMode === 'single' ? '选择' : '操作',
- width: selectMode === 'single' ? 80 : 100,
- operate: false,
- formatter: function (value, row, index) {
- var html = '';
- if (selectMode === 'single') {
- // 单选模式:蓝色选择按钮,更明显
- html = '<button class="btn btn-xs btn-primary btn-select-single" data-id="' + row.id + '" data-index="' + index + '" title="点击选择该商品">' +
- '<i class="fa fa-check"></i> 选择</button>';
- } else {
- // 多选模式:绿色选择按钮,带图标区分状态
- html = '<button class="btn btn-xs btn-success btn-select-multi" data-id="' + row.id + '" data-index="' + index + '" data-selected="false" title="点击添加到选择列表">' +
- '<i class="fa fa-plus"></i> 选择</button>';
- }
- return html;
- }
- },
-
- // 隐藏字段用于搜索
- {field: 'category_id', title: '分类', visible: false, searchList: $.getJSON("shop/category/getList")},
- {field: 'goods_sn', title: '商品编码', visible: false, operate: 'LIKE'},
- ];
- // 初始化表格
- table.bootstrapTable({
- url: $.fn.bootstrapTable.defaults.extend.index_url,
- pk: 'id',
- sortName: 'id',
- clickToSelect: false, // 禁用点击行选择
- columns: [columns]
- });
-
- // 如果是多选模式且有最大选择限制,添加选择控制
- if (selectMode === 'multiple' && maxSelect > 0) {
- table.on('check.bs.table check-all.bs.table', function (e, row) {
- var selectedRows = table.bootstrapTable('getSelections');
- if (selectedRows.length > maxSelect) {
- // 超出限制,取消最后一次选择
- if (e.type === 'check.bs.table') {
- table.bootstrapTable('uncheck', table.bootstrapTable('getData').indexOf(row));
- } else {
- // 如果是全选,只保留前N个
- var allData = table.bootstrapTable('getData');
- for (var i = maxSelect; i < allData.length; i++) {
- table.bootstrapTable('uncheck', i);
- }
- }
- Toastr.warning('最多只能选择 ' + maxSelect + ' 个商品');
- }
- });
- }
-
- // 存储选中的商品(用于按钮模式)
- var selectedGoods = [];
-
- // 单选按钮点击事件
- $(document).on('click', '.btn-select-single', function () {
- var $btn = $(this);
- var id = $btn.data('id');
- var index = $btn.data('index');
- var rowData = table.bootstrapTable('getData')[index];
-
- // 直接选择商品并关闭弹窗
- Fast.api.close([rowData]);
- });
-
- // 多选按钮点击事件
- $(document).on('click', '.btn-select-multi', function () {
- var $btn = $(this);
- var id = $btn.data('id');
- var index = $btn.data('index');
- var isSelected = $btn.data('selected');
- var rowData = table.bootstrapTable('getData')[index];
-
- if (!isSelected) {
- // 检查最大选择限制
- if (maxSelect > 0 && selectedGoods.length >= maxSelect) {
- Toastr.warning('最多只能选择 ' + maxSelect + ' 个商品');
- return;
- }
-
- // 添加到选中列表
- selectedGoods.push(rowData);
- $btn.removeClass('btn-success').addClass('btn-danger')
- .html('<i class="fa fa-minus"></i> 取消选择')
- .attr('title', '点击从选择列表中移除')
- .data('selected', true);
- } else {
- // 从选中列表移除
- selectedGoods = selectedGoods.filter(function(item) {
- return item.id != id;
- });
- $btn.removeClass('btn-danger').addClass('btn-success')
- .html('<i class="fa fa-plus"></i> 选择')
- .attr('title', '点击添加到选择列表')
- .data('selected', false);
- }
-
- // 更新选中数量显示
- updateSelectedCount();
- });
-
- // 更新选中数量显示
- function updateSelectedCount() {
- var count = selectedGoods.length;
- var countText = count > 0 ? '已选择 ' + count + ' 个商品' : '请选择商品';
-
- // 更新确认按钮文本
- $('.btn-goods-select').text(countText === '请选择商品' ? '确认选择' : '确认选择 (' + count + ')');
-
- // 如果达到最大选择数量,禁用其他选择按钮
- if (maxSelect > 0 && count >= maxSelect) {
- $('.btn-select-multi[data-selected="false"]').prop('disabled', true).addClass('disabled');
- } else {
- $('.btn-select-multi[data-selected="false"]').prop('disabled', false).removeClass('disabled');
- }
- }
-
- // 确认按钮绑定事件(仅多选模式使用)
- $(document).on('click', '.btn-goods-select', function () {
- var selectedRows = [];
-
- if (selectMode === 'single') {
- // 单选模式:不应该走到这里,因为单选时直接选择
- Layer.alert('单选模式请直接点击商品的选择按钮');
- return;
- } else {
- // 多选模式:使用按钮选择的商品
- selectedRows = selectedGoods;
- }
-
- if (selectedRows.length === 0) {
- Layer.alert('请选择商品');
- return;
- }
-
- // 调用父窗口回调函数
- Fast.api.close(selectedRows);
- });
-
- // 在页面标题中显示选择模式
- var modeText = selectMode === 'single' ? '单选' : '多选';
- if (selectMode === 'multiple' && maxSelect > 0) {
- modeText += '(最多' + maxSelect + '个)';
- }
- $('.panel-heading, .layui-layer-title').each(function() {
- var currentTitle = $(this).text();
- if (currentTitle.indexOf('选择商品') !== -1 && currentTitle.indexOf(modeText) === -1) {
- $(this).text(currentTitle + ' - ' + modeText);
- }
- });
-
- // 显示选择模式提示信息
- $('#selection-info').show();
- $('#selection-mode-text').text(modeText);
-
- if (selectMode === 'single') {
- $('#selection-tip').html('<strong>单击任意商品的"选择"按钮即可完成选择</strong>');
- // 单选模式隐藏确认按钮
- $('#confirm-select-btn').hide();
- } else {
- var tipText = '点击商品的"选择"按钮添加到选择列表,绿色表示可选择,红色表示已选择';
- if (maxSelect > 0) {
- tipText += ',最多可选择' + maxSelect + '个商品';
- }
- $('#selection-tip').text(tipText);
- // 多选模式显示确认按钮
- $('#confirm-select-btn').show();
- }
-
- // 表格刷新后恢复选择状态
- table.on('refresh.bs.table load-success.bs.table', function () {
- if (selectMode === 'multiple') {
- // 恢复多选按钮状态
- setTimeout(function() {
- $('.btn-select-multi').each(function() {
- var $btn = $(this);
- var id = $btn.data('id');
- var isSelected = selectedGoods.some(function(item) {
- return item.id == id;
- });
-
- if (isSelected) {
- $btn.removeClass('btn-success').addClass('btn-danger')
- .html('<i class="fa fa-minus"></i> 取消选择')
- .attr('title', '点击从选择列表中移除')
- .data('selected', true);
- } else {
- $btn.removeClass('btn-danger').addClass('btn-success')
- .html('<i class="fa fa-plus"></i> 选择')
- .attr('title', '点击添加到选择列表')
- .data('selected', false);
- }
- });
-
- // 更新选中数量显示
- updateSelectedCount();
- }, 100);
- }
- });
-
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- recyclebin: function () {
- // 初始化表格参数配置
- Table.api.init({
- extend: {
- 'dragsort_url': ''
- }
- });
- var table = $("#table");
- // 初始化表格
- table.bootstrapTable({
- url: 'shop/goods/recyclebin' + location.search,
- pk: 'id',
- sortName: 'id',
- columns: [
- [{
- checkbox: true
- },
- {
- field: 'id',
- title: __('Id')
- },
- {
- field: 'title',
- title: __('Title'),
- align: 'left'
- },
- {
- field: 'deletetime',
- title: __('Deletetime'),
- operate: 'RANGE',
- addclass: 'datetimerange',
- formatter: Table.api.formatter.datetime
- },
- {
- field: 'operate',
- width: '130px',
- title: __('Operate'),
- table: table,
- events: Table.api.events.operate,
- buttons: [{
- name: 'Restore',
- text: __('Restore'),
- classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
- icon: 'fa fa-rotate-left',
- url: 'shop/goods/restore',
- refresh: true
- },
- {
- name: 'Destroy',
- text: __('Destroy'),
- classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
- icon: 'fa fa-times',
- url: 'shop/goods/destroy',
- refresh: true
- }
- ],
- formatter: Table.api.formatter.operate
- }
- ]
- ]
- });
- // 为表格绑定事件
- Table.api.bindevent(table);
- },
- getAttribute: function (category_id, attribute_ids = []) {
- $.get('shop/attribute/attrs?category_id=' + category_id, function (res) {
- const {code, data, msg} = res;
- if (code) {
- $('#attributes').html(data.length ? Template('attributetpl', {row: data, attribute_ids}) : ' <input name="row[attribute_ids][0][]" type="hidden" value="">');
- var instance = $("form[data-toggle='validator']").data("validator");
- $('#attributes input').each(function () {
- instance._parse(this);
- });
- } else {
- Toastr.error(msg);
- }
- })
- },
- add: function () {
- let that = this;
-
- // 等待DOM完全加载后再执行
- $(document).ready(function() {
- $('#c-category_id, #c-category_ids').on('change', function () {
- let category_id = $(this).val();
- that.getAttribute(category_id);
- });
-
- // 初始化商品类型卡片交互
- that.initGoodsTypeCards();
-
- // 添加上架时间和下架时间的交互逻辑
- that.initOnlineOfflineControl();
-
-
- // 初始化商品详情预览功能
- that.initContentPreview();
-
- // 初始化选项卡验证提示系统
- that.initTabValidation();
-
- Controller.api.bindevent();
- Controller.api.add_sku();
- });
- },
- edit: function () {
- let that = this;
-
- // 等待DOM完全加载后再执行
- $(document).ready(function() {
- $('#c-category_id, #c-category_ids').on('change', function () {
- let category_id = $(this).val();
- //that.getAttribute(category_id);
- });
- if (Config.goods && Config.goods.category_id) {
- //that.getAttribute(Config.goods.category_id, Config.goods.attribute_ids ? Config.goods.attribute_ids.split(',') : []);
- }
-
- // 初始化商品类型卡片交互
- that.initGoodsTypeCards();
-
- // 添加上架时间和下架时间的交互逻辑
- that.initOnlineOfflineControl();
-
- // 初始化商品详情预览功能
- that.initContentPreview();
-
- // 初始化选项卡验证提示系统
- that.initTabValidation();
-
- // 编辑时初始化商品类型选择状态
- that.initEditTypeState();
-
-
- Controller.api.bindevent();
- Controller.api.add_sku();
- });
- },
-
- // 检查多选控件是否为空
- isMultiSelectEmpty: function(value) {
- if (Array.isArray(value)) {
- return value.length === 0;
- } else if (typeof value === 'string') {
- // 移除空格并检查
- var trimmed = value.trim();
- return trimmed === '' || trimmed === '0' || trimmed === 'null' || trimmed === 'undefined';
- } else {
- return !value || value === null || value === undefined;
- }
- },
-
- // 添加错误高亮样式
- addErrorStyles: function() {
- // 检查是否已经添加过样式
- if ($('#goods-error-styles').length > 0) {
- return;
- }
-
- var styles = `
- <style id="goods-error-styles">
- .nav-tabs > li > a.tab-error {
- color: #d9534f !important;
- background-color: #f2dede !important;
- border-color: #d9534f !important;
- }
- .nav-tabs > li > a.tab-error:hover,
- .nav-tabs > li > a.tab-error:focus {
- background-color: #ebccd1 !important;
- border-color: #d9534f !important;
- }
- .nav-tabs > li > a.tab-success {
- color: #5cb85c !important;
- }
- .nav-tabs > li > a .error-icon {
- color: #d9534f;
- }
- .nav-tabs > li > a .success-icon {
- color: #5cb85c;
- }
- .error-highlight {
- border-color: #d9534f !important;
- box-shadow: 0 0 0 0.2rem rgba(217, 83, 79, 0.25) !important;
- animation: shake 0.5s ease-in-out;
- }
- @keyframes shake {
- 0%, 20%, 40%, 60%, 80% {
- transform: translateX(0);
- }
- 10%, 30%, 50%, 70%, 90% {
- transform: translateX(-3px);
- }
- }
- </style>
- `;
- $('head').append(styles);
- },
-
- // 初始化商品类型卡片交互
- initGoodsTypeCards: function() {
- // 检查元素是否存在,避免在不支持该功能的页面报错
- if ($('.goods-type-card').length === 0) {
- return;
- }
-
- // 初始化选中状态
- function updateTypeCardState() {
- var $cards = $('.goods-type-card');
- if ($cards.length > 0) {
- $cards.removeClass('selected');
- $('.goods-type-card input[type="radio"]:checked').closest('.goods-type-card').addClass('selected');
- }
- }
-
- // 监听单选按钮变化
- var $radioInputs = $('.goods-type-card input[type="radio"]');
- if ($radioInputs && $radioInputs.length > 0) {
- $radioInputs.off('change.typecard').on('change.typecard', function() {
- updateTypeCardState();
- });
- }
-
- // 初始化时设置状态
- updateTypeCardState();
-
- // 让FastAdmin处理表单验证和按钮状态
- // 无需额外的验证逻辑,data-rule会自动处理
- },
-
- // 初始化编辑状态
- initEditTypeState: function() {
- console.log('初始化编辑状态');
-
- // 如果存在商品数据,设置商品类型选中状态
- if (Config.goods && Config.goods.type) {
- console.log('设置商品类型:', Config.goods.type);
- var $typeRadio = $('input[name="row[type]"][value="' + Config.goods.type + '"]');
- if ($typeRadio.length > 0) {
- $typeRadio.prop('checked', true);
- $typeRadio.trigger('change');
- }
- }
-
- // 如果存在上架类型数据,设置上架类型选中状态(优先使用online_type字段)
- if (Config.goods && Config.goods.online_type !== undefined) {
- console.log('设置上架类型(online_type):', Config.goods.online_type);
- var $onlineTypeRadio = $('input[name="row[online_type]"][value="' + Config.goods.online_type + '"]');
- if ($onlineTypeRadio.length > 0) {
- $onlineTypeRadio.prop('checked', true);
- $onlineTypeRadio.trigger('change');
- }
- }
-
- // 设置上下架时间相关字段
- if (Config.goods) {
- // 设置定时上架时间
- if (Config.goods.scheduled_online_time) {
- $('#c-scheduled_online_time').val(Config.goods.scheduled_online_time);
- }
-
- // 设置自动下架选项
- if (Config.goods.is_auto_offline) {
- $('#c-is_auto_offline').prop('checked', true);
- if (Config.goods.scheduled_offline_time) {
- $('#c-scheduled_offline_time').val(Config.goods.scheduled_offline_time);
- }
- }
- }
-
- // 如果存在规格类型数据,设置规格类型选中状态
- if (Config.goods && Config.goods.spec_type !== undefined) {
- console.log('设置规格类型:', Config.goods.spec_type);
- var $specTypeRadio = $('input[name="row[spec_type]"][value="' + Config.goods.spec_type + '"]');
- if ($specTypeRadio.length > 0) {
- $specTypeRadio.prop('checked', true);
- $specTypeRadio.trigger('change');
-
- // 触发FastAdmin的Favisible事件,确保对应的表单区域显示
- setTimeout(function() {
- $(document).trigger('fa.event.favisible', $specTypeRadio);
- }, 100);
- }
- }
-
- // 如果是单规格且有SKU数据,填充单规格表单
- if (Config.goods && Config.goods.spec_type == '0' && Config.goods_skus && Config.goods_skus.length > 0) {
- console.log('填充单规格数据');
- var sku = Config.goods_skus[0];
-
- // 延迟填充数据,确保DOM已渲染
- setTimeout(function() {
- $('#c-price').val(sku.price || '');
- $('#c-lineation_price').val(sku.lineation_price || '');
- $('#c-cost_price').val(sku.cost_price || '');
- $('#c-stocks').val(sku.stocks || '');
- $('#c-weight').val(sku.weight || '');
- $('#c-volume').val(sku.volume || '');
- $('#c-sku-sn').val(sku.sku_sn || '');
- $('#c-single-image').val(sku.image || '');
-
- // 更新单规格图片预览
- if (sku.image) {
- var $preview = $('#p-single-image');
- var img = '<li><a href="' + Fast.api.cdnurl(sku.image, true) + '" data-url="' + sku.image + '" target="_blank"><img src="' + Fast.api.cdnurl(sku.image, true) + '"/></a></li>';
- $preview.html(img);
- }
-
- console.log('单规格数据填充完成');
- }, 200);
- } else if (Config.goods && Config.goods.spec_type == '1') {
- console.log('多规格商品,等待Vue组件初始化多规格数据');
- // 多规格数据由Vue组件的init方法处理
- }
- },
-
- // 初始化选项卡验证提示系统
- initTabValidation: function() {
- var that = this;
-
- // 添加错误高亮样式
- that.addErrorStyles();
-
- // 清除所有选项卡错误标记
- that.clearTabErrors();
-
- // 启用提交按钮(移除disabled类)
- $('.btn[type="submit"]').removeClass('disabled');
-
- // 监听表单字段变化,实时验证
- var $forms = $('#add-form, #edit-form');
- if ($forms && $forms.length > 0) {
- $forms.on('change keyup blur', 'input, select, textarea', function() {
- setTimeout(function() {
- that.validateCurrentTab();
- }, 100);
- });
- }
-
- // 监听选项卡切换
- var $tabLinks = $('.nav-tabs a[data-toggle="tab"]');
- if ($tabLinks && $tabLinks.length > 0) {
- $tabLinks.on('shown.bs.tab', function(e) {
- setTimeout(function() {
- that.validateCurrentTab();
- }, 100);
- });
-
- // 当离开选项卡时,验证该选项卡并标记状态
- $tabLinks.on('hide.bs.tab', function(e) {
- var leavingTab = $(e.target).attr('href');
- that.validateAndMarkTab(leavingTab);
- });
- }
-
- // 页面加载完成后进行一次全面验证,但不跳转,只显示状态
- setTimeout(function() {
- that.validateAllTabsForStatus();
- }, 1000);
- },
-
- // 验证当前选项卡
- validateCurrentTab: function() {
- var that = this;
- var $activeTab = $('.nav-tabs li.active a');
- if ($activeTab.length === 0) {
- return; // 没有活动选项卡,直接返回
- }
-
- var activeTab = $activeTab.attr('href');
- if (!activeTab) {
- return; // 没有href属性,直接返回
- }
-
- // 清除当前选项卡的错误标记
- that.clearTabError(activeTab);
-
- var hasError = false;
- var errorMessage = '';
-
- switch(activeTab) {
- case '#basics':
- var result = that.validateBasicsTab();
- hasError = !result.valid;
- errorMessage = result.message;
- break;
- case '#skus':
- var result = that.validateSkusTab();
- hasError = !result.valid;
- errorMessage = result.message;
- break;
- case '#delivery':
- var result = that.validateDeliveryTab();
- hasError = !result.valid;
- errorMessage = result.message;
- break;
- case '#detail':
- var result = that.validateDetailTab();
- hasError = !result.valid;
- errorMessage = result.message;
- break;
- case '#sales':
- var result = that.validateSalesTab();
- hasError = !result.valid;
- errorMessage = result.message;
- break;
- }
-
- if (hasError) {
- that.showTabError(activeTab, errorMessage);
- }
- },
-
- // 验证基础信息选项卡
- validateBasicsTab: function() {
- var errors = [];
-
- console.log('验证基础信息选项卡');
-
- // 验证商品类型
- if (!$('input[name="row[type]"]:checked').length) {
- errors.push('请选择商品类型');
- console.log('商品类型验证失败');
- }
-
- // 验证商品编码 - 检查是否有data-rule required
- var $goodsSn = $('#c-goods_sn');
- if ($goodsSn.length > 0 && $goodsSn.attr('data-rule') && $goodsSn.attr('data-rule').indexOf('required') !== -1) {
- var goodsSn = $goodsSn.val();
- if (!goodsSn || goodsSn.trim() === '') {
- errors.push('请输入商品编码');
- console.log('商品编码验证失败');
- }
- }
-
- // 验证商品标题
- var $title = $('#c-title');
- if ($title.length > 0 && $title.attr('data-rule') && $title.attr('data-rule').indexOf('required') !== -1) {
- var title = $title.val();
- if (!title || title.trim() === '') {
- errors.push('请输入商品标题');
- console.log('商品标题验证失败');
- }
- }
-
- // 验证商品分类 - 多选控件(兼容不同页面的字段ID)
- var $categoryId = $('#c-category_id, #c-category_ids').first();
- if ($categoryId.length > 0 && $categoryId.attr('data-rule') && $categoryId.attr('data-rule').indexOf('required') !== -1) {
- var categoryId = $categoryId.val();
- if (Controller.isMultiSelectEmpty(categoryId)) {
- errors.push('请选择商品分类');
- console.log('商品分类验证失败');
- }
- }
-
- // 验证主图
- var $image = $('#c-image');
- if ($image.length > 0 && $image.attr('data-rule') && $image.attr('data-rule').indexOf('required') !== -1) {
- var image = $image.val();
- if (!image || image.trim() === '') {
- errors.push('请上传商品主图');
- console.log('商品主图验证失败');
- }
- }
-
- console.log('基础信息验证结果:', errors);
-
- return {
- valid: errors.length === 0,
- message: errors.join('、'),
- errors: errors
- };
- },
-
- // 验证价格库存选项卡
- validateSkusTab: function() {
- var errors = [];
- var specType = $('input[name="row[spec_type]"]:checked').val();
-
- console.log('验证价格库存选项卡, 规格类型:', specType);
-
- if (!specType) {
- errors.push('请选择规格类型');
- console.log('规格类型未选择');
- } else if (specType == '0') {
- // 单规格验证
- console.log('验证单规格');
-
- // 验证价格
- var $price = $('#c-price');
- if ($price.length > 0 && $price.attr('data-rule') && $price.attr('data-rule').indexOf('required') !== -1) {
- var price = parseFloat($price.val());
- if (!price || price <= 0) {
- errors.push('销售价必须大于0');
- console.log('销售价验证失败');
- }
- }
-
- // 验证库存
- var $stocks = $('#c-stocks');
- if ($stocks.length > 0 && $stocks.attr('data-rule') && $stocks.attr('data-rule').indexOf('required') !== -1) {
- var stocks = parseInt($stocks.val());
- if (isNaN(stocks) || stocks <= 0) {
- errors.push('库存必须大于0');
- console.log('库存验证失败');
- }
- }
- } else if (specType == '1') {
- // 多规格验证
- console.log('验证多规格');
-
- if (typeof vm !== 'undefined' && vm && vm.tableData) {
- var hasValidSku = false;
- var validSkuCount = 0;
-
- console.log('检查SKU数据, tableData长度:', vm.tableData.length);
-
- for (var i = 0; i < vm.tableData.length; i++) {
- var sku = vm.tableData[i];
- console.log('检查SKU[' + i + ']:', {
- status: sku.status,
- price: sku.price,
- stocks: sku.stocks,
- sku_sn: sku.sku_sn
- });
-
- // 只检查状态为显示的SKU
- var isVisible = (sku.status === 1 || sku.status === '1' || sku.status === true);
-
- console.log('SKU[' + i + '] 显示状态:', sku.status, '可见:', isVisible);
-
- if (isVisible) {
- var price = parseFloat(sku.price);
- var stocks = parseInt(sku.stocks);
-
- console.log('SKU[' + i + '] 检查通过, price:', price, 'stocks:', stocks);
-
- hasValidSku = true;
- validSkuCount++;
-
- // 验证价格必须大于0
- if (!price || price <= 0) {
- errors.push('SKU销售价必须大于0');
- console.log('SKU[' + i + ']销售价验证失败:', price);
- break;
- }
-
- // 验证库存
- if (isNaN(stocks) || stocks <= 0) {
- errors.push('SKU库存必须大于0');
- console.log('SKU[' + i + ']库存验证失败:', stocks);
- break;
- }
- }
- }
-
- console.log('有效SKU数量:', validSkuCount);
-
- if (!hasValidSku) {
- errors.push('请至少设置一个有效的SKU');
- console.log('没有有效的SKU');
- }
- } else {
- errors.push('请设置商品规格');
- console.log('多规格数据不存在');
- }
- }
-
- console.log('价格库存验证结果:', errors);
-
- return {
- valid: errors.length === 0,
- message: errors.join('、'),
- errors: errors
- };
- },
-
- // 验证配送设置选项卡
- validateDeliveryTab: function() {
- var errors = [];
-
- console.log('验证配送设置选项卡');
-
- // 验证配送方式
- if (!$('input[name="row[delivery_type]"]:checked').length) {
- errors.push('请选择配送方式');
- console.log('配送方式未选择');
- }
-
- var deliveryType = $('input[name="row[delivery_type]"]:checked').val();
- if (deliveryType === 'EXPRESS') {
- var expressType = $('input[name="row[express_type]"]:checked').val();
-
- if (expressType === '3') {
- // 运费模板
- var templateId = $('#c-express_template_id').val();
- if (!templateId) {
- errors.push('请选择运费模板');
- console.log('运费模板未选择');
- }
- }
- }
-
- console.log('配送设置验证结果:', errors);
-
- return {
- valid: errors.length === 0,
- message: errors.join('、'),
- errors: errors
- };
- },
-
- // 验证商品详情选项卡
- validateDetailTab: function() {
- console.log('验证商品详情选项卡');
- // 商品详情不是必填项,暂时返回有效
- return {
- valid: true,
- message: '',
- errors: []
- };
- },
-
- // 验证销售设置选项卡
- validateSalesTab: function() {
- var errors = [];
-
- console.log('验证销售设置选项卡');
-
- // 验证库存显示方式
- if (!$('input[name="row[stock_show_type]"]:checked').length) {
- errors.push('请选择库存显示方式');
- console.log('库存显示方式未选择');
- }
-
- // 验证销量显示方式
- if (!$('input[name="row[sales_show_type]"]:checked').length) {
- errors.push('请选择销量显示方式');
- console.log('销量显示方式未选择');
- }
-
- console.log('销售设置验证结果:', errors);
-
- return {
- valid: errors.length === 0,
- message: errors.join('、'),
- errors: errors
- };
- },
-
- // 显示选项卡错误
- showTabError: function(tabId, message) {
- if (!tabId || !message) return;
-
- var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
- if ($tabLink.length > 0 && !$tabLink.hasClass('tab-error')) {
- $tabLink.addClass('tab-error');
-
- // 添加错误图标
- if ($tabLink.find('.error-icon').length === 0) {
- $tabLink.append(' <i class="fa fa-exclamation-circle error-icon"></i>');
- }
-
- // 添加提示信息
- $tabLink.attr('title', message);
- $tabLink.tooltip('destroy').tooltip({
- placement: 'top',
- title: message
- });
- }
- },
-
- // 清除选项卡错误
- clearTabError: function(tabId) {
- if (!tabId) return;
-
- var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
- if ($tabLink.length > 0) {
- $tabLink.removeClass('tab-error tab-success');
- $tabLink.find('.error-icon, .success-icon').remove();
- $tabLink.removeAttr('title');
- if ($tabLink.tooltip) {
- try {
- $tabLink.tooltip('destroy');
- } catch (e) {
- console.log('单个选项卡tooltip清理错误:', e);
- }
- }
- }
- },
-
- // 清除所有选项卡错误
- clearTabErrors: function() {
- var $navTabs = $('.nav-tabs');
- if ($navTabs.length > 0) {
- var $tabLinks = $navTabs.find('a');
- if ($tabLinks.length > 0) {
- $tabLinks.removeClass('tab-error tab-success');
- $tabLinks.find('.error-icon, .success-icon').remove();
- $tabLinks.removeAttr('title');
- if ($tabLinks.tooltip) {
- try {
- $tabLinks.tooltip('destroy');
- } catch (e) {
- console.log('tooltip清理错误:', e);
- }
- }
- }
- }
- },
-
- // 验证并标记单个选项卡状态
- validateAndMarkTab: function(tabId) {
- if (!tabId) return;
-
- var that = this;
- var result = null;
-
- // 清除当前选项卡的标记
- that.clearTabError(tabId);
-
- switch(tabId) {
- case '#basics':
- result = that.validateBasicsTab();
- break;
- case '#skus':
- result = that.validateSkusTab();
- break;
- case '#delivery':
- result = that.validateDeliveryTab();
- break;
- case '#detail':
- result = that.validateDetailTab();
- break;
- case '#sales':
- result = that.validateSalesTab();
- break;
- }
-
- if (result) {
- if (!result.valid) {
- that.showTabError(tabId, result.errors.join('、'));
- } else {
- that.showTabSuccess(tabId);
- }
- }
- },
-
- // 验证所有选项卡但只显示状态,不跳转
- validateAllTabsForStatus: function() {
- var that = this;
- var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
-
- tabs.forEach(function(tabId) {
- that.validateAndMarkTab(tabId);
- });
- },
-
- // 显示选项卡成功状态
- showTabSuccess: function(tabId) {
- if (!tabId) return;
-
- var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
- if ($tabLink.length > 0) {
- $tabLink.removeClass('tab-error').addClass('tab-success');
- $tabLink.find('.error-icon').remove();
-
- // 添加成功图标
- if ($tabLink.find('.success-icon').length === 0) {
- $tabLink.append(' <i class="fa fa-check-circle success-icon"></i>');
- }
-
- $tabLink.removeAttr('title');
- if ($tabLink.tooltip) {
- try {
- $tabLink.tooltip('destroy');
- } catch (e) {
- console.log('tooltip错误:', e);
- }
- }
- }
- },
-
- // 处理Nice-validator验证错误
- handleValidationError: function(validator) {
- var that = this;
- var $firstInvalidField = null;
-
- // 多种方式获取验证失败的字段
- if (validator && typeof validator.getInvalidFields === 'function') {
- var $invalidFields = validator.getInvalidFields();
- if ($invalidFields && $invalidFields.length > 0) {
- $firstInvalidField = $($invalidFields[0]);
- }
- }
-
- // 如果上面方法失败,尝试查找带有错误类的字段
- if (!$firstInvalidField || $firstInvalidField.length === 0) {
- $firstInvalidField = $('.form-control.n-invalid, input.n-invalid, select.n-invalid, textarea.n-invalid').first();
- }
-
- // 如果还是没有,查找第一个必填但为空的字段
- if (!$firstInvalidField || $firstInvalidField.length === 0) {
- $firstInvalidField = $('input[data-rule*="required"]:visible').filter(function() {
- return !$(this).val();
- }).first();
- }
-
- if (!$firstInvalidField || $firstInvalidField.length === 0) {
- $firstInvalidField = $('select[data-rule*="required"]:visible').filter(function() {
- return !$(this).val();
- }).first();
- }
-
- // 如果找到了错误字段
- if ($firstInvalidField && $firstInvalidField.length > 0) {
- var fieldName = $firstInvalidField.attr('name') || $firstInvalidField.attr('id');
- var errorTab = that.getTabByFieldName(fieldName, $firstInvalidField);
-
- console.log('找到验证错误字段:', fieldName, '对应选项卡:', errorTab);
-
- if (errorTab) {
- // 跳转到对应选项卡
- var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
- if ($tabLink.length > 0) {
- $tabLink.tab('show');
-
- // 标记错误选项卡
- that.showTabError(errorTab, '该选项卡有必填项未完成');
-
- // 滚动到页面顶部
- $('html, body').animate({scrollTop: 0}, 300);
-
- // 延迟聚焦到错误字段
- setTimeout(function() {
- $firstInvalidField.focus();
- that.highlightErrorField($firstInvalidField);
- }, 500);
- }
- }
- } else {
- console.log('未找到验证错误字段,执行通用错误处理');
- // 如果找不到具体的错误字段,至少显示一个通用提示
- Toastr.error('请检查表单填写是否完整');
- }
- },
-
- // 根据字段名获取对应的选项卡
- getTabByFieldName: function(fieldName, $field) {
- if (!fieldName && !$field) return '#basics';
-
- // 根据字段名判断选项卡
- if (fieldName) {
- // 基础信息相关字段
- if (fieldName.indexOf('type') !== -1 ||
- fieldName.indexOf('goods_sn') !== -1 ||
- fieldName.indexOf('title') !== -1 ||
- fieldName.indexOf('category_id') !== -1 ||
- fieldName.indexOf('category_ids') !== -1 ||
- fieldName.indexOf('brand_id') !== -1 ||
- fieldName.indexOf('image') !== -1 && fieldName.indexOf('single') === -1) {
- return '#basics';
- }
-
- // 价格库存相关字段
- if (fieldName.indexOf('spec_type') !== -1 ||
- fieldName.indexOf('price') !== -1 ||
- fieldName.indexOf('stocks') !== -1 ||
- fieldName.indexOf('marketprice') !== -1 ||
- fieldName.indexOf('single') !== -1) {
- return '#skus';
- }
-
- // 配送设置相关字段
- if (fieldName.indexOf('delivery_type') !== -1 ||
- fieldName.indexOf('express') !== -1 ||
- fieldName.indexOf('freight') !== -1) {
- return '#delivery';
- }
-
- // 商品详情相关字段
- if (fieldName.indexOf('content') !== -1 ||
- fieldName.indexOf('detail') !== -1) {
- return '#detail';
- }
-
- // 销售设置相关字段
- if (fieldName.indexOf('stock_show_type') !== -1 ||
- fieldName.indexOf('sales_show_type') !== -1 ||
- fieldName.indexOf('keywords') !== -1 ||
- fieldName.indexOf('description') !== -1 ||
- fieldName.indexOf('status') !== -1) {
- return '#sales';
- }
- }
-
- // 根据字段所在的选项卡容器判断
- if ($field && $field.length > 0) {
- var $tabPane = $field.closest('.tab-pane');
- if ($tabPane.length > 0) {
- var tabId = '#' + $tabPane.attr('id');
- return tabId;
- }
- }
-
- // 默认返回基础信息选项卡
- return '#basics';
- },
-
- // 高亮错误字段
- highlightErrorField: function($field) {
- if ($field && $field.length > 0) {
- $field.addClass('error-highlight');
- setTimeout(function() {
- $field.removeClass('error-highlight');
- }, 3000);
-
- // 滚动到字段位置
- var fieldOffset = $field.offset();
- if (fieldOffset) {
- $('html, body').animate({
- scrollTop: fieldOffset.top - 100
- }, 300);
- }
- }
- },
-
- // 验证整个表单并定位到错误选项卡
- validateFormAndShowErrors: function() {
- var that = this;
- var firstErrorTab = null;
- var errorMessage = '';
-
- console.log('开始全面验证表单');
-
- // 验证所有选项卡
- var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
-
- tabs.forEach(function(tabId) {
- that.clearTabError(tabId);
-
- var result = null;
- switch(tabId) {
- case '#basics':
- result = that.validateBasicsTab();
- break;
- case '#skus':
- result = that.validateSkusTab();
- break;
- case '#delivery':
- result = that.validateDeliveryTab();
- break;
- case '#detail':
- result = that.validateDetailTab();
- break;
- case '#sales':
- result = that.validateSalesTab();
- break;
- }
-
- console.log('选项卡', tabId, '验证结果:', result);
-
- if (result && !result.valid) {
- that.showTabError(tabId, result.message || result.errors.join('、'));
- if (!firstErrorTab) {
- firstErrorTab = tabId;
- errorMessage = result.message || result.errors.join('、');
- }
- }
- });
-
- // 如果有错误,切换到第一个错误选项卡
- if (firstErrorTab) {
- console.log('发现错误选项卡:', firstErrorTab, '错误信息:', errorMessage);
-
- var $errorTab = $('.nav-tabs a[href="' + firstErrorTab + '"]');
- if ($errorTab.length > 0) {
- console.log('切换到错误选项卡:', firstErrorTab);
- $errorTab.tab('show');
-
- // 显示错误提示
- Toastr.error(errorMessage);
-
- // 延迟聚焦到第一个错误字段
- setTimeout(function() {
- that.focusFirstErrorFieldInTab(firstErrorTab);
- }, 500);
- }
- $('html, body').animate({scrollTop: 0}, 300);
- return false;
- }
-
- console.log('表单验证通过');
- return true;
- },
-
- // 聚焦到指定选项卡的第一个错误字段
- focusFirstErrorFieldInTab: function(tabId) {
- var $tabPane = $(tabId);
- if ($tabPane.length === 0) return;
-
- var $errorField = null;
-
- // 查找第一个验证失败的字段
- $errorField = $tabPane.find('input[data-rule]:invalid, select[data-rule]:invalid, textarea[data-rule]:invalid').first();
-
- // 如果没有找到invalid字段,查找必填但为空的字段
- if (!$errorField || $errorField.length === 0) {
- $errorField = $tabPane.find('input[data-rule*="required"]:visible').filter(function() {
- return !$(this).val();
- }).first();
- }
-
- if (!$errorField || $errorField.length === 0) {
- $errorField = $tabPane.find('select[data-rule*="required"]:visible').filter(function() {
- return !$(this).val();
- }).first();
- }
-
- // 聚焦并高亮错误字段
- if ($errorField && $errorField.length > 0) {
- $errorField.focus();
- this.highlightErrorField($errorField);
- }
- },
-
- // 初始化上架时间和下架时间控制
- initOnlineOfflineControl: function() {
- // 上架时间类型切换事件
- $('input[name="row[online_type]"]').change(function() {
- var value = $(this).val();
- // 当类型为定时上架(3)时,显示上架时间选择
- if (value == '3') {
- $('#scheduled-online-time').show();
- } else {
- $('#scheduled-online-time').hide();
- }
-
- // 当类型为立即上架(1)或定时上架(3)时,显示定时下架选项
- if (value == '1' || value == '3') {
- $('#offline-time-setting').show();
- } else {
- $('#offline-time-setting').hide();
- }
- });
-
- // 初始执行一次,设置默认状态
- $('input[name="row[online_type]"]:checked').trigger('change');
-
- // 定时下架复选框切换事件
- $('#c-is_auto_offline').change(function() {
- if ($(this).is(':checked')) {
- $('#scheduled-offline-time').show();
- } else {
- $('#scheduled-offline-time').hide();
- }
- });
-
- // 初始执行一次,检查定时下架复选框状态
- if ($('#c-is_auto_offline').is(':checked')) {
- $('#scheduled-offline-time').show();
- } else {
- $('#scheduled-offline-time').hide();
- }
- },
-
-
- // 初始化商品详情预览功能
- initContentPreview: function() {
- // 设置定时刷新预览
- var previewTimer = null;
- var lastContent = "";
-
- // 监听标签页切换,确保切换到详情标签页时刷新预览
- $('a[href="#detail"]').on('shown.bs.tab', function (e) {
- updatePreview();
-
- // 设置定时器,每隔1秒检查内容是否有变化
- if (previewTimer === null) {
- previewTimer = setInterval(function() {
- checkContentChange();
- }, 1000);
- }
- });
-
- // 离开详情标签页时清除定时器
- $('a').not('a[href="#detail"]').on('shown.bs.tab', function (e) {
- if (previewTimer) {
- clearInterval(previewTimer);
- previewTimer = null;
- }
- });
-
- // 检查内容变化
- function checkContentChange() {
- var editor = $("#c-content").data("nkeditor");
- if (!editor) return;
-
- var content = editor.html();
- if (content !== lastContent) {
- lastContent = content;
- updatePreview();
- }
- }
-
- // 更新预览内容
- function updatePreview() {
- // 获取编辑器实例
- var editor = $("#c-content").data("nkeditor");
- if (!editor) return;
-
- // 获取编辑器内容
- var content = editor.html();
-
- // 更新预览区域
- $('#content-preview').html(content || '<div class="text-center text-muted">暂无内容</div>');
-
- // 调整预览区域的高度
- adjustPreviewHeight();
- }
-
- // 调整预览区域高度,使其与编辑器一致
- function adjustPreviewHeight() {
- var $editorContainer = $('.ke-container');
- if ($editorContainer.length > 0) {
- var editorHeight = $editorContainer.height();
- $('#content-preview').css('height', editorHeight - 40 + 'px');
- }
- }
-
- // 初始预览
- setTimeout(function() {
- adjustPreviewHeight();
- updatePreview();
- }, 1000);
- },
-
- // 格式化SKU规格属性显示
- formatSkuAttr: function(skuAttr) {
- if (!skuAttr) {
- return '';
- }
-
- try {
- // 尝试解析JSON格式
- var attrs = JSON.parse(skuAttr);
- if (Array.isArray(attrs)) {
- var formatted = [];
- attrs.forEach(function(attr) {
- if (attr.name && attr.value) {
- formatted.push(attr.name + ': ' + attr.value);
- }
- });
- return formatted.join(' | ');
- }
- } catch (e) {
- // 兼容旧的字符串格式:规格名:规格值,规格名:规格值
- if (skuAttr.indexOf(':') !== -1) {
- var attrs = skuAttr.split(',');
- var formatted = [];
- attrs.forEach(function(attr) {
- if (attr.indexOf(':') !== -1) {
- var parts = attr.split(':');
- if (parts.length >= 2) {
- formatted.push(parts[0].trim() + ': ' + parts.slice(1).join(':').trim());
- }
- }
- });
- return formatted.join(' | ');
- }
- }
-
- return skuAttr;
- },
-
- // 显示表单错误并定位到对应选项卡
- showFormError: function(ret) {
- var message = ret.msg || '操作失败';
- var errorTab = this.getErrorTab(message);
-
- // 如果能定位到具体选项卡,显示错误
- if (errorTab) {
- var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
- if ($tabLink.length > 0 && !$tabLink.hasClass('tab-error')) {
- $tabLink.addClass('tab-error');
- if ($tabLink.find('.error-icon').length === 0) {
- $tabLink.append(' <i class="fa fa-exclamation-circle error-icon"></i>');
- }
- $tabLink.attr('title', message);
- if ($tabLink.tooltip) {
- try {
- $tabLink.tooltip('destroy').tooltip({
- placement: 'top',
- title: message
- });
- } catch (e) {
- console.log('tooltip错误:', e);
- }
- }
- }
- }
-
- // 显示错误提示
- Toastr.error(message);
- },
-
- // 跳转到有错误的选项卡
- jumpToErrorTab: function(ret) {
- var that = this;
- var message = ret.msg || '操作失败';
- var errorTab = null;
-
- // 首先尝试从错误信息判断选项卡
- errorTab = this.getErrorTab(message);
-
- // 如果无法从错误信息判断,则进行全面验证
- if (!errorTab) {
- errorTab = this.findFirstErrorTab();
- }
-
- // 跳转到错误选项卡
- if (errorTab) {
- var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
- if ($tabLink.length > 0) {
- // 切换到对应选项卡
- $tabLink.tab('show');
-
- // 滚动到页面顶部
- $('html, body').animate({scrollTop: 0}, 300);
-
- // 延迟聚焦到第一个错误字段
- setTimeout(function() {
- that.focusFirstErrorField(errorTab);
- }, 500);
- }
- }
- },
-
- // 根据错误信息获取对应的选项卡
- getErrorTab: function(message) {
- if (!message) return null;
-
- // 基础信息相关错误
- if (message.indexOf('商品类型') !== -1 ||
- message.indexOf('商品编码') !== -1 ||
- message.indexOf('商品标题') !== -1 ||
- message.indexOf('商品分类') !== -1 ||
- message.indexOf('主图') !== -1 ||
- message.indexOf('图片') !== -1 ||
- message.indexOf('品牌') !== -1) {
- return '#basics';
- }
-
- // 价格库存相关错误
- if (message.indexOf('价格') !== -1 ||
- message.indexOf('库存') !== -1 ||
- message.indexOf('SKU') !== -1 ||
- message.indexOf('规格') !== -1 ||
- message.indexOf('销售价') !== -1 ||
- message.indexOf('市场价') !== -1) {
- return '#skus';
- }
-
- // 配送设置相关错误
- if (message.indexOf('配送') !== -1 ||
- message.indexOf('运费') !== -1 ||
- message.indexOf('快递') !== -1 ||
- message.indexOf('运费模板') !== -1) {
- return '#delivery';
- }
-
- // 商品详情相关错误
- if (message.indexOf('详情') !== -1 ||
- message.indexOf('内容') !== -1) {
- return '#detail';
- }
-
- // 销售设置相关错误
- if (message.indexOf('库存显示') !== -1 ||
- message.indexOf('销量显示') !== -1 ||
- message.indexOf('关键词') !== -1 ||
- message.indexOf('描述') !== -1) {
- return '#sales';
- }
-
- return null;
- },
-
- // 查找第一个有错误的选项卡
- findFirstErrorTab: function() {
- var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
-
- console.log('开始查找第一个有错误的选项卡');
-
- for (var i = 0; i < tabs.length; i++) {
- var tabId = tabs[i];
- var result = null;
-
- console.log('检查选项卡:', tabId);
-
- try {
- switch(tabId) {
- case '#basics':
- result = this.validateBasicsTab();
- break;
- case '#skus':
- result = this.validateSkusTab();
- break;
- case '#delivery':
- result = this.validateDeliveryTab();
- break;
- case '#detail':
- result = this.validateDetailTab();
- break;
- case '#sales':
- result = this.validateSalesTab();
- break;
- }
-
- console.log('选项卡 ' + tabId + ' 验证结果:', result);
-
- if (result && !result.valid) {
- console.log('找到第一个错误选项卡:', tabId, '错误:', result.errors);
- return tabId;
- }
- } catch (e) {
- console.error('验证选项卡 ' + tabId + ' 时出错:', e);
- }
- }
-
- console.log('没有找到错误选项卡');
- return null;
- },
-
- // 聚焦到第一个错误字段
- focusFirstErrorField: function(tabId) {
- var $activeTabPane = $(tabId);
- if ($activeTabPane.length === 0) return;
-
- // 查找第一个有错误的必填字段
- var $errorField = null;
-
- switch(tabId) {
- case '#basics':
- // 按优先级查找错误字段
- $errorField = $activeTabPane.find('#c-goods_sn:invalid, #c-goods_sn[value=""]').first();
- if ($errorField.length === 0) {
- $errorField = $activeTabPane.find('#c-title:invalid, #c-title[value=""]').first();
- }
- if ($errorField.length === 0) {
- // 对于多选的selectpage控件,需要特殊处理
- var $categoryField = $activeTabPane.find('#c-category_id, #c-category_ids').first();
- if ($categoryField.length > 0) {
- var categoryVal = $categoryField.val();
- if (Controller.isMultiSelectEmpty(categoryVal)) {
- $errorField = $categoryField;
- }
- }
- }
- if ($errorField.length === 0) {
- $errorField = $activeTabPane.find('#c-image:invalid, #c-image[value=""]').first();
- }
- break;
-
- case '#skus':
- // 检查规格类型
- var specType = $('input[name="row[spec_type]"]:checked').val();
- if (specType == '0') {
- $errorField = $activeTabPane.find('#c-price:invalid, #c-price[value=""]').first();
- if ($errorField.length === 0) {
- $errorField = $activeTabPane.find('#c-stocks:invalid, #c-stocks[value=""]').first();
- }
- }
- break;
-
- case '#delivery':
- $errorField = $activeTabPane.find('#c-express_template_id:invalid, #c-express_template_id[value=""]').first();
- break;
-
- case '#sales':
- $errorField = $activeTabPane.find('input[name="row[stock_show_type]"]:invalid').first();
- if ($errorField.length === 0) {
- $errorField = $activeTabPane.find('input[name="row[sales_show_type]"]:invalid').first();
- }
- break;
- }
-
- // 如果没有找到特定的错误字段,查找第一个有data-rule的空字段
- if (!$errorField || $errorField.length === 0) {
- $errorField = $activeTabPane.find('input[data-rule]:invalid, input[data-rule][value=""], select[data-rule]:invalid, select[data-rule][value=""], textarea[data-rule]:invalid, textarea[data-rule][value=""]').first();
- }
-
- // 聚焦并高亮错误字段
- if ($errorField && $errorField.length > 0) {
- $errorField.focus();
-
- // 添加错误高亮效果
- $errorField.addClass('error-highlight');
- setTimeout(function() {
- $errorField.removeClass('error-highlight');
- }, 2000);
-
- // 滚动到字段位置
- var fieldOffset = $errorField.offset();
- if (fieldOffset) {
- $('html, body').animate({
- scrollTop: fieldOffset.top - 100
- }, 300);
- }
- }
- },
-
- // 验证基础信息选项卡
- validateBasicsTab: function() {
- var isValid = true;
- var errors = [];
-
- console.log('验证基础信息选项卡');
-
- // 检查商品类型
- if (!$('input[name="row[type]"]:checked').length) {
- isValid = false;
- errors.push('请选择商品类型');
- }
-
- // 检查商品编码
- var $goodsSn = $('#c-goods_sn');
- var goodsSnVal = $goodsSn.val();
- console.log('商品编码值:', goodsSnVal);
- if ($goodsSn.length > 0 && $goodsSn.attr('data-rule') && $goodsSn.attr('data-rule').indexOf('required') !== -1) {
- if (!goodsSnVal || goodsSnVal.trim() === '') {
- isValid = false;
- errors.push('商品编码不能为空');
- }
- }
-
- // 检查商品标题
- var $title = $('#c-title');
- var titleVal = $title.val();
- console.log('商品标题值:', titleVal);
- if ($title.length > 0 && $title.attr('data-rule') && $title.attr('data-rule').indexOf('required') !== -1) {
- if (!titleVal || titleVal.trim() === '') {
- isValid = false;
- errors.push('商品标题不能为空');
- }
- }
-
- // 检查分类 - 多选控件(兼容不同页面的字段ID)
- var $categoryId = $('#c-category_id, #c-category_ids').first();
- var categoryVal = $categoryId.val();
- console.log('商品分类值:', categoryVal);
- if ($categoryId.length > 0 && $categoryId.attr('data-rule') && $categoryId.attr('data-rule').indexOf('required') !== -1) {
- if (Controller.isMultiSelectEmpty(categoryVal)) {
- isValid = false;
- errors.push('商品分类不能为空');
- console.log('商品分类验证失败');
- }
- }
-
- // 检查主图
- var $image = $('#c-image');
- var imageVal = $image.val();
- console.log('主图值:', imageVal);
- if ($image.length > 0 && $image.attr('data-rule') && $image.attr('data-rule').indexOf('required') !== -1) {
- if (!imageVal || imageVal.trim() === '') {
- isValid = false;
- errors.push('商品主图不能为空');
- }
- }
-
- // 检查轮播图
- var $images = $('#c-images');
- var imagesVal = $images.val();
- console.log('轮播图值:', imagesVal);
- if ($images.length > 0 && $images.attr('data-rule') && $images.attr('data-rule').indexOf('required') !== -1) {
- if (!imagesVal || imagesVal.trim() === '') {
- isValid = false;
- errors.push('商品轮播图不能为空');
- }
- }
-
- console.log('基础信息验证结果:', {valid: isValid, errors: errors});
- return {
- valid: isValid,
- errors: errors
- };
- },
-
- // 验证价格库存选项卡
- validateSkusTab: function() {
- var isValid = true;
- var errors = [];
-
- // 检查规格类型
- var specType = $('input[name="row[spec_type]"]:checked').val();
- console.log('验证价格库存选项卡, 规格类型:', specType);
-
- if (specType == '0') {
- // 单规格验证
- var $price = $('#c-price');
- var priceVal = $price.val();
- console.log('价格字段值:', priceVal);
- if (!priceVal || priceVal.trim() === '' || parseFloat(priceVal) <= 0) {
- isValid = false;
- errors.push('销售价必须大于0');
- }
-
- var $stocks = $('#c-stocks');
- var stocksVal = $stocks.val();
- console.log('库存字段值:', stocksVal);
- if (!stocksVal || stocksVal.trim() === '' || parseInt(stocksVal) <= 0) {
- isValid = false;
- errors.push('库存必须大于0');
- }
- } else if (specType == '1') {
- // 多规格验证
- if (typeof vm === 'undefined' || !vm || !vm.specList || vm.specList.length === 0) {
- isValid = false;
- errors.push('请设置商品规格');
- } else {
- // 检查是否有有效的规格组合
- if (!vm.tableData || vm.tableData.length === 0) {
- isValid = false;
- errors.push('请设置规格组合数据');
- } else {
- // 检查每个有效的SKU是否有正确的价格和库存
- var hasValidSku = false;
- var validSkuCount = 0;
-
- console.log('第二次验证: 检查SKU数据, tableData长度:', vm.tableData.length);
-
- for (var i = 0; i < vm.tableData.length; i++) {
- var sku = vm.tableData[i];
- console.log('第二次验证: 检查SKU[' + i + ']:', {
- status: sku.status,
- price: sku.price,
- stocks: sku.stocks
- });
-
- // 只检查状态为显示的SKU
- var isVisible = (sku.status === 1 || sku.status === '1' || sku.status === true);
-
- console.log('第二次验证: SKU[' + i + '] 显示状态:', sku.status, '可见:', isVisible);
-
- if (isVisible) {
- var price = parseFloat(sku.price);
- var stocks = parseInt(sku.stocks);
-
- console.log('第二次验证: SKU[' + i + '] 检查通过, price:', price, 'stocks:', stocks);
-
- hasValidSku = true;
- validSkuCount++;
-
- // 验证价格必须大于0
- if (!price || price <= 0) {
- isValid = false;
- errors.push('SKU销售价必须大于0');
- console.log('第二次验证: SKU[' + i + ']销售价验证失败:', price);
- break;
- }
-
- // 验证库存
- if (isNaN(stocks) || stocks <= 0) {
- isValid = false;
- errors.push('SKU库存必须大于0');
- console.log('第二次验证: SKU[' + i + ']库存验证失败:', stocks);
- break;
- }
- }
- }
-
- console.log('第二次验证: 有效SKU数量:', validSkuCount);
-
- if (!hasValidSku) {
- isValid = false;
- errors.push('请至少设置一个有效的SKU');
- console.log('第二次验证: 没有有效的SKU');
- }
- }
- }
- } else {
- // 如果没有选择规格类型
- isValid = false;
- errors.push('请选择规格类型');
- }
-
- console.log('价格库存验证结果:', {valid: isValid, errors: errors});
- return {
- valid: isValid,
- errors: errors
- };
- },
-
- // 验证配送设置选项卡
- validateDeliveryTab: function() {
- var isValid = true;
- var errors = [];
-
- // 检查配送方式
- var deliveryType = $('input[name="row[delivery_type]"]:checked').val();
-
- if (deliveryType === 'EXPRESS') {
- // 如果选择快递配送,检查运费设置
- var expressType = $('input[name="row[express_type]"]:checked').val();
-
- if (expressType === '3') {
- // 使用运费模板
- var $templateId = $('#c-express_template_id');
- if ($templateId.length > 0 && !$templateId.val()) {
- isValid = false;
- errors.push('请选择运费模板');
- }
- } else if (expressType === '2') {
- // 固定运费
- var $expressPrice = $('#c-express_price');
- if ($expressPrice.length > 0 && (!$expressPrice.val() || parseFloat($expressPrice.val()) < 0)) {
- isValid = false;
- errors.push('请设置正确的运费');
- }
- }
- }
-
- return {
- valid: isValid,
- errors: errors
- };
- },
-
- // 验证商品详情选项卡
- validateDetailTab: function() {
- // 详情一般不做必填验证,返回有效
- return {
- valid: true,
- errors: []
- };
- },
-
- // 验证销售设置选项卡
- validateSalesTab: function() {
- var isValid = true;
- var errors = [];
-
- // 检查库存显示类型
- var stockShowType = $('input[name="row[stock_show_type]"]:checked').val();
- if (!stockShowType) {
- isValid = false;
- errors.push('请选择库存显示方式');
- }
-
- // 检查销量显示类型
- var salesShowType = $('input[name="row[sales_show_type]"]:checked').val();
- if (!salesShowType) {
- isValid = false;
- errors.push('请选择销量显示方式');
- }
-
- return {
- valid: isValid,
- errors: errors
- };
- },
- api: {
- // 初始化规格类型控制
- initSpecTypeControl: function() {
- // 监听规格类型切换
- $('input[name="row[spec_type]"]').off('change.spectype').on('change.spectype', function() {
- var specType = $(this).val();
- console.log('规格类型切换为:', specType);
-
- // 使用FastAdmin的Favisible系统自动控制显示隐藏
- $(document).trigger('fa.event.favisible');
-
- // 如果切换到单规格,清空多规格数据(可选)
- if (specType == '0' && typeof vm !== 'undefined' && vm) {
- console.log('切换到单规格,清空多规格数据');
- // vm.specList = [];
- // vm.tableData = [];
- }
-
- // 如果切换到多规格,确保Vue组件已初始化
- if (specType == '1' && typeof vm !== 'undefined' && vm) {
- console.log('切换到多规格');
- var $multiSpecForm = $('#multi-spec-form');
- if ($multiSpecForm.length > 0 && !$multiSpecForm.is(':visible')) {
- setTimeout(function() {
- $(document).trigger('fa.event.favisible');
- }, 100);
- }
- }
- });
-
- // 初始触发一次,确保默认状态正确
- $('input[name="row[spec_type]"]:checked').trigger('change.spectype');
- },
-
- bindevent: function () {
- $(document).on("click", ".btn-legal", function (a) {
- Fast.api.ajax({
- url: "shop/ajax/check_content_islegal",
- data: {content: $("#c-content").val()}
- }, function (data, ret) {
- }, function (data, ret) {
- if ($.isArray(data)) {
- Layer.alert(__('Banned words') + ":" + data.join(","));
- }
- });
- });
- $(document).on("click", ".btn-keywords", function (a) {
- Fast.api.ajax({
- url: "shop/ajax/get_content_keywords",
- data: {title: $("#c-title").val(), content: $("#c-content").val()}
- }, function (data, ret) {
- $("#c-keywords").val(data.keywords);
- $("#c-description").val(data.description);
- });
- });
- // 绑定FastAdmin表单验证事件
- var $form = $("form[role=form]");
-
- // 监听提交按钮点击事件,在表单验证前进行自定义验证
- $form.find('button[type="submit"], input[type="submit"]').off('click.tabvalidation').on('click.tabvalidation', function(e) {
- console.log('提交按钮被点击,开始验证');
-
- // 进行自定义验证
- if (!Controller.validateFormAndShowErrors()) {
- console.log('自定义验证失败,阻止表单提交');
- e.preventDefault();
- e.stopPropagation();
- return false;
- }
-
- console.log('自定义验证通过,继续表单提交流程');
- });
-
- // 使用FastAdmin标准方式绑定表单事件
- Form.api.bindevent($form, function (data, ret) {
- // 提交成功回调
- Controller.clearTabErrors();
- }, function (data, ret) {
- // 提交失败回调
- Controller.showFormError(ret);
- Controller.jumpToErrorTab(ret);
- }, function (success, error) {
- // 提交前验证和数据处理
- console.log('开始提交表单数据');
-
- // 清除所有选项卡错误标记
- Controller.clearTabErrors();
-
- // 进行表单验证,如果失败则跳转到错误选项卡
- var validator = $form.data('validator');
- if (validator) {
- console.log('检查表单验证状态');
- // 手动触发验证
- var isValid = validator.isFormValid();
- console.log('表单验证结果:', isValid);
-
- if (!isValid) {
- console.log('表单验证失败,开始处理错误');
- Controller.handleValidationError(validator);
- return false;
- }
- } else {
- console.log('validator不存在,使用自定义验证');
- // 如果validator不存在,使用我们的自定义验证
- if (!Controller.validateFormAndShowErrors()) {
- console.log('自定义验证失败');
- return false;
- }
- }
-
- let skus = '[]', spec = '[]';
- var specType = $('input[name="row[spec_type]"]:checked').val();
-
- console.log('当前规格类型:', specType);
- console.log('vm对象:', typeof vm !== 'undefined' ? vm : 'undefined');
-
- if (specType == '1') {
- // 多规格处理
- if (typeof vm !== 'undefined' && vm && vm.tableData && vm.tableData.length > 0) {
- console.log('处理多规格商品, tableData长度:', vm.tableData.length);
-
- try {
- // 不需要特殊处理,直接传输所有数据
- // 后端会根据status字段判断SKU是否有效
- skus = JSON.stringify(vm.tableData);
- spec = JSON.stringify(vm.specList || []);
- console.log('多规格数据处理完成');
- console.log('规格数据 (spec):', vm.specList);
- console.log('SKU数据 (skus):', vm.tableData);
- console.log('规格数据JSON:', spec);
-
- // 检查规格值中是否包含图片
- vm.specList.forEach(function(spec, specIndex) {
- if (spec.value && spec.value.length > 0) {
- spec.value.forEach(function(value, valueIndex) {
- if (value.image) {
- console.log('规格[' + specIndex + ']值[' + valueIndex + ']包含图片:', value.image);
- }
- });
- }
- });
- } catch (e) {
- console.log('多规格处理出错:', e);
- Toastr.error('多规格数据处理失败');
- return false;
- }
- } else {
- console.log('多规格数据不完整');
- Toastr.error('请设置完整的多规格数据');
- return false;
- }
- } else {
- // 单规格处理 - 统一使用skus和spec格式
- console.log('处理单规格商品');
-
- var singleSku = {
- sku_sn: $('#c-sku-sn').val() || $('#c-goods_sn').val() || '',
- price: parseFloat($('#c-price').val()) || 0,
- lineation_price: parseFloat($('#c-lineation_price').val()) || 0,
- cost_price: parseFloat($('#c-cost_price').val()) || 0,
- stocks: parseInt($('#c-stocks').val()) || 0,
- weight: parseFloat($('#c-weight').val()) || 0,
- volume: parseFloat($('#c-volume').val()) || 0,
- image: $('#c-single-image').val() || '',
- sales: 0,
- status: 1,
- is_default: 1,
- skus: []
- };
- skus = JSON.stringify([singleSku]);
- spec = JSON.stringify([]);
- console.log('单规格数据处理完成', singleSku);
- }
-
- //绑定商品属性
- let html = `<textarea id="c-skus" class="form-control hide" rows="5" name="row[skus]" cols="50">${skus}</textarea>
- <textarea id="c-spec" class="form-control hide" rows="5" name="row[spec]" cols="50">${spec}</textarea>`;
- this.find('#goods-sku').html(html);
- console.log(html);
- //提交表单
- Form.api.submit(this, success, error);
- return false;
- });
- require(['backend/shop/card'], function (Card) {
- Card.api.bindcardevent();
- });
- },
- bindUpload: function () {
- if ($('.goods-sku-table table td.td-img button.faupload:not([initialized])').length === 0) {
- return;
- }
- clearTimeout(si);
- si = setTimeout(function () {
- let doms = $('.goods-sku-table table td.td-img').toArray();
- function uploadButtonTask(deadline) {
- while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && doms.length > 0) {
- bindEvent();
- }
- if (doms.length > 0)
- requestIdleCallback(uploadButtonTask);
- }
- function bindEvent() {
- var dom = doms.shift();
- if (dom) {
- var $elements = $(".faselect,.fachoose", dom);
- if ($elements && $elements.length > 0) {
- $elements.off('click');
- }
- Form.events.plupload(dom);
- Form.events.faselect(dom);
- }
- }
- requestIdleCallback(uploadButtonTask, {timeout: 1000});
- }, 250);
- },
- add_sku: function () {
- //移除属性的
- $('.td-img').find('.faupload').removeAttr('initialized');
-
- require(['vue'], function (Vue) {
- vm = new Vue({
- el: '#vue-app',
- computed: {
- specValueText() {
- return (skus, k) => {
- return !skus || typeof skus[k] == 'undefined' ? '' : skus[k];
- }
- },
- contentHtml() {
- return field => {
- return `<div class='input-group'>
- <input class='form-control' type='text' value=''/>
- <div class='input-group-btn'>
- <span class='btn btn-success sku-confirm' data-field='${field}'>
- 确定
- </span>
- </div>
- </div>`;
- }
- }
- },
- watch: {
- specList: {
- handler: function (val) {
- this.renderTableData(val);
- // 延迟绑定上传功能,确保DOM更新完成
- var that = this;
- that.$nextTick(function() {
- Controller.api.bindSpecValueUpload();
- Controller.api.rebindMultipleEdit();
- // 重新绑定规格值上传按钮
- setTimeout(function() {
- Controller.api.bindUploadButtons();
- // 更新图片预览
- that.updateSpecImagePreviews();
- }, 300);
- });
- },
- deep: true
- }
- },
- data() {
- return {
- spec_name: '',
- specList: [],
- tableData: [],
- result: [],
- skus: [], //
- defaultSpecIndex: 0 // 默认规格索引
- }
- },
- mounted() {
- let that = this;
- that.init();
-
- // 延迟初始化规格类型切换,确保DOM完全渲染
- setTimeout(function() {
- Controller.api.initSpecTypeControl();
- // 初始绑定规格值上传功能
- Controller.api.bindSpecValueUpload();
-
- // 如果是编辑模式且是多规格商品,确保多规格表单显示
- if (Config.goods && Config.goods.spec_type == '1') {
- console.log('编辑模式:显示多规格表单');
- var $multiSpecForm = $('#multi-spec-form');
- if ($multiSpecForm.length > 0) {
- $multiSpecForm.show();
- console.log('多规格表单已显示');
- }
- }
- }, 100);
-
- //批量设置
- this.$nextTick(function () {
- $('body').on('click', function (e) {
- if (!$(e.target).hasClass('multiple-edit') &&
- $(e.target).parents('.multiple-edit').length === 0 &&
- $(e.target).parents('.popover.in').length === 0) {
- $('.multiple-edit').popover('hide');
- }
- });
- $(".multiple-edit").popover({
- sanitize: false,
- container: "body",
- html: true,
- placement: "top",
- trigger: 'manual'
- }).on('click', function (e) {
- $(".popover").hide();
- $(this).popover('show');
- });
- $(document).on('click', '.sku-confirm', function () {
- let value = $(this).parent().prev().val().trim();
- let field = $(this).data('field');
- if (field != 'sku_sn' && Number.isNaN(parseFloat(value))) {
- Toastr.error('请输入数字');
- return;
- }
- for (let [index] of that.tableData.entries()) {
- that.$set(that.tableData[index], field, value);
- }
- });
- require(['selectpage'], function () {
- $('.selectpage', $('.spec-template')).selectPage({
- eAjaxSuccess: function (data) {
- data.totalRow = data.total;
- return data;
- },
- eSelect: function (row) {
- let spec_names = row.spec_names.split(';');
- let spec_values = row.spec_values.split(';');
- let list = [];
- for (let [i, v] of spec_names.entries()) {
- // 转换规格模板数据为新格式
- let valueList = spec_values[i].split(',').map(val => ({
- name: val,
- image: '',
- description: ''
- }));
-
- list.push({
- name: v,
- type: 'basic', // 默认为基础规格
- value: valueList
- });
- }
- that.tableData = [];
- that.skus = [];
- setTimeout(function () {
- that.specList = list;
- }, 100);
- }
- });
- });
- })
- },
- methods: {
- init() {
- console.log('Vue组件初始化开始');
- console.log('Config数据:', Config);
-
- let skus = [];
- if (Config.goods_skus && Config.goods_skus.length) {
- console.log('发现商品SKU数据,数量:', Config.goods_skus.length);
- console.log('完整SKU数据:', Config.goods_skus);
-
- // 如果是多规格商品,解析规格数据
- if (Config.goods && Config.goods.spec_type == '1') {
- console.log('初始化多规格数据');
- let specList = [];
- let specName = {};
-
- for (let item of Config.goods_skus) {
- console.log('处理SKU项:', item);
- if (item.sku_attr) {
- console.log('SKU属性字符串:', item.sku_attr);
- let sku_attr = item.sku_attr.split(',');
- console.log('分割后的属性数组:', sku_attr);
- let attr = [];
- for (let res of sku_attr) {
- let sku = res.split(':');
- console.log('属性键值对:', sku);
- if (sku.length >= 2) {
- attr.push(sku[1]);
- //属性名
- if (!specName[sku[0]]) {
- specName[sku[0]] = [];
- }
- if (!specName[sku[0]].includes(sku[1])) {
- specName[sku[0]].push(sku[1]);
- }
- } else {
- console.warn('无效的属性格式:', res);
- }
- }
- // 使用字符串作为键,与renderTableData中的查找方式一致
- let attrKey = attr.join(',');
- skus[attrKey] = item;
- console.log('SKU映射:', attrKey, '->', item);
- } else {
- console.warn('SKU缺少sku_attr字段:', item);
- }
- }
- console.log('解析完成的规格名称映射:', specName);
-
- // 构建规格值映射表(从数据库获取的完整数据)
- let specValueMap = {};
- if (Config.spec_values && Config.spec_values.length > 0) {
- console.log('发现规格值数据:', Config.spec_values);
- console.log('规格值数据类型:', typeof Config.spec_values);
- console.log('规格值数据结构样例:', Config.spec_values[0]);
-
- Config.spec_values.forEach(function(item) {
- if (!specValueMap[item.spec_name]) {
- specValueMap[item.spec_name] = {};
- }
- specValueMap[item.spec_name][item.value] = {
- name: item.value,
- image: item.image || '',
- description: item.description || ''
- };
- });
- console.log('规格值映射表:', specValueMap);
- } else {
- console.log('没有发现规格值数据,使用默认处理方式');
- console.log('Config.spec_values:', Config.spec_values);
- }
-
- for (let i in specName) {
- // 转换旧格式数据为新格式,优先使用数据库中的完整数据
- let valueList = specName[i].map(val => {
- if (typeof val === 'string') {
- // 从映射表中查找完整数据,如果没有则使用默认值
- if (specValueMap[i] && specValueMap[i][val]) {
- console.log('找到规格值完整数据:', i, val, specValueMap[i][val]);
- return {
- name: specValueMap[i][val].name,
- image: specValueMap[i][val].image || '',
- description: specValueMap[i][val].description || ''
- };
- } else {
- console.log('使用默认规格值数据:', i, val);
- return {
- name: val,
- image: '',
- description: ''
- };
- }
- }
- // 如果已经是对象格式,确保结构完整
- return {
- name: val.name || val,
- image: val.image || '',
- description: val.description || ''
- };
- });
-
- specList.push({
- name: i,
- type: 'basic', // 默认为基础规格
- value: valueList
- });
- }
-
- this.skus = skus;
- this.specList = specList;
- console.log('多规格初始化完成,规格数量:', specList.length);
- console.log('规格列表:', specList);
-
- // 延迟触发数据渲染,确保DOM已准备好
- this.$nextTick(() => {
- console.log('Vue nextTick: 准备渲染多规格表格数据');
- if (this.specList.length > 0) {
- this.renderTableData(this.specList);
-
- // 在数据渲染完成后,更新规格值图片预览
- setTimeout(() => {
- this.updateSpecImagePreviews();
- }, 500);
- }
- });
- }
- }
-
- console.log('Vue组件初始化完成');
- },
- addSpec() {
- if (!this.spec_name.trim()) {
- Toastr.error('请输入规格名称');
- return;
- }
- if (this.specList.some(item => item.name == this.spec_name)) {
- Toastr.error('已存在规格名称');
- return;
- }
- this.specList.push({
- name: this.spec_name,
- type: 'basic', // 默认为基础规格
- value: [{
- name: '',
- image: '',
- description: ''
- }]
- });
- this.spec_name = '';
- },
- showAddSpecForm() {
- // 添加新的规格
- this.specList.push({
- name: '',
- type: 'basic', // 默认为基础规格
- value: [{
- name: '',
- image: '',
- description: ''
- }]
- });
- },
- addSpecValue(key) {
- this.specList[key].value.push({
- name: '',
- image: '',
- description: ''
- });
-
- // 重新绑定上传功能
- this.$nextTick(function() {
- setTimeout(function() {
- Controller.api.bindUploadButtons();
- }, 100);
- });
- },
- removeSpecValue(key, index) {
- this.specList[key].value.splice(index, 1);
- },
- //渲染表格数据
- renderTableData(list) {
- // 判断是否为编辑模式
- const isEditMode = Config.goods && Config.goods.id;
-
- // 统一的默认值 - 新增模式使用固定默认值
- const defaultValues = {
- goods_sn: $('#c-goods_sn').val() || '',
- price: '0.01',
- lineation_price: '0.00',
- cost_price: '0.00',
- weight: '0.00',
- volume: '0.00',
- stocks: '1'
- };
-
- let columns = [];
- this.result = [];
- this.resetSpec(list, 0);
-
- console.log('渲染表格数据,模式:', isEditMode ? '编辑' : '新增');
- console.log('固定默认值:', defaultValues);
- console.log('SKU数据映射:', this.skus);
-
- //渲染表格数据
- this.result.forEach((item, index) => {
- let su = this.skus[item];
- console.log('处理规格组合[' + index + ']:', item, '对应SKU数据:', su);
-
- let row;
-
- if (isEditMode && su) {
- // 编辑模式:完全使用后台SKU数据
- console.log('编辑模式:使用后台SKU数据:', su);
- row = {
- skus: item ? item.split(',') : [],
- sku_sn: su.sku_sn || '',
- image: su.image || '',
- price: parseFloat(su.price) || 0,
- lineation_price: parseFloat(su.lineation_price) || 0,
- cost_price: parseFloat(su.cost_price) || 0,
- weight: parseFloat(su.weight) || 0,
- volume: parseFloat(su.volume) || 0,
- stocks: parseInt(su.stocks) || 0,
- sales: parseInt(su.sales) || 0,
- status: su.status !== undefined ? parseInt(su.status) : 1,
- is_default: su.is_default !== undefined ? parseInt(su.is_default) : 0
- };
- console.log('编辑模式最终行数据:', row);
- } else {
- // 新增模式或编辑模式下没有对应SKU数据:使用固定默认值
- console.log('新增模式:使用固定默认值');
- row = {
- skus: item ? item.split(',') : [],
- sku_sn: defaultValues.goods_sn,
- image: '',
- price: defaultValues.price,
- lineation_price: defaultValues.lineation_price,
- cost_price: defaultValues.cost_price,
- weight: defaultValues.weight,
- volume: defaultValues.volume,
- stocks: defaultValues.stocks,
- sales: 0,
- status: 1, // 默认显示状态
- is_default: index === 0 ? 1 : 0 // 第一个SKU默认为默认规格
- };
- console.log('新增模式最终行数据:', row);
- }
-
- // 保留已有的用户修改数据(仅在新增模式下)
- if (!isEditMode) {
- let old = this.tableData[index];
- if (old) {
- console.log('新增模式:保留用户修改的数据:', old);
- for (let i in row) {
- // 只有在新值为空且旧值不为空时才使用旧值
- if ((row[i] === '' || row[i] === 0 || row[i] === '0.00') && old[i]) {
- row[i] = old[i];
- }
- }
- }
- }
-
- columns.push(row);
- });
-
- this.tableData = columns;
- console.log('最终表格数据:', this.tableData);
-
- // 在编辑模式下,设置默认规格的索引
- if (isEditMode) {
- this.defaultSpecIndex = this.tableData.findIndex(item => item.is_default === 1);
- console.log('设置默认规格索引:', this.defaultSpecIndex);
- }
-
- //更新dom,加载事件
- this.$nextTick(function () {
- Controller.api.bindUpload();
- Controller.api.bindSpecValueUpload();
- // 重新绑定批量编辑popover
- Controller.api.rebindMultipleEdit();
- });
- },
- removeSpec(key) {
- this.specList.splice(key, 1);
- },
-
- // 更新规格值图片预览
- updateSpecImagePreviews() {
- console.log('开始更新规格值图片预览');
- this.specList.forEach((spec, specKey) => {
- if (spec.value && spec.value.length > 0) {
- spec.value.forEach((value, valueIndex) => {
- if (value.image) {
- const previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
- const $preview = $('#' + previewId);
- if ($preview.length > 0) {
- const img = '<img src="' + Fast.api.cdnurl(value.image) + '" style="width:40px;height:40px;object-fit:cover;border-radius:4px;border:1px solid #ddd;">';
- $preview.html(img);
- console.log('更新规格值图片预览:', previewId, value.image);
- }
- }
- });
- }
- });
- },
- //组合规格属性
- resetSpec(list, index) {
- if (list[index] != undefined) {
- let value = list[index].value.map(item => typeof item === 'string' ? item : item.name);
- if (!index) {
- this.result = value;
- } else {
- let res = [];
- for (let i of this.result) {
- for (let j of value) {
- res.push(i + ',' + j);
- }
- }
- if (res.length) {
- this.result = res;
- }
- }
- this.resetSpec(list, ++index);
- }
- },
- }
- });
- });
- //情况属性
- $(document).on('click', '.btn-del-sku', function () {
- vm.specList = [];
- vm.tableData = [];
- });
- //监听图片变化赋值
- $(document).on('change', '.sku-images', function () {
- let index = $(this).data('index');
- let value = $(this).val();
- vm.tableData[index].image = value;
- });
- },
-
- // 重新绑定批量编辑功能
- rebindMultipleEdit: function() {
- var $multipleEdit = $(".multiple-edit");
- if (!$multipleEdit || $multipleEdit.length === 0) {
- return;
- }
-
- // 销毁之前的popover
- $multipleEdit.popover('destroy');
-
- // 重新初始化popover
- $multipleEdit.popover({
- sanitize: false,
- container: "body",
- html: true,
- placement: "top",
- trigger: 'manual'
- });
- if ($multipleEdit && $multipleEdit.length > 0) {
- $multipleEdit.off('click.multiple').on('click.multiple', function (e) {
- $(".popover").hide();
- $(this).popover('show');
- });
- }
- },
-
- // 绑定规格值图片上传功能
- bindSpecValueUpload: function() {
- // 检查是否存在规格相关的元素
- if ($('.spec-image-input').length === 0) {
- return;
- }
-
- // 监听规格值图片变化
- $(document).off('change.specvalue', '.spec-image-input');
- $(document).on('change.specvalue', '.spec-image-input', function () {
- var specKey = parseInt($(this).data('spec-key'));
- var valueIndex = parseInt($(this).data('value-index'));
- var imageUrl = $(this).val();
-
- if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
- vm.$set(vm.specList[specKey].value[valueIndex], 'image', imageUrl);
- console.log('规格值图片已更新:', {
- specKey: specKey,
- valueIndex: valueIndex,
- imageUrl: imageUrl,
- specData: vm.specList[specKey].value[valueIndex]
- });
- } else {
- console.warn('无法更新规格值图片,数据结构不正确:', {
- specKey: specKey,
- valueIndex: valueIndex,
- hasVm: !!vm,
- hasSpecList: !!(vm && vm.specList),
- hasSpec: !!(vm && vm.specList && vm.specList[specKey]),
- hasValue: !!(vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex])
- });
- }
- });
-
- // 延迟绑定上传功能,确保DOM已渲染
- setTimeout(function() {
- Controller.api.bindUploadButtons();
- }, 200);
- },
-
- // 绑定上传按钮
- bindUploadButtons: function() {
- // 检查是否存在上传按钮
- if ($('.spec-upload-btn').length === 0) {
- return;
- }
-
- // 延迟执行,确保DOM已完全渲染
- setTimeout(function() {
- require(['upload'], function (Upload) {
- // 绑定规格值上传按钮
- $('.spec-upload-btn:not([initialized])').each(function() {
- var $btn = $(this);
- var specKey = $btn.attr('data-spec-key');
- var valueIndex = $btn.attr('data-value-index');
-
- if (specKey !== undefined && valueIndex !== undefined) {
- $btn.attr('initialized', true);
-
- if ($btn && $btn.length > 0) {
- $btn.off('click.specUpload').on('click.specUpload', function() {
- var inputId = 'c-spec-image-' + specKey + '-' + valueIndex;
- var previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
-
- // 创建临时按钮用于上传
- var tempBtn = $('<button type="button" class="faupload" style="display:none;"></button>');
- tempBtn.attr('data-input-id', inputId);
- tempBtn.attr('data-preview-id', previewId);
- tempBtn.attr('data-mimetype', $btn.attr('data-mimetype'));
- tempBtn.attr('data-multiple', $btn.attr('data-multiple'));
- $('body').append(tempBtn);
-
- // 使用FastAdmin标准上传方法
- Upload.api.upload(tempBtn, function(data, ret) {
- var url = data.url || '';
- console.log('规格值图片上传成功:', {
- inputId: inputId,
- url: url,
- specKey: specKey,
- valueIndex: valueIndex
- });
-
- // 直接更新Vue数据而不是DOM操作
- if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
- vm.$set(vm.specList[specKey].value[valueIndex], 'image', url);
- console.log('Vue数据已更新:', vm.specList[specKey].value[valueIndex]);
- }
-
- // 同时更新输入框的值以保持同步
- $('#' + inputId).val(url);
-
- // 更新预览
- var $preview = $('#' + previewId);
- if (url) {
- var img = '<img src="' + Fast.api.cdnurl(url) + '" style="width:100%;height:100%;object-fit:cover;">';
- $preview.html(img);
- } else {
- $preview.empty();
- }
-
- // 清理临时按钮
- tempBtn.remove();
- }, function(data, ret) {
- // 错误回调
- console.error('上传失败:', ret);
- Toastr.error(ret.msg || '上传失败');
- tempBtn.remove();
- });
-
- // 触发上传
- tempBtn.click();
- });
- }
- }
- });
-
- // 绑定选择按钮
- $('.spec-choose-btn:not([initialized])').each(function() {
- var $btn = $(this);
- if (!$btn || $btn.length === 0) {
- return;
- }
-
- var specKey = $btn.attr('data-spec-key');
- var valueIndex = $btn.attr('data-value-index');
-
- if (specKey !== undefined && valueIndex !== undefined) {
- $btn.attr('initialized', true);
-
- if ($btn && $btn.length > 0) {
- $btn.off('click.specChoose').on('click.specChoose', function() {
- var inputId = 'c-spec-image-' + specKey + '-' + valueIndex;
- var previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
-
- parent.Fast.api.open("general/attachment/select?element_id=" + inputId + "&multiple=false&mimetype=image/*", __('Choose'), {
- callback: function(data) {
- var url = data.url || '';
-
- // 直接更新Vue数据
- if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
- vm.$set(vm.specList[specKey].value[valueIndex], 'image', url);
- console.log('选择图片Vue数据已更新:', vm.specList[specKey].value[valueIndex]);
- }
-
- // 同时更新输入框的值以保持同步
- $('#' + inputId).val(url);
-
- // 更新预览
- var $preview = $('#' + previewId);
- if (url) {
- var img = '<img src="' + Fast.api.cdnurl(url) + '" style="width:100%;height:100%;object-fit:cover;">';
- $preview.html(img);
- } else {
- $preview.empty();
- }
- }
- });
- });
- }
- }
- });
- });
- }, 100);
- },
- // 内容处理
- content: function (value, row, index) {
- var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "350px";
- return "<div style='white-space: nowrap; text-align:left; text-overflow:ellipsis; overflow: hidden; max-width:" + width + ";' title='" + value + "' data-toggle='tooltip' data-placement='right'>" + value + "</div>";
- },
- }
- };
- return Controller;
- });
|