goods.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155
  1. define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
  2. //设置弹窗宽高
  3. Fast.config.openArea = ['80%', '80%'];
  4. var vm, si;
  5. var Controller = {
  6. index: function () {
  7. // 添加列表样式优化
  8. $('<style>')
  9. .prop('type', 'text/css')
  10. .html(`
  11. .bootstrap-table .fixed-table-container {
  12. border: 1px solid #ddd;
  13. }
  14. .bootstrap-table .table th {
  15. background-color: #f8f9fa;
  16. font-weight: 600;
  17. border-bottom: 2px solid #dee2e6;
  18. }
  19. .bootstrap-table .table td {
  20. vertical-align: middle;
  21. padding: 4px 6px;
  22. min-height: 75px;
  23. }
  24. .bootstrap-table .table tr {
  25. border-bottom: 1px solid #f1f3f4;
  26. }
  27. .bootstrap-table .table tbody tr:hover {
  28. background-color: #f8f9fa;
  29. }
  30. .label-xs {
  31. font-size: 10px;
  32. padding: 2px 6px;
  33. }
  34. .goods-info-cell {
  35. word-wrap: break-word;
  36. padding: 3px 5px !important;
  37. max-width: 280px;
  38. overflow: hidden;
  39. }
  40. .goods-info-cell:hover {
  41. background-color: #fafbfc;
  42. }
  43. .goods-info-cell .goods-title {
  44. transition: color 0.3s ease;
  45. }
  46. .goods-info-cell:hover .goods-title {
  47. color: #3498db;
  48. }
  49. .price-cell {
  50. text-align: center;
  51. font-family: 'Arial', sans-serif;
  52. }
  53. .stock-cell {
  54. text-align: center;
  55. }
  56. /* 响应式优化 */
  57. @media (max-width: 1200px) {
  58. .goods-info-cell {
  59. max-width: 220px;
  60. }
  61. }
  62. @media (max-width: 768px) {
  63. .bootstrap-table .table td {
  64. padding: 3px 4px;
  65. font-size: 11px;
  66. min-height: 65px;
  67. }
  68. .goods-info-cell {
  69. max-width: 180px;
  70. }
  71. .goods-info-cell .goods-img {
  72. width: 40px !important;
  73. height: 40px !important;
  74. }
  75. .goods-info-cell .goods-title {
  76. font-size: 11px !important;
  77. }
  78. }
  79. /* 图片优化 */
  80. .bootstrap-table .table .img-center img {
  81. max-width: 80px;
  82. max-height: 80px;
  83. object-fit: cover;
  84. border-radius: 6px;
  85. border: 1px solid #ddd;
  86. box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  87. }
  88. /* 标签优化 */
  89. .label {
  90. display: inline-block;
  91. margin: 1px;
  92. line-height: 1.2;
  93. }
  94. `)
  95. .appendTo('head');
  96. // 初始化表格参数配置
  97. Table.api.init({
  98. extend: {
  99. index_url: 'shop/goods/index' + location.search,
  100. add_url: 'shop/goods/add',
  101. edit_url: 'shop/goods/edit?dialog=1',
  102. del_url: 'shop/goods/del',
  103. multi_url: 'shop/goods/multi',
  104. import_url: 'shop/goods/import',
  105. table: 'shop_goods',
  106. }
  107. });
  108. Table.config.dragsortfield = '';
  109. var table = $("#table");
  110. var goodsTypeList = Controller.api.parseConfigJson('goodsTypeList', {});
  111. var specTypeList = Controller.api.parseConfigJson('specTypeList', {});
  112. var statusList = Controller.api.parseConfigJson('statusList', {});
  113. // 初始化表格
  114. table.bootstrapTable({
  115. url: $.fn.bootstrapTable.defaults.extend.index_url,
  116. pk: 'id',
  117. sortName: 'id',
  118. fixedColumns: true,
  119. fixedRightNumber: 1,
  120. columns: [
  121. [
  122. {checkbox: true},
  123. {field: 'id', title: 'ID', width: 60, sortable: true},
  124. {field: 'image', title: '图片', width: 100, operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
  125. {
  126. field: 'title',
  127. title: '商品信息',
  128. width: 300,
  129. operate: 'LIKE',
  130. formatter: function (value, row, index) {
  131. var html = '<div style="width: 280px; padding: 8px 0; line-height: 1.4; word-wrap: break-word;">';
  132. // 商品名称、编码、品牌在一行 - 固定宽度,超出换行
  133. html += '<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; width: 100%;">';
  134. // 商品标题
  135. html += '<span style="font-weight: 600; color: #2c3e50; font-size: 14px; word-break: break-all;" title="' + (value || '') + '">' + (value || '') + '</span>';
  136. // 分隔符
  137. html += '<span style="color: #ddd; font-size: 12px; flex-shrink: 0;">|</span>';
  138. // 商品编码
  139. html += '<div style="display: flex; align-items: center; flex-shrink: 0;">';
  140. html += '<i class="fa fa-barcode" style="margin-right: 3px; color: #999; font-size: 10px;"></i>';
  141. html += '<span style="font-size: 11px; color: #666; word-break: break-all;">' + (row.goods_sn || '-') + '</span>';
  142. html += '</div>';
  143. // 品牌信息
  144. if (row.brand && row.brand.name) {
  145. html += '<span style="color: #ddd; font-size: 12px; flex-shrink: 0;">|</span>';
  146. html += '<div style="display: flex; align-items: center; flex-shrink: 0;">';
  147. html += '<i class="fa fa-tag" style="margin-right: 3px; color: #999; font-size: 10px;"></i>';
  148. html += '<span style="font-size: 11px; color: #666; word-break: break-all;">' + row.brand.name + '</span>';
  149. html += '</div>';
  150. }
  151. html += '</div>';
  152. // 副标题
  153. if (row.subtitle) {
  154. 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>';
  155. }
  156. // 显示规格信息(如果是多规格商品且有默认SKU)
  157. if (row.spec_type == 1 && row.default_sku && row.default_sku.sku_attr) {
  158. html += '<div style="font-size: 10px; color: #888; margin-top: 4px; padding: 2px 6px; background-color: #f5f5f5; border-radius: 3px;">';
  159. html += '<i class="fa fa-list-alt" style="margin-right: 3px;"></i>';
  160. html += '默认规格: ' + Controller.formatSkuAttr(row.default_sku.sku_attr);
  161. html += '</div>';
  162. }
  163. html += '</div>';
  164. return html;
  165. }
  166. },
  167. {
  168. field: 'type',
  169. title: '商品类型',
  170. width: 100,
  171. searchList: goodsTypeList,
  172. formatter: function (value, row, index) {
  173. var text = (goodsTypeList && goodsTypeList[value]) ? goodsTypeList[value] : '未知';
  174. var className = 'label-primary';
  175. var icon = 'fa-cube';
  176. switch(parseInt(value)) {
  177. case 1: className = 'label-primary'; icon = 'fa-cube'; break; // 普通商品
  178. case 2: className = 'label-info'; icon = 'fa-key'; break; // 卡密/网盘
  179. case 3: className = 'label-warning'; icon = 'fa-cloud'; break; // 虚拟商品
  180. case 4: className = 'label-success'; icon = 'fa-ticket'; break; // 次卡商品
  181. }
  182. return '<span class="label ' + className + '"><i class="fa ' + icon + '"></i> ' + text + '</span>';
  183. }
  184. },
  185. {
  186. field: 'spec_type',
  187. title: '规格',
  188. width: 80,
  189. searchList: specTypeList,
  190. formatter: function (value, row, index) {
  191. var label = (specTypeList && specTypeList[value]) ? specTypeList[value] : (value == 1 ? '多规格' : '单规格');
  192. var className = value == 1 ? 'label-info' : 'label-success';
  193. return '<span class="label ' + className + '"><i class="fa ' + (value == 1 ? 'fa-list' : 'fa-square') + '"></i> ' + label + '</span>';
  194. }
  195. },
  196. {field: 'price', title: '价格', width: 80, operate: 'BETWEEN', sortable: true},
  197. {field: 'stocks', title: '库存', width: 80, operate: 'BETWEEN', sortable: true},
  198. {field: 'sales', title: '销量', width: 80, operate: 'BETWEEN', sortable: true},
  199. {field: 'views', title: '浏览量', width: 80, operate: 'BETWEEN', sortable: true},
  200. {
  201. field: 'status',
  202. title: '状态',
  203. width: 80,
  204. searchList: statusList,
  205. formatter: function (value, row, index) {
  206. // 状态样式映射 - 根据GoodsEnum中的状态值
  207. var statusStyles = {
  208. 0: {class: 'label-warning', icon: 'fa-warehouse'}, // 仓库中(未上架)
  209. 1: {class: 'label-success', icon: 'fa-check-circle'}, // 销售中(已上架)
  210. 2: {class: 'label-danger', icon: 'fa-times-circle'}, // 已售罄
  211. 3: {class: 'label-default', icon: 'fa-eye-slash'} // 已下架
  212. };
  213. // 直接使用后台statusList数据
  214. var text = statusList && statusList[value] ? statusList[value] : '未知';
  215. var style = statusStyles[value] || {class: 'label-default', icon: 'fa-question'};
  216. return '<span class="label ' + style.class + '"><i class="fa ' + style.icon + '"></i> ' + text + '</span>';
  217. }
  218. },
  219. {field: 'createtime', title: '创建时间', width: 120, operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime, visible: false},
  220. {field: 'updatetime', title: '更新时间', width: 120, operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime, visible: false},
  221. // 隐藏字段用于搜索
  222. {field: 'brand_id', title: '品牌', visible: false, searchList: $.getJSON("shop/brand/getList")},
  223. {field: 'goods_sn', title: '商品编码', visible: false, operate: 'LIKE'},
  224. {field: 'title', title: '商品标题', visible: false, operate: 'LIKE'},
  225. {
  226. field: 'operate',
  227. title: '操作',
  228. width: 120,
  229. table: table,
  230. events: Table.api.events.operate,
  231. formatter: Table.api.formatter.operate,
  232. buttons: [
  233. {
  234. name: 'edit',
  235. title: '编辑',
  236. classname: 'btn btn-xs btn-success btn-dialog',
  237. icon: 'fa fa-pencil',
  238. url: 'shop/goods/edit'
  239. }
  240. // {
  241. // name: 'preview',
  242. // title: '预览',
  243. // classname: 'btn btn-xs btn-info',
  244. // icon: 'fa fa-eye',
  245. // url: function(row) {
  246. // return row.url;
  247. // },
  248. // target: '_blank'
  249. // }
  250. ]
  251. }
  252. ]
  253. ]
  254. });
  255. // 为表格绑定事件
  256. Table.api.bindevent(table);
  257. },
  258. select: function () {
  259. // 解析JSON格式的Config数据
  260. var specTypeList = {};
  261. try {
  262. specTypeList = Config.specTypeList ? JSON.parse(Config.specTypeList) : {0: "单规格", 1: "多规格"};
  263. } catch (e) {
  264. console.error('解析Config数据失败:', e);
  265. specTypeList = {0: "单规格", 1: "多规格"};
  266. }
  267. // 从URL参数中获取选择模式,默认为多选
  268. var urlParams = new URLSearchParams(window.location.search);
  269. var selectMode = urlParams.get('selectMode') || 'multiple'; // 'single' 或 'multiple'
  270. var maxSelect = parseInt(urlParams.get('maxSelect')) || 0; // 最大选择数量,0表示无限制
  271. // 初始化表格参数配置
  272. Table.api.init({
  273. extend: {
  274. index_url: 'shop/goods/index' + location.search,
  275. table: 'shop_goods',
  276. }
  277. });
  278. Table.config.dragsortfield = '';
  279. var table = $("#table");
  280. // 根据选择模式配置表格列
  281. var columns = [
  282. {field: 'id', title: 'ID', width: 60},
  283. {field: 'image', title: '图片', width: 120, operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
  284. {
  285. field: 'title',
  286. title: '商品信息',
  287. operate: 'LIKE',
  288. formatter: function (value, row, index) {
  289. var html = '<div>';
  290. html += '<div style="font-weight: bold; margin-bottom: 2px;">' + value + '</div>';
  291. html += '<div style="font-size: 12px; color: #999;">';
  292. html += '编码: ' + (row.goods_sn || '-');
  293. if (row.category && row.category.name) {
  294. html += ' | 分类: ' + row.category.name;
  295. }
  296. html += '</div>';
  297. html += '</div>';
  298. return html;
  299. }
  300. },
  301. {field: 'spec_type', title: '规格', width: 80, searchList: specTypeList, formatter: Table.api.formatter.label},
  302. {
  303. field: 'price',
  304. title: '价格',
  305. width: 100,
  306. operate: 'BETWEEN',
  307. formatter: function (value, row, index) {
  308. return '<span style="color: #e74c3c; font-weight: bold;">¥' + (value || '0.00') + '</span>';
  309. }
  310. },
  311. {field: 'stocks', title: '库存', width: 80},
  312. // 操作列 - 添加选择按钮
  313. {
  314. field: 'operate',
  315. title: selectMode === 'single' ? '选择' : '操作',
  316. width: selectMode === 'single' ? 80 : 100,
  317. operate: false,
  318. formatter: function (value, row, index) {
  319. var html = '';
  320. if (selectMode === 'single') {
  321. // 单选模式:蓝色选择按钮,更明显
  322. html = '<button class="btn btn-xs btn-primary btn-select-single" data-id="' + row.id + '" data-index="' + index + '" title="点击选择该商品">' +
  323. '<i class="fa fa-check"></i> 选择</button>';
  324. } else {
  325. // 多选模式:绿色选择按钮,带图标区分状态
  326. html = '<button class="btn btn-xs btn-success btn-select-multi" data-id="' + row.id + '" data-index="' + index + '" data-selected="false" title="点击添加到选择列表">' +
  327. '<i class="fa fa-plus"></i> 选择</button>';
  328. }
  329. return html;
  330. }
  331. },
  332. // 隐藏字段用于搜索
  333. {field: 'category_id', title: '分类', visible: false, searchList: $.getJSON("shop/category/getList")},
  334. {field: 'goods_sn', title: '商品编码', visible: false, operate: 'LIKE'},
  335. ];
  336. // 初始化表格
  337. table.bootstrapTable({
  338. url: $.fn.bootstrapTable.defaults.extend.index_url,
  339. pk: 'id',
  340. sortName: 'id',
  341. clickToSelect: false, // 禁用点击行选择
  342. columns: [columns]
  343. });
  344. // 如果是多选模式且有最大选择限制,添加选择控制
  345. if (selectMode === 'multiple' && maxSelect > 0) {
  346. table.on('check.bs.table check-all.bs.table', function (e, row) {
  347. var selectedRows = table.bootstrapTable('getSelections');
  348. if (selectedRows.length > maxSelect) {
  349. // 超出限制,取消最后一次选择
  350. if (e.type === 'check.bs.table') {
  351. table.bootstrapTable('uncheck', table.bootstrapTable('getData').indexOf(row));
  352. } else {
  353. // 如果是全选,只保留前N个
  354. var allData = table.bootstrapTable('getData');
  355. for (var i = maxSelect; i < allData.length; i++) {
  356. table.bootstrapTable('uncheck', i);
  357. }
  358. }
  359. Toastr.warning('最多只能选择 ' + maxSelect + ' 个商品');
  360. }
  361. });
  362. }
  363. // 存储选中的商品(用于按钮模式)
  364. var selectedGoods = [];
  365. // 单选按钮点击事件
  366. $(document).on('click', '.btn-select-single', function () {
  367. var $btn = $(this);
  368. var id = $btn.data('id');
  369. var index = $btn.data('index');
  370. var rowData = table.bootstrapTable('getData')[index];
  371. // 直接选择商品并关闭弹窗
  372. Fast.api.close([rowData]);
  373. });
  374. // 多选按钮点击事件
  375. $(document).on('click', '.btn-select-multi', function () {
  376. var $btn = $(this);
  377. var id = $btn.data('id');
  378. var index = $btn.data('index');
  379. var isSelected = $btn.data('selected');
  380. var rowData = table.bootstrapTable('getData')[index];
  381. if (!isSelected) {
  382. // 检查最大选择限制
  383. if (maxSelect > 0 && selectedGoods.length >= maxSelect) {
  384. Toastr.warning('最多只能选择 ' + maxSelect + ' 个商品');
  385. return;
  386. }
  387. // 添加到选中列表
  388. selectedGoods.push(rowData);
  389. $btn.removeClass('btn-success').addClass('btn-danger')
  390. .html('<i class="fa fa-minus"></i> 取消选择')
  391. .attr('title', '点击从选择列表中移除')
  392. .data('selected', true);
  393. } else {
  394. // 从选中列表移除
  395. selectedGoods = selectedGoods.filter(function(item) {
  396. return item.id != id;
  397. });
  398. $btn.removeClass('btn-danger').addClass('btn-success')
  399. .html('<i class="fa fa-plus"></i> 选择')
  400. .attr('title', '点击添加到选择列表')
  401. .data('selected', false);
  402. }
  403. // 更新选中数量显示
  404. updateSelectedCount();
  405. });
  406. // 更新选中数量显示
  407. function updateSelectedCount() {
  408. var count = selectedGoods.length;
  409. var countText = count > 0 ? '已选择 ' + count + ' 个商品' : '请选择商品';
  410. // 更新确认按钮文本
  411. $('.btn-goods-select').text(countText === '请选择商品' ? '确认选择' : '确认选择 (' + count + ')');
  412. // 如果达到最大选择数量,禁用其他选择按钮
  413. if (maxSelect > 0 && count >= maxSelect) {
  414. $('.btn-select-multi[data-selected="false"]').prop('disabled', true).addClass('disabled');
  415. } else {
  416. $('.btn-select-multi[data-selected="false"]').prop('disabled', false).removeClass('disabled');
  417. }
  418. }
  419. // 确认按钮绑定事件(仅多选模式使用)
  420. $(document).on('click', '.btn-goods-select', function () {
  421. var selectedRows = [];
  422. if (selectMode === 'single') {
  423. // 单选模式:不应该走到这里,因为单选时直接选择
  424. Layer.alert('单选模式请直接点击商品的选择按钮');
  425. return;
  426. } else {
  427. // 多选模式:使用按钮选择的商品
  428. selectedRows = selectedGoods;
  429. }
  430. if (selectedRows.length === 0) {
  431. Layer.alert('请选择商品');
  432. return;
  433. }
  434. // 调用父窗口回调函数
  435. Fast.api.close(selectedRows);
  436. });
  437. // 在页面标题中显示选择模式
  438. var modeText = selectMode === 'single' ? '单选' : '多选';
  439. if (selectMode === 'multiple' && maxSelect > 0) {
  440. modeText += '(最多' + maxSelect + '个)';
  441. }
  442. $('.panel-heading, .layui-layer-title').each(function() {
  443. var currentTitle = $(this).text();
  444. if (currentTitle.indexOf('选择商品') !== -1 && currentTitle.indexOf(modeText) === -1) {
  445. $(this).text(currentTitle + ' - ' + modeText);
  446. }
  447. });
  448. // 显示选择模式提示信息
  449. $('#selection-info').show();
  450. $('#selection-mode-text').text(modeText);
  451. if (selectMode === 'single') {
  452. $('#selection-tip').html('<strong>单击任意商品的"选择"按钮即可完成选择</strong>');
  453. // 单选模式隐藏确认按钮
  454. $('#confirm-select-btn').hide();
  455. } else {
  456. var tipText = '点击商品的"选择"按钮添加到选择列表,绿色表示可选择,红色表示已选择';
  457. if (maxSelect > 0) {
  458. tipText += ',最多可选择' + maxSelect + '个商品';
  459. }
  460. $('#selection-tip').text(tipText);
  461. // 多选模式显示确认按钮
  462. $('#confirm-select-btn').show();
  463. }
  464. // 表格刷新后恢复选择状态
  465. table.on('refresh.bs.table load-success.bs.table', function () {
  466. if (selectMode === 'multiple') {
  467. // 恢复多选按钮状态
  468. setTimeout(function() {
  469. $('.btn-select-multi').each(function() {
  470. var $btn = $(this);
  471. var id = $btn.data('id');
  472. var isSelected = selectedGoods.some(function(item) {
  473. return item.id == id;
  474. });
  475. if (isSelected) {
  476. $btn.removeClass('btn-success').addClass('btn-danger')
  477. .html('<i class="fa fa-minus"></i> 取消选择')
  478. .attr('title', '点击从选择列表中移除')
  479. .data('selected', true);
  480. } else {
  481. $btn.removeClass('btn-danger').addClass('btn-success')
  482. .html('<i class="fa fa-plus"></i> 选择')
  483. .attr('title', '点击添加到选择列表')
  484. .data('selected', false);
  485. }
  486. });
  487. // 更新选中数量显示
  488. updateSelectedCount();
  489. }, 100);
  490. }
  491. });
  492. // 为表格绑定事件
  493. Table.api.bindevent(table);
  494. },
  495. recyclebin: function () {
  496. // 初始化表格参数配置
  497. Table.api.init({
  498. extend: {
  499. 'dragsort_url': ''
  500. }
  501. });
  502. var table = $("#table");
  503. // 初始化表格
  504. table.bootstrapTable({
  505. url: 'shop/goods/recyclebin' + location.search,
  506. pk: 'id',
  507. sortName: 'id',
  508. columns: [
  509. [{
  510. checkbox: true
  511. },
  512. {
  513. field: 'id',
  514. title: __('Id')
  515. },
  516. {
  517. field: 'title',
  518. title: __('Title'),
  519. align: 'left'
  520. },
  521. {
  522. field: 'deletetime',
  523. title: __('Deletetime'),
  524. operate: 'RANGE',
  525. addclass: 'datetimerange',
  526. formatter: Table.api.formatter.datetime
  527. },
  528. {
  529. field: 'operate',
  530. width: '130px',
  531. title: __('Operate'),
  532. table: table,
  533. events: Table.api.events.operate,
  534. buttons: [{
  535. name: 'Restore',
  536. text: __('Restore'),
  537. classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
  538. icon: 'fa fa-rotate-left',
  539. url: 'shop/goods/restore',
  540. refresh: true
  541. },
  542. {
  543. name: 'Destroy',
  544. text: __('Destroy'),
  545. classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
  546. icon: 'fa fa-times',
  547. url: 'shop/goods/destroy',
  548. refresh: true
  549. }
  550. ],
  551. formatter: Table.api.formatter.operate
  552. }
  553. ]
  554. ]
  555. });
  556. // 为表格绑定事件
  557. Table.api.bindevent(table);
  558. },
  559. getAttribute: function (category_id, attribute_ids = []) {
  560. $.get('shop/attribute/attrs?category_id=' + category_id, function (res) {
  561. const {code, data, msg} = res;
  562. if (code) {
  563. $('#attributes').html(data.length ? Template('attributetpl', {row: data, attribute_ids}) : ' <input name="row[attribute_ids][0][]" type="hidden" value="">');
  564. var instance = $("form[data-toggle='validator']").data("validator");
  565. $('#attributes input').each(function () {
  566. instance._parse(this);
  567. });
  568. } else {
  569. Toastr.error(msg);
  570. }
  571. })
  572. },
  573. add: function () {
  574. let that = this;
  575. // 等待DOM完全加载后再执行
  576. $(document).ready(function() {
  577. // $('#c-category_id, #c-category_ids').on('change', function () {
  578. // let category_id = $(this).val();
  579. // that.getAttribute(category_id);
  580. // });
  581. // 初始化商品类型卡片交互
  582. that.initGoodsTypeCards();
  583. // 添加上架时间和下架时间的交互逻辑
  584. that.initOnlineOfflineControl();
  585. // 初始化商品详情预览功能
  586. that.initContentPreview();
  587. // 初始化选项卡验证提示系统
  588. that.initTabValidation();
  589. Controller.api.bindevent();
  590. Controller.api.add_sku();
  591. });
  592. },
  593. edit: function () {
  594. let that = this;
  595. // 等待DOM完全加载后再执行
  596. $(document).ready(function() {
  597. $('#c-category_id, #c-category_ids').on('change', function () {
  598. let category_id = $(this).val();
  599. //that.getAttribute(category_id);
  600. });
  601. if (Config.goods && Config.goods.category_id) {
  602. //that.getAttribute(Config.goods.category_id, Config.goods.attribute_ids ? Config.goods.attribute_ids.split(',') : []);
  603. }
  604. // 初始化商品类型卡片交互
  605. that.initGoodsTypeCards();
  606. // 添加上架时间和下架时间的交互逻辑
  607. that.initOnlineOfflineControl();
  608. // 初始化商品详情预览功能
  609. that.initContentPreview();
  610. // 初始化选项卡验证提示系统
  611. that.initTabValidation();
  612. // 编辑时初始化商品类型选择状态
  613. that.initEditTypeState();
  614. Controller.api.bindevent();
  615. Controller.api.add_sku();
  616. });
  617. },
  618. // 检查多选控件是否为空
  619. isMultiSelectEmpty: function(value) {
  620. if (Array.isArray(value)) {
  621. return value.length === 0;
  622. } else if (typeof value === 'string') {
  623. // 移除空格并检查
  624. var trimmed = value.trim();
  625. return trimmed === '' || trimmed === '0' || trimmed === 'null' || trimmed === 'undefined';
  626. } else {
  627. return !value || value === null || value === undefined;
  628. }
  629. },
  630. // 添加错误高亮样式
  631. addErrorStyles: function() {
  632. // 检查是否已经添加过样式
  633. if ($('#goods-error-styles').length > 0) {
  634. return;
  635. }
  636. var styles = `
  637. <style id="goods-error-styles">
  638. .nav-tabs > li > a.tab-error {
  639. color: #d9534f !important;
  640. background-color: #f2dede !important;
  641. border-color: #d9534f !important;
  642. }
  643. .nav-tabs > li > a.tab-error:hover,
  644. .nav-tabs > li > a.tab-error:focus {
  645. background-color: #ebccd1 !important;
  646. border-color: #d9534f !important;
  647. }
  648. .nav-tabs > li > a.tab-success {
  649. color: #5cb85c !important;
  650. }
  651. .nav-tabs > li > a .error-icon {
  652. color: #d9534f;
  653. }
  654. .nav-tabs > li > a .success-icon {
  655. color: #5cb85c;
  656. }
  657. .error-highlight {
  658. border-color: #d9534f !important;
  659. box-shadow: 0 0 0 0.2rem rgba(217, 83, 79, 0.25) !important;
  660. animation: shake 0.5s ease-in-out;
  661. }
  662. @keyframes shake {
  663. 0%, 20%, 40%, 60%, 80% {
  664. transform: translateX(0);
  665. }
  666. 10%, 30%, 50%, 70%, 90% {
  667. transform: translateX(-3px);
  668. }
  669. }
  670. </style>
  671. `;
  672. $('head').append(styles);
  673. },
  674. // 初始化商品类型卡片交互
  675. initGoodsTypeCards: function() {
  676. // 检查元素是否存在,避免在不支持该功能的页面报错
  677. if ($('.goods-type-card').length === 0) {
  678. return;
  679. }
  680. // 初始化选中状态
  681. function updateTypeCardState() {
  682. var $cards = $('.goods-type-card');
  683. if ($cards.length > 0) {
  684. $cards.removeClass('selected');
  685. $('.goods-type-card input[type="radio"]:checked').closest('.goods-type-card').addClass('selected');
  686. }
  687. }
  688. // 监听单选按钮变化
  689. var $radioInputs = $('.goods-type-card input[type="radio"]');
  690. if ($radioInputs && $radioInputs.length > 0) {
  691. $radioInputs.off('change.typecard').on('change.typecard', function() {
  692. updateTypeCardState();
  693. });
  694. }
  695. // 初始化时设置状态
  696. updateTypeCardState();
  697. // 让FastAdmin处理表单验证和按钮状态
  698. // 无需额外的验证逻辑,data-rule会自动处理
  699. },
  700. // 初始化编辑状态
  701. initEditTypeState: function() {
  702. console.log('初始化编辑状态');
  703. // 如果存在商品数据,设置商品类型选中状态
  704. if (Config.goods && Config.goods.type) {
  705. console.log('设置商品类型:', Config.goods.type);
  706. var $typeRadio = $('input[name="row[type]"][value="' + Config.goods.type + '"]');
  707. if ($typeRadio.length > 0) {
  708. $typeRadio.prop('checked', true);
  709. $typeRadio.trigger('change');
  710. }
  711. }
  712. // 如果存在上架类型数据,设置上架类型选中状态(优先使用online_type字段)
  713. if (Config.goods && Config.goods.online_type !== undefined) {
  714. console.log('设置上架类型(online_type):', Config.goods.online_type);
  715. var $onlineTypeRadio = $('input[name="row[online_type]"][value="' + Config.goods.online_type + '"]');
  716. if ($onlineTypeRadio.length > 0) {
  717. $onlineTypeRadio.prop('checked', true);
  718. $onlineTypeRadio.trigger('change');
  719. }
  720. }
  721. // 设置上下架时间相关字段
  722. if (Config.goods) {
  723. // 设置定时上架时间
  724. if (Config.goods.scheduled_online_time) {
  725. $('#c-scheduled_online_time').val(Config.goods.scheduled_online_time);
  726. }
  727. // 设置自动下架选项
  728. if (Config.goods.is_auto_offline) {
  729. $('#c-is_auto_offline').prop('checked', true);
  730. if (Config.goods.scheduled_offline_time) {
  731. $('#c-scheduled_offline_time').val(Config.goods.scheduled_offline_time);
  732. }
  733. }
  734. }
  735. // 如果存在规格类型数据,设置规格类型选中状态
  736. if (Config.goods && Config.goods.spec_type !== undefined) {
  737. console.log('设置规格类型:', Config.goods.spec_type);
  738. var $specTypeRadio = $('input[name="row[spec_type]"][value="' + Config.goods.spec_type + '"]');
  739. if ($specTypeRadio.length > 0) {
  740. $specTypeRadio.prop('checked', true);
  741. $specTypeRadio.trigger('change');
  742. // 触发FastAdmin的Favisible事件,确保对应的表单区域显示
  743. setTimeout(function() {
  744. $(document).trigger('fa.event.favisible', $specTypeRadio);
  745. }, 100);
  746. }
  747. }
  748. // 如果是单规格且有SKU数据,填充单规格表单
  749. if (Config.goods && Config.goods.spec_type == '0' && Config.goods_skus && Config.goods_skus.length > 0) {
  750. console.log('填充单规格数据');
  751. var sku = Config.goods_skus[0];
  752. // 延迟填充数据,确保DOM已渲染
  753. setTimeout(function() {
  754. $('#c-price').val(sku.price || '');
  755. $('#c-lineation_price').val(sku.lineation_price || '');
  756. $('#c-cost_price').val(sku.cost_price || '');
  757. $('#c-stocks').val(sku.stocks || '');
  758. $('#c-weight').val(sku.weight || '');
  759. $('#c-volume').val(sku.volume || '');
  760. $('#c-sku-sn').val(sku.sku_sn || '');
  761. $('#c-single-image').val(sku.image || '');
  762. // 更新单规格图片预览
  763. if (sku.image) {
  764. var $preview = $('#p-single-image');
  765. 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>';
  766. $preview.html(img);
  767. }
  768. console.log('单规格数据填充完成');
  769. }, 200);
  770. } else if (Config.goods && Config.goods.spec_type == '1') {
  771. console.log('多规格商品,等待Vue组件初始化多规格数据');
  772. // 多规格数据由Vue组件的init方法处理
  773. }
  774. },
  775. // 初始化选项卡验证提示系统
  776. initTabValidation: function() {
  777. var that = this;
  778. // 添加错误高亮样式
  779. that.addErrorStyles();
  780. // 清除所有选项卡错误标记
  781. that.clearTabErrors();
  782. // 启用提交按钮(移除disabled类)
  783. $('.btn[type="submit"]').removeClass('disabled');
  784. // 监听表单字段变化,实时验证
  785. var $forms = $('#add-form, #edit-form');
  786. if ($forms && $forms.length > 0) {
  787. $forms.on('change keyup blur', 'input, select, textarea', function() {
  788. setTimeout(function() {
  789. that.validateCurrentTab();
  790. }, 100);
  791. });
  792. }
  793. // 监听选项卡切换
  794. var $tabLinks = $('.nav-tabs a[data-toggle="tab"]');
  795. if ($tabLinks && $tabLinks.length > 0) {
  796. $tabLinks.on('shown.bs.tab', function(e) {
  797. setTimeout(function() {
  798. that.validateCurrentTab();
  799. }, 100);
  800. });
  801. // 当离开选项卡时,验证该选项卡并标记状态
  802. $tabLinks.on('hide.bs.tab', function(e) {
  803. var leavingTab = $(e.target).attr('href');
  804. that.validateAndMarkTab(leavingTab);
  805. });
  806. }
  807. // 页面加载完成后进行一次全面验证,但不跳转,只显示状态
  808. setTimeout(function() {
  809. that.validateAllTabsForStatus();
  810. }, 1000);
  811. },
  812. // 验证当前选项卡
  813. validateCurrentTab: function() {
  814. var that = this;
  815. var $activeTab = $('.nav-tabs li.active a');
  816. if ($activeTab.length === 0) {
  817. return; // 没有活动选项卡,直接返回
  818. }
  819. var activeTab = $activeTab.attr('href');
  820. if (!activeTab) {
  821. return; // 没有href属性,直接返回
  822. }
  823. // 清除当前选项卡的错误标记
  824. that.clearTabError(activeTab);
  825. var hasError = false;
  826. var errorMessage = '';
  827. switch(activeTab) {
  828. case '#basics':
  829. var result = that.validateBasicsTab();
  830. hasError = !result.valid;
  831. errorMessage = result.message;
  832. break;
  833. case '#skus':
  834. var result = that.validateSkusTab();
  835. hasError = !result.valid;
  836. errorMessage = result.message;
  837. break;
  838. case '#delivery':
  839. var result = that.validateDeliveryTab();
  840. hasError = !result.valid;
  841. errorMessage = result.message;
  842. break;
  843. case '#detail':
  844. var result = that.validateDetailTab();
  845. hasError = !result.valid;
  846. errorMessage = result.message;
  847. break;
  848. case '#sales':
  849. var result = that.validateSalesTab();
  850. hasError = !result.valid;
  851. errorMessage = result.message;
  852. break;
  853. }
  854. if (hasError) {
  855. that.showTabError(activeTab, errorMessage);
  856. }
  857. },
  858. // 验证基础信息选项卡
  859. validateBasicsTab: function() {
  860. var errors = [];
  861. console.log('验证基础信息选项卡');
  862. // 验证商品类型
  863. if (!$('input[name="row[type]"]:checked').length) {
  864. errors.push('请选择商品类型');
  865. console.log('商品类型验证失败');
  866. }
  867. // 验证商品编码 - 检查是否有data-rule required
  868. var $goodsSn = $('#c-goods_sn');
  869. if ($goodsSn.length > 0 && $goodsSn.attr('data-rule') && $goodsSn.attr('data-rule').indexOf('required') !== -1) {
  870. var goodsSn = $goodsSn.val();
  871. if (!goodsSn || goodsSn.trim() === '') {
  872. errors.push('请输入商品编码');
  873. console.log('商品编码验证失败');
  874. }
  875. }
  876. // 验证商品标题
  877. var $title = $('#c-title');
  878. if ($title.length > 0 && $title.attr('data-rule') && $title.attr('data-rule').indexOf('required') !== -1) {
  879. var title = $title.val();
  880. if (!title || title.trim() === '') {
  881. errors.push('请输入商品标题');
  882. console.log('商品标题验证失败');
  883. }
  884. }
  885. // 验证商品分类 - 多选控件(兼容不同页面的字段ID)
  886. var $categoryId = $('#c-category_id, #c-category_ids').first();
  887. if ($categoryId.length > 0 && $categoryId.attr('data-rule') && $categoryId.attr('data-rule').indexOf('required') !== -1) {
  888. var categoryId = $categoryId.val();
  889. if (Controller.isMultiSelectEmpty(categoryId)) {
  890. errors.push('请选择商品分类');
  891. console.log('商品分类验证失败');
  892. }
  893. }
  894. // 验证主图
  895. var $image = $('#c-image');
  896. if ($image.length > 0 && $image.attr('data-rule') && $image.attr('data-rule').indexOf('required') !== -1) {
  897. var image = $image.val();
  898. if (!image || image.trim() === '') {
  899. errors.push('请上传商品主图');
  900. console.log('商品主图验证失败');
  901. }
  902. }
  903. console.log('基础信息验证结果:', errors);
  904. return {
  905. valid: errors.length === 0,
  906. message: errors.join('、'),
  907. errors: errors
  908. };
  909. },
  910. // 验证价格库存选项卡
  911. validateSkusTab: function() {
  912. var errors = [];
  913. var specType = $('input[name="row[spec_type]"]:checked').val();
  914. console.log('验证价格库存选项卡, 规格类型:', specType);
  915. if (!specType) {
  916. errors.push('请选择规格类型');
  917. console.log('规格类型未选择');
  918. } else if (specType == '0') {
  919. // 单规格验证
  920. console.log('验证单规格');
  921. // 验证价格
  922. var $price = $('#c-price');
  923. if ($price.length > 0 && $price.attr('data-rule') && $price.attr('data-rule').indexOf('required') !== -1) {
  924. var price = parseFloat($price.val());
  925. if (!price || price <= 0) {
  926. errors.push('销售价必须大于0');
  927. console.log('销售价验证失败');
  928. }
  929. }
  930. // 验证库存
  931. var $stocks = $('#c-stocks');
  932. if ($stocks.length > 0 && $stocks.attr('data-rule') && $stocks.attr('data-rule').indexOf('required') !== -1) {
  933. var stocks = parseInt($stocks.val());
  934. if (isNaN(stocks) || stocks <= 0) {
  935. errors.push('库存必须大于0');
  936. console.log('库存验证失败');
  937. }
  938. }
  939. } else if (specType == '1') {
  940. // 多规格验证
  941. console.log('验证多规格');
  942. if (typeof vm !== 'undefined' && vm && vm.tableData) {
  943. var hasValidSku = false;
  944. var validSkuCount = 0;
  945. console.log('检查SKU数据, tableData长度:', vm.tableData.length);
  946. for (var i = 0; i < vm.tableData.length; i++) {
  947. var sku = vm.tableData[i];
  948. console.log('检查SKU[' + i + ']:', {
  949. status: sku.status,
  950. price: sku.price,
  951. stocks: sku.stocks,
  952. sku_sn: sku.sku_sn
  953. });
  954. // 只检查状态为显示的SKU
  955. var isVisible = (sku.status === 1 || sku.status === '1' || sku.status === true);
  956. console.log('SKU[' + i + '] 显示状态:', sku.status, '可见:', isVisible);
  957. if (isVisible) {
  958. var price = parseFloat(sku.price);
  959. var stocks = parseInt(sku.stocks);
  960. console.log('SKU[' + i + '] 检查通过, price:', price, 'stocks:', stocks);
  961. hasValidSku = true;
  962. validSkuCount++;
  963. // 验证价格必须大于0
  964. if (!price || price <= 0) {
  965. errors.push('SKU销售价必须大于0');
  966. console.log('SKU[' + i + ']销售价验证失败:', price);
  967. break;
  968. }
  969. // 验证库存
  970. if (isNaN(stocks) || stocks <= 0) {
  971. errors.push('SKU库存必须大于0');
  972. console.log('SKU[' + i + ']库存验证失败:', stocks);
  973. break;
  974. }
  975. }
  976. }
  977. console.log('有效SKU数量:', validSkuCount);
  978. if (!hasValidSku) {
  979. errors.push('请至少设置一个有效的SKU');
  980. console.log('没有有效的SKU');
  981. }
  982. } else {
  983. errors.push('请设置商品规格');
  984. console.log('多规格数据不存在');
  985. }
  986. }
  987. console.log('价格库存验证结果:', errors);
  988. return {
  989. valid: errors.length === 0,
  990. message: errors.join('、'),
  991. errors: errors
  992. };
  993. },
  994. // 验证配送设置选项卡
  995. validateDeliveryTab: function() {
  996. var errors = [];
  997. console.log('验证配送设置选项卡');
  998. // 验证配送方式
  999. if (!$('input[name="row[delivery_type]"]:checked').length) {
  1000. errors.push('请选择配送方式');
  1001. console.log('配送方式未选择');
  1002. }
  1003. var deliveryType = $('input[name="row[delivery_type]"]:checked').val();
  1004. if (deliveryType === 'EXPRESS') {
  1005. var expressType = $('input[name="row[express_type]"]:checked').val();
  1006. if (expressType === '3') {
  1007. // 运费模板
  1008. var templateId = $('#c-express_template_id').val();
  1009. if (!templateId) {
  1010. errors.push('请选择运费模板');
  1011. console.log('运费模板未选择');
  1012. }
  1013. }
  1014. }
  1015. console.log('配送设置验证结果:', errors);
  1016. return {
  1017. valid: errors.length === 0,
  1018. message: errors.join('、'),
  1019. errors: errors
  1020. };
  1021. },
  1022. // 验证商品详情选项卡
  1023. validateDetailTab: function() {
  1024. console.log('验证商品详情选项卡');
  1025. // 商品详情不是必填项,暂时返回有效
  1026. return {
  1027. valid: true,
  1028. message: '',
  1029. errors: []
  1030. };
  1031. },
  1032. // 验证销售设置选项卡
  1033. validateSalesTab: function() {
  1034. var errors = [];
  1035. console.log('验证销售设置选项卡');
  1036. // 验证库存显示方式
  1037. if (!$('input[name="row[stock_show_type]"]:checked').length) {
  1038. errors.push('请选择库存显示方式');
  1039. console.log('库存显示方式未选择');
  1040. }
  1041. // 验证销量显示方式
  1042. if (!$('input[name="row[sales_show_type]"]:checked').length) {
  1043. errors.push('请选择销量显示方式');
  1044. console.log('销量显示方式未选择');
  1045. }
  1046. console.log('销售设置验证结果:', errors);
  1047. return {
  1048. valid: errors.length === 0,
  1049. message: errors.join('、'),
  1050. errors: errors
  1051. };
  1052. },
  1053. // 显示选项卡错误
  1054. showTabError: function(tabId, message) {
  1055. if (!tabId || !message) return;
  1056. var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
  1057. if ($tabLink.length > 0 && !$tabLink.hasClass('tab-error')) {
  1058. $tabLink.addClass('tab-error');
  1059. // 添加错误图标
  1060. if ($tabLink.find('.error-icon').length === 0) {
  1061. $tabLink.append(' <i class="fa fa-exclamation-circle error-icon"></i>');
  1062. }
  1063. // 添加提示信息
  1064. $tabLink.attr('title', message);
  1065. $tabLink.tooltip('destroy').tooltip({
  1066. placement: 'top',
  1067. title: message
  1068. });
  1069. }
  1070. },
  1071. // 清除选项卡错误
  1072. clearTabError: function(tabId) {
  1073. if (!tabId) return;
  1074. var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
  1075. if ($tabLink.length > 0) {
  1076. $tabLink.removeClass('tab-error tab-success');
  1077. $tabLink.find('.error-icon, .success-icon').remove();
  1078. $tabLink.removeAttr('title');
  1079. if ($tabLink.tooltip) {
  1080. try {
  1081. $tabLink.tooltip('destroy');
  1082. } catch (e) {
  1083. console.log('单个选项卡tooltip清理错误:', e);
  1084. }
  1085. }
  1086. }
  1087. },
  1088. // 清除所有选项卡错误
  1089. clearTabErrors: function() {
  1090. var $navTabs = $('.nav-tabs');
  1091. if ($navTabs.length > 0) {
  1092. var $tabLinks = $navTabs.find('a');
  1093. if ($tabLinks.length > 0) {
  1094. $tabLinks.removeClass('tab-error tab-success');
  1095. $tabLinks.find('.error-icon, .success-icon').remove();
  1096. $tabLinks.removeAttr('title');
  1097. if ($tabLinks.tooltip) {
  1098. try {
  1099. $tabLinks.tooltip('destroy');
  1100. } catch (e) {
  1101. console.log('tooltip清理错误:', e);
  1102. }
  1103. }
  1104. }
  1105. }
  1106. },
  1107. // 验证并标记单个选项卡状态
  1108. validateAndMarkTab: function(tabId) {
  1109. if (!tabId) return;
  1110. var that = this;
  1111. var result = null;
  1112. // 清除当前选项卡的标记
  1113. that.clearTabError(tabId);
  1114. switch(tabId) {
  1115. case '#basics':
  1116. result = that.validateBasicsTab();
  1117. break;
  1118. case '#skus':
  1119. result = that.validateSkusTab();
  1120. break;
  1121. case '#delivery':
  1122. result = that.validateDeliveryTab();
  1123. break;
  1124. case '#detail':
  1125. result = that.validateDetailTab();
  1126. break;
  1127. case '#sales':
  1128. result = that.validateSalesTab();
  1129. break;
  1130. }
  1131. if (result) {
  1132. if (!result.valid) {
  1133. that.showTabError(tabId, result.errors.join('、'));
  1134. } else {
  1135. that.showTabSuccess(tabId);
  1136. }
  1137. }
  1138. },
  1139. // 验证所有选项卡但只显示状态,不跳转
  1140. validateAllTabsForStatus: function() {
  1141. var that = this;
  1142. var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
  1143. tabs.forEach(function(tabId) {
  1144. that.validateAndMarkTab(tabId);
  1145. });
  1146. },
  1147. // 显示选项卡成功状态
  1148. showTabSuccess: function(tabId) {
  1149. if (!tabId) return;
  1150. var $tabLink = $('.nav-tabs a[href="' + tabId + '"]');
  1151. if ($tabLink.length > 0) {
  1152. $tabLink.removeClass('tab-error').addClass('tab-success');
  1153. $tabLink.find('.error-icon').remove();
  1154. // 添加成功图标
  1155. if ($tabLink.find('.success-icon').length === 0) {
  1156. $tabLink.append(' <i class="fa fa-check-circle success-icon"></i>');
  1157. }
  1158. $tabLink.removeAttr('title');
  1159. if ($tabLink.tooltip) {
  1160. try {
  1161. $tabLink.tooltip('destroy');
  1162. } catch (e) {
  1163. console.log('tooltip错误:', e);
  1164. }
  1165. }
  1166. }
  1167. },
  1168. // 处理Nice-validator验证错误
  1169. handleValidationError: function(validator) {
  1170. var that = this;
  1171. var $firstInvalidField = null;
  1172. // 多种方式获取验证失败的字段
  1173. if (validator && typeof validator.getInvalidFields === 'function') {
  1174. var $invalidFields = validator.getInvalidFields();
  1175. if ($invalidFields && $invalidFields.length > 0) {
  1176. $firstInvalidField = $($invalidFields[0]);
  1177. }
  1178. }
  1179. // 如果上面方法失败,尝试查找带有错误类的字段
  1180. if (!$firstInvalidField || $firstInvalidField.length === 0) {
  1181. $firstInvalidField = $('.form-control.n-invalid, input.n-invalid, select.n-invalid, textarea.n-invalid').first();
  1182. }
  1183. // 如果还是没有,查找第一个必填但为空的字段
  1184. if (!$firstInvalidField || $firstInvalidField.length === 0) {
  1185. $firstInvalidField = $('input[data-rule*="required"]:visible').filter(function() {
  1186. return !$(this).val();
  1187. }).first();
  1188. }
  1189. if (!$firstInvalidField || $firstInvalidField.length === 0) {
  1190. $firstInvalidField = $('select[data-rule*="required"]:visible').filter(function() {
  1191. return !$(this).val();
  1192. }).first();
  1193. }
  1194. // 如果找到了错误字段
  1195. if ($firstInvalidField && $firstInvalidField.length > 0) {
  1196. var fieldName = $firstInvalidField.attr('name') || $firstInvalidField.attr('id');
  1197. var errorTab = that.getTabByFieldName(fieldName, $firstInvalidField);
  1198. console.log('找到验证错误字段:', fieldName, '对应选项卡:', errorTab);
  1199. if (errorTab) {
  1200. // 跳转到对应选项卡
  1201. var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
  1202. if ($tabLink.length > 0) {
  1203. $tabLink.tab('show');
  1204. // 标记错误选项卡
  1205. that.showTabError(errorTab, '该选项卡有必填项未完成');
  1206. // 滚动到页面顶部
  1207. $('html, body').animate({scrollTop: 0}, 300);
  1208. // 延迟聚焦到错误字段
  1209. setTimeout(function() {
  1210. $firstInvalidField.focus();
  1211. that.highlightErrorField($firstInvalidField);
  1212. }, 500);
  1213. }
  1214. }
  1215. } else {
  1216. console.log('未找到验证错误字段,执行通用错误处理');
  1217. // 如果找不到具体的错误字段,至少显示一个通用提示
  1218. Toastr.error('请检查表单填写是否完整');
  1219. }
  1220. },
  1221. // 根据字段名获取对应的选项卡
  1222. getTabByFieldName: function(fieldName, $field) {
  1223. if (!fieldName && !$field) return '#basics';
  1224. // 根据字段名判断选项卡
  1225. if (fieldName) {
  1226. // 基础信息相关字段
  1227. if (fieldName.indexOf('type') !== -1 ||
  1228. fieldName.indexOf('goods_sn') !== -1 ||
  1229. fieldName.indexOf('title') !== -1 ||
  1230. fieldName.indexOf('category_id') !== -1 ||
  1231. fieldName.indexOf('category_ids') !== -1 ||
  1232. fieldName.indexOf('brand_id') !== -1 ||
  1233. fieldName.indexOf('image') !== -1 && fieldName.indexOf('single') === -1) {
  1234. return '#basics';
  1235. }
  1236. // 价格库存相关字段
  1237. if (fieldName.indexOf('spec_type') !== -1 ||
  1238. fieldName.indexOf('price') !== -1 ||
  1239. fieldName.indexOf('stocks') !== -1 ||
  1240. fieldName.indexOf('marketprice') !== -1 ||
  1241. fieldName.indexOf('single') !== -1) {
  1242. return '#skus';
  1243. }
  1244. // 配送设置相关字段
  1245. if (fieldName.indexOf('delivery_type') !== -1 ||
  1246. fieldName.indexOf('express') !== -1 ||
  1247. fieldName.indexOf('freight') !== -1) {
  1248. return '#delivery';
  1249. }
  1250. // 商品详情相关字段
  1251. if (fieldName.indexOf('content') !== -1 ||
  1252. fieldName.indexOf('detail') !== -1) {
  1253. return '#detail';
  1254. }
  1255. // 销售设置相关字段
  1256. if (fieldName.indexOf('stock_show_type') !== -1 ||
  1257. fieldName.indexOf('sales_show_type') !== -1 ||
  1258. fieldName.indexOf('keywords') !== -1 ||
  1259. fieldName.indexOf('description') !== -1 ||
  1260. fieldName.indexOf('status') !== -1) {
  1261. return '#sales';
  1262. }
  1263. }
  1264. // 根据字段所在的选项卡容器判断
  1265. if ($field && $field.length > 0) {
  1266. var $tabPane = $field.closest('.tab-pane');
  1267. if ($tabPane.length > 0) {
  1268. var tabId = '#' + $tabPane.attr('id');
  1269. return tabId;
  1270. }
  1271. }
  1272. // 默认返回基础信息选项卡
  1273. return '#basics';
  1274. },
  1275. // 高亮错误字段
  1276. highlightErrorField: function($field) {
  1277. if ($field && $field.length > 0) {
  1278. $field.addClass('error-highlight');
  1279. setTimeout(function() {
  1280. $field.removeClass('error-highlight');
  1281. }, 3000);
  1282. // 滚动到字段位置
  1283. var fieldOffset = $field.offset();
  1284. if (fieldOffset) {
  1285. $('html, body').animate({
  1286. scrollTop: fieldOffset.top - 100
  1287. }, 300);
  1288. }
  1289. }
  1290. },
  1291. // 验证整个表单并定位到错误选项卡
  1292. validateFormAndShowErrors: function() {
  1293. var that = this;
  1294. var firstErrorTab = null;
  1295. var errorMessage = '';
  1296. console.log('开始全面验证表单');
  1297. // 验证所有选项卡
  1298. var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
  1299. tabs.forEach(function(tabId) {
  1300. that.clearTabError(tabId);
  1301. var result = null;
  1302. switch(tabId) {
  1303. case '#basics':
  1304. result = that.validateBasicsTab();
  1305. break;
  1306. case '#skus':
  1307. result = that.validateSkusTab();
  1308. break;
  1309. case '#delivery':
  1310. result = that.validateDeliveryTab();
  1311. break;
  1312. case '#detail':
  1313. result = that.validateDetailTab();
  1314. break;
  1315. case '#sales':
  1316. result = that.validateSalesTab();
  1317. break;
  1318. }
  1319. console.log('选项卡', tabId, '验证结果:', result);
  1320. if (result && !result.valid) {
  1321. that.showTabError(tabId, result.message || result.errors.join('、'));
  1322. if (!firstErrorTab) {
  1323. firstErrorTab = tabId;
  1324. errorMessage = result.message || result.errors.join('、');
  1325. }
  1326. }
  1327. });
  1328. // 如果有错误,切换到第一个错误选项卡
  1329. if (firstErrorTab) {
  1330. console.log('发现错误选项卡:', firstErrorTab, '错误信息:', errorMessage);
  1331. var $errorTab = $('.nav-tabs a[href="' + firstErrorTab + '"]');
  1332. if ($errorTab.length > 0) {
  1333. console.log('切换到错误选项卡:', firstErrorTab);
  1334. $errorTab.tab('show');
  1335. // 显示错误提示
  1336. Toastr.error(errorMessage);
  1337. // 延迟聚焦到第一个错误字段
  1338. setTimeout(function() {
  1339. that.focusFirstErrorFieldInTab(firstErrorTab);
  1340. }, 500);
  1341. }
  1342. $('html, body').animate({scrollTop: 0}, 300);
  1343. return false;
  1344. }
  1345. console.log('表单验证通过');
  1346. return true;
  1347. },
  1348. // 聚焦到指定选项卡的第一个错误字段
  1349. focusFirstErrorFieldInTab: function(tabId) {
  1350. var $tabPane = $(tabId);
  1351. if ($tabPane.length === 0) return;
  1352. var $errorField = null;
  1353. // 查找第一个验证失败的字段
  1354. $errorField = $tabPane.find('input[data-rule]:invalid, select[data-rule]:invalid, textarea[data-rule]:invalid').first();
  1355. // 如果没有找到invalid字段,查找必填但为空的字段
  1356. if (!$errorField || $errorField.length === 0) {
  1357. $errorField = $tabPane.find('input[data-rule*="required"]:visible').filter(function() {
  1358. return !$(this).val();
  1359. }).first();
  1360. }
  1361. if (!$errorField || $errorField.length === 0) {
  1362. $errorField = $tabPane.find('select[data-rule*="required"]:visible').filter(function() {
  1363. return !$(this).val();
  1364. }).first();
  1365. }
  1366. // 聚焦并高亮错误字段
  1367. if ($errorField && $errorField.length > 0) {
  1368. $errorField.focus();
  1369. this.highlightErrorField($errorField);
  1370. }
  1371. },
  1372. // 初始化上架时间和下架时间控制
  1373. initOnlineOfflineControl: function() {
  1374. // 上架时间类型切换事件
  1375. $('input[name="row[online_type]"]').change(function() {
  1376. var value = $(this).val();
  1377. // 当类型为定时上架(3)时,显示上架时间选择
  1378. if (value == '3') {
  1379. $('#scheduled-online-time').show();
  1380. } else {
  1381. $('#scheduled-online-time').hide();
  1382. }
  1383. // 当类型为立即上架(1)或定时上架(3)时,显示定时下架选项
  1384. if (value == '1' || value == '3') {
  1385. $('#offline-time-setting').show();
  1386. } else {
  1387. $('#offline-time-setting').hide();
  1388. }
  1389. });
  1390. // 初始执行一次,设置默认状态
  1391. $('input[name="row[online_type]"]:checked').trigger('change');
  1392. // 定时下架复选框切换事件
  1393. $('#c-is_auto_offline').change(function() {
  1394. if ($(this).is(':checked')) {
  1395. $('#scheduled-offline-time').show();
  1396. } else {
  1397. $('#scheduled-offline-time').hide();
  1398. }
  1399. });
  1400. // 初始执行一次,检查定时下架复选框状态
  1401. if ($('#c-is_auto_offline').is(':checked')) {
  1402. $('#scheduled-offline-time').show();
  1403. } else {
  1404. $('#scheduled-offline-time').hide();
  1405. }
  1406. },
  1407. // 初始化商品详情预览功能
  1408. initContentPreview: function() {
  1409. // 设置定时刷新预览
  1410. var previewTimer = null;
  1411. var lastContent = "";
  1412. // 监听标签页切换,确保切换到详情标签页时刷新预览
  1413. $('a[href="#detail"]').on('shown.bs.tab', function (e) {
  1414. updatePreview();
  1415. // 设置定时器,每隔1秒检查内容是否有变化
  1416. if (previewTimer === null) {
  1417. previewTimer = setInterval(function() {
  1418. checkContentChange();
  1419. }, 1000);
  1420. }
  1421. });
  1422. // 离开详情标签页时清除定时器
  1423. $('a').not('a[href="#detail"]').on('shown.bs.tab', function (e) {
  1424. if (previewTimer) {
  1425. clearInterval(previewTimer);
  1426. previewTimer = null;
  1427. }
  1428. });
  1429. // 检查内容变化
  1430. function checkContentChange() {
  1431. var editor = $("#c-content").data("nkeditor");
  1432. if (!editor) return;
  1433. var content = editor.html();
  1434. if (content !== lastContent) {
  1435. lastContent = content;
  1436. updatePreview();
  1437. }
  1438. }
  1439. // 更新预览内容
  1440. function updatePreview() {
  1441. // 获取编辑器实例
  1442. var editor = $("#c-content").data("nkeditor");
  1443. if (!editor) return;
  1444. // 获取编辑器内容
  1445. var content = editor.html();
  1446. // 更新预览区域
  1447. $('#content-preview').html(content || '<div class="text-center text-muted">暂无内容</div>');
  1448. // 调整预览区域的高度
  1449. adjustPreviewHeight();
  1450. }
  1451. // 调整预览区域高度,使其与编辑器一致
  1452. function adjustPreviewHeight() {
  1453. var $editorContainer = $('.ke-container');
  1454. if ($editorContainer.length > 0) {
  1455. var editorHeight = $editorContainer.height();
  1456. $('#content-preview').css('height', editorHeight - 40 + 'px');
  1457. }
  1458. }
  1459. // 初始预览
  1460. setTimeout(function() {
  1461. adjustPreviewHeight();
  1462. updatePreview();
  1463. }, 1000);
  1464. },
  1465. // 格式化SKU规格属性显示
  1466. formatSkuAttr: function(skuAttr) {
  1467. if (!skuAttr) {
  1468. return '';
  1469. }
  1470. try {
  1471. // 尝试解析JSON格式
  1472. var attrs = JSON.parse(skuAttr);
  1473. if (Array.isArray(attrs)) {
  1474. var formatted = [];
  1475. attrs.forEach(function(attr) {
  1476. if (attr.name && attr.value) {
  1477. formatted.push(attr.name + ': ' + attr.value);
  1478. }
  1479. });
  1480. return formatted.join(' | ');
  1481. }
  1482. } catch (e) {
  1483. // 兼容旧的字符串格式:规格名:规格值,规格名:规格值
  1484. if (skuAttr.indexOf(':') !== -1) {
  1485. var attrs = skuAttr.split(',');
  1486. var formatted = [];
  1487. attrs.forEach(function(attr) {
  1488. if (attr.indexOf(':') !== -1) {
  1489. var parts = attr.split(':');
  1490. if (parts.length >= 2) {
  1491. formatted.push(parts[0].trim() + ': ' + parts.slice(1).join(':').trim());
  1492. }
  1493. }
  1494. });
  1495. return formatted.join(' | ');
  1496. }
  1497. }
  1498. return skuAttr;
  1499. },
  1500. // 显示表单错误并定位到对应选项卡
  1501. showFormError: function(ret) {
  1502. var message = ret.msg || '操作失败';
  1503. var errorTab = this.getErrorTab(message);
  1504. // 如果能定位到具体选项卡,显示错误
  1505. if (errorTab) {
  1506. var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
  1507. if ($tabLink.length > 0 && !$tabLink.hasClass('tab-error')) {
  1508. $tabLink.addClass('tab-error');
  1509. if ($tabLink.find('.error-icon').length === 0) {
  1510. $tabLink.append(' <i class="fa fa-exclamation-circle error-icon"></i>');
  1511. }
  1512. $tabLink.attr('title', message);
  1513. if ($tabLink.tooltip) {
  1514. try {
  1515. $tabLink.tooltip('destroy').tooltip({
  1516. placement: 'top',
  1517. title: message
  1518. });
  1519. } catch (e) {
  1520. console.log('tooltip错误:', e);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. // 显示错误提示
  1526. Toastr.error(message);
  1527. },
  1528. // 跳转到有错误的选项卡
  1529. jumpToErrorTab: function(ret) {
  1530. var that = this;
  1531. var message = ret.msg || '操作失败';
  1532. var errorTab = null;
  1533. // 首先尝试从错误信息判断选项卡
  1534. errorTab = this.getErrorTab(message);
  1535. // 如果无法从错误信息判断,则进行全面验证
  1536. if (!errorTab) {
  1537. errorTab = this.findFirstErrorTab();
  1538. }
  1539. // 跳转到错误选项卡
  1540. if (errorTab) {
  1541. var $tabLink = $('.nav-tabs a[href="' + errorTab + '"]');
  1542. if ($tabLink.length > 0) {
  1543. // 切换到对应选项卡
  1544. $tabLink.tab('show');
  1545. // 滚动到页面顶部
  1546. $('html, body').animate({scrollTop: 0}, 300);
  1547. // 延迟聚焦到第一个错误字段
  1548. setTimeout(function() {
  1549. that.focusFirstErrorField(errorTab);
  1550. }, 500);
  1551. }
  1552. }
  1553. },
  1554. // 根据错误信息获取对应的选项卡
  1555. getErrorTab: function(message) {
  1556. if (!message) return null;
  1557. // 基础信息相关错误
  1558. if (message.indexOf('商品类型') !== -1 ||
  1559. message.indexOf('商品编码') !== -1 ||
  1560. message.indexOf('商品标题') !== -1 ||
  1561. message.indexOf('商品分类') !== -1 ||
  1562. message.indexOf('主图') !== -1 ||
  1563. message.indexOf('图片') !== -1 ||
  1564. message.indexOf('品牌') !== -1) {
  1565. return '#basics';
  1566. }
  1567. // 价格库存相关错误
  1568. if (message.indexOf('价格') !== -1 ||
  1569. message.indexOf('库存') !== -1 ||
  1570. message.indexOf('SKU') !== -1 ||
  1571. message.indexOf('规格') !== -1 ||
  1572. message.indexOf('销售价') !== -1 ||
  1573. message.indexOf('市场价') !== -1) {
  1574. return '#skus';
  1575. }
  1576. // 配送设置相关错误
  1577. if (message.indexOf('配送') !== -1 ||
  1578. message.indexOf('运费') !== -1 ||
  1579. message.indexOf('快递') !== -1 ||
  1580. message.indexOf('运费模板') !== -1) {
  1581. return '#delivery';
  1582. }
  1583. // 商品详情相关错误
  1584. if (message.indexOf('详情') !== -1 ||
  1585. message.indexOf('内容') !== -1) {
  1586. return '#detail';
  1587. }
  1588. // 销售设置相关错误
  1589. if (message.indexOf('库存显示') !== -1 ||
  1590. message.indexOf('销量显示') !== -1 ||
  1591. message.indexOf('关键词') !== -1 ||
  1592. message.indexOf('描述') !== -1) {
  1593. return '#sales';
  1594. }
  1595. return null;
  1596. },
  1597. // 查找第一个有错误的选项卡
  1598. findFirstErrorTab: function() {
  1599. var tabs = ['#basics', '#skus', '#delivery', '#detail', '#sales'];
  1600. console.log('开始查找第一个有错误的选项卡');
  1601. for (var i = 0; i < tabs.length; i++) {
  1602. var tabId = tabs[i];
  1603. var result = null;
  1604. console.log('检查选项卡:', tabId);
  1605. try {
  1606. switch(tabId) {
  1607. case '#basics':
  1608. result = this.validateBasicsTab();
  1609. break;
  1610. case '#skus':
  1611. result = this.validateSkusTab();
  1612. break;
  1613. case '#delivery':
  1614. result = this.validateDeliveryTab();
  1615. break;
  1616. case '#detail':
  1617. result = this.validateDetailTab();
  1618. break;
  1619. case '#sales':
  1620. result = this.validateSalesTab();
  1621. break;
  1622. }
  1623. console.log('选项卡 ' + tabId + ' 验证结果:', result);
  1624. if (result && !result.valid) {
  1625. console.log('找到第一个错误选项卡:', tabId, '错误:', result.errors);
  1626. return tabId;
  1627. }
  1628. } catch (e) {
  1629. console.error('验证选项卡 ' + tabId + ' 时出错:', e);
  1630. }
  1631. }
  1632. console.log('没有找到错误选项卡');
  1633. return null;
  1634. },
  1635. // 聚焦到第一个错误字段
  1636. focusFirstErrorField: function(tabId) {
  1637. var $activeTabPane = $(tabId);
  1638. if ($activeTabPane.length === 0) return;
  1639. // 查找第一个有错误的必填字段
  1640. var $errorField = null;
  1641. switch(tabId) {
  1642. case '#basics':
  1643. // 按优先级查找错误字段
  1644. $errorField = $activeTabPane.find('#c-goods_sn:invalid, #c-goods_sn[value=""]').first();
  1645. if ($errorField.length === 0) {
  1646. $errorField = $activeTabPane.find('#c-title:invalid, #c-title[value=""]').first();
  1647. }
  1648. if ($errorField.length === 0) {
  1649. // 对于多选的selectpage控件,需要特殊处理
  1650. var $categoryField = $activeTabPane.find('#c-category_id, #c-category_ids').first();
  1651. if ($categoryField.length > 0) {
  1652. var categoryVal = $categoryField.val();
  1653. if (Controller.isMultiSelectEmpty(categoryVal)) {
  1654. $errorField = $categoryField;
  1655. }
  1656. }
  1657. }
  1658. if ($errorField.length === 0) {
  1659. $errorField = $activeTabPane.find('#c-image:invalid, #c-image[value=""]').first();
  1660. }
  1661. break;
  1662. case '#skus':
  1663. // 检查规格类型
  1664. var specType = $('input[name="row[spec_type]"]:checked').val();
  1665. if (specType == '0') {
  1666. $errorField = $activeTabPane.find('#c-price:invalid, #c-price[value=""]').first();
  1667. if ($errorField.length === 0) {
  1668. $errorField = $activeTabPane.find('#c-stocks:invalid, #c-stocks[value=""]').first();
  1669. }
  1670. }
  1671. break;
  1672. case '#delivery':
  1673. $errorField = $activeTabPane.find('#c-express_template_id:invalid, #c-express_template_id[value=""]').first();
  1674. break;
  1675. case '#sales':
  1676. $errorField = $activeTabPane.find('input[name="row[stock_show_type]"]:invalid').first();
  1677. if ($errorField.length === 0) {
  1678. $errorField = $activeTabPane.find('input[name="row[sales_show_type]"]:invalid').first();
  1679. }
  1680. break;
  1681. }
  1682. // 如果没有找到特定的错误字段,查找第一个有data-rule的空字段
  1683. if (!$errorField || $errorField.length === 0) {
  1684. $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();
  1685. }
  1686. // 聚焦并高亮错误字段
  1687. if ($errorField && $errorField.length > 0) {
  1688. $errorField.focus();
  1689. // 添加错误高亮效果
  1690. $errorField.addClass('error-highlight');
  1691. setTimeout(function() {
  1692. $errorField.removeClass('error-highlight');
  1693. }, 2000);
  1694. // 滚动到字段位置
  1695. var fieldOffset = $errorField.offset();
  1696. if (fieldOffset) {
  1697. $('html, body').animate({
  1698. scrollTop: fieldOffset.top - 100
  1699. }, 300);
  1700. }
  1701. }
  1702. },
  1703. // 验证基础信息选项卡
  1704. validateBasicsTab: function() {
  1705. var isValid = true;
  1706. var errors = [];
  1707. console.log('验证基础信息选项卡');
  1708. // 检查商品类型
  1709. if (!$('input[name="row[type]"]:checked').length) {
  1710. isValid = false;
  1711. errors.push('请选择商品类型');
  1712. }
  1713. // 检查商品编码
  1714. var $goodsSn = $('#c-goods_sn');
  1715. var goodsSnVal = $goodsSn.val();
  1716. console.log('商品编码值:', goodsSnVal);
  1717. if ($goodsSn.length > 0 && $goodsSn.attr('data-rule') && $goodsSn.attr('data-rule').indexOf('required') !== -1) {
  1718. if (!goodsSnVal || goodsSnVal.trim() === '') {
  1719. isValid = false;
  1720. errors.push('商品编码不能为空');
  1721. }
  1722. }
  1723. // 检查商品标题
  1724. var $title = $('#c-title');
  1725. var titleVal = $title.val();
  1726. console.log('商品标题值:', titleVal);
  1727. if ($title.length > 0 && $title.attr('data-rule') && $title.attr('data-rule').indexOf('required') !== -1) {
  1728. if (!titleVal || titleVal.trim() === '') {
  1729. isValid = false;
  1730. errors.push('商品标题不能为空');
  1731. }
  1732. }
  1733. // 检查分类 - 多选控件(兼容不同页面的字段ID)
  1734. var $categoryId = $('#c-category_id, #c-category_ids').first();
  1735. var categoryVal = $categoryId.val();
  1736. console.log('商品分类值:', categoryVal);
  1737. if ($categoryId.length > 0 && $categoryId.attr('data-rule') && $categoryId.attr('data-rule').indexOf('required') !== -1) {
  1738. if (Controller.isMultiSelectEmpty(categoryVal)) {
  1739. isValid = false;
  1740. errors.push('商品分类不能为空');
  1741. console.log('商品分类验证失败');
  1742. }
  1743. }
  1744. // 检查主图
  1745. var $image = $('#c-image');
  1746. var imageVal = $image.val();
  1747. console.log('主图值:', imageVal);
  1748. if ($image.length > 0 && $image.attr('data-rule') && $image.attr('data-rule').indexOf('required') !== -1) {
  1749. if (!imageVal || imageVal.trim() === '') {
  1750. isValid = false;
  1751. errors.push('商品主图不能为空');
  1752. }
  1753. }
  1754. // 检查轮播图
  1755. var $images = $('#c-images');
  1756. var imagesVal = $images.val();
  1757. console.log('轮播图值:', imagesVal);
  1758. if ($images.length > 0 && $images.attr('data-rule') && $images.attr('data-rule').indexOf('required') !== -1) {
  1759. if (!imagesVal || imagesVal.trim() === '') {
  1760. isValid = false;
  1761. errors.push('商品轮播图不能为空');
  1762. }
  1763. }
  1764. console.log('基础信息验证结果:', {valid: isValid, errors: errors});
  1765. return {
  1766. valid: isValid,
  1767. errors: errors
  1768. };
  1769. },
  1770. // 验证价格库存选项卡
  1771. validateSkusTab: function() {
  1772. var isValid = true;
  1773. var errors = [];
  1774. // 检查规格类型
  1775. var specType = $('input[name="row[spec_type]"]:checked').val();
  1776. console.log('验证价格库存选项卡, 规格类型:', specType);
  1777. if (specType == '0') {
  1778. // 单规格验证
  1779. var $price = $('#c-price');
  1780. var priceVal = $price.val();
  1781. console.log('价格字段值:', priceVal);
  1782. if (!priceVal || priceVal.trim() === '' || parseFloat(priceVal) <= 0) {
  1783. isValid = false;
  1784. errors.push('销售价必须大于0');
  1785. }
  1786. var $stocks = $('#c-stocks');
  1787. var stocksVal = $stocks.val();
  1788. console.log('库存字段值:', stocksVal);
  1789. if (!stocksVal || stocksVal.trim() === '' || parseInt(stocksVal) <= 0) {
  1790. isValid = false;
  1791. errors.push('库存必须大于0');
  1792. }
  1793. } else if (specType == '1') {
  1794. // 多规格验证
  1795. if (typeof vm === 'undefined' || !vm || !vm.specList || vm.specList.length === 0) {
  1796. isValid = false;
  1797. errors.push('请设置商品规格');
  1798. } else {
  1799. // 检查是否有有效的规格组合
  1800. if (!vm.tableData || vm.tableData.length === 0) {
  1801. isValid = false;
  1802. errors.push('请设置规格组合数据');
  1803. } else {
  1804. // 检查每个有效的SKU是否有正确的价格和库存
  1805. var hasValidSku = false;
  1806. var validSkuCount = 0;
  1807. console.log('第二次验证: 检查SKU数据, tableData长度:', vm.tableData.length);
  1808. for (var i = 0; i < vm.tableData.length; i++) {
  1809. var sku = vm.tableData[i];
  1810. console.log('第二次验证: 检查SKU[' + i + ']:', {
  1811. status: sku.status,
  1812. price: sku.price,
  1813. stocks: sku.stocks
  1814. });
  1815. // 只检查状态为显示的SKU
  1816. var isVisible = (sku.status === 1 || sku.status === '1' || sku.status === true);
  1817. console.log('第二次验证: SKU[' + i + '] 显示状态:', sku.status, '可见:', isVisible);
  1818. if (isVisible) {
  1819. var price = parseFloat(sku.price);
  1820. var stocks = parseInt(sku.stocks);
  1821. console.log('第二次验证: SKU[' + i + '] 检查通过, price:', price, 'stocks:', stocks);
  1822. hasValidSku = true;
  1823. validSkuCount++;
  1824. // 验证价格必须大于0
  1825. if (!price || price <= 0) {
  1826. isValid = false;
  1827. errors.push('SKU销售价必须大于0');
  1828. console.log('第二次验证: SKU[' + i + ']销售价验证失败:', price);
  1829. break;
  1830. }
  1831. // 验证库存
  1832. if (isNaN(stocks) || stocks <= 0) {
  1833. isValid = false;
  1834. errors.push('SKU库存必须大于0');
  1835. console.log('第二次验证: SKU[' + i + ']库存验证失败:', stocks);
  1836. break;
  1837. }
  1838. }
  1839. }
  1840. console.log('第二次验证: 有效SKU数量:', validSkuCount);
  1841. if (!hasValidSku) {
  1842. isValid = false;
  1843. errors.push('请至少设置一个有效的SKU');
  1844. console.log('第二次验证: 没有有效的SKU');
  1845. }
  1846. }
  1847. }
  1848. } else {
  1849. // 如果没有选择规格类型
  1850. isValid = false;
  1851. errors.push('请选择规格类型');
  1852. }
  1853. console.log('价格库存验证结果:', {valid: isValid, errors: errors});
  1854. return {
  1855. valid: isValid,
  1856. errors: errors
  1857. };
  1858. },
  1859. // 验证配送设置选项卡
  1860. validateDeliveryTab: function() {
  1861. var isValid = true;
  1862. var errors = [];
  1863. // 检查配送方式
  1864. var deliveryType = $('input[name="row[delivery_type]"]:checked').val();
  1865. if (deliveryType === 'EXPRESS') {
  1866. // 如果选择快递配送,检查运费设置
  1867. var expressType = $('input[name="row[express_type]"]:checked').val();
  1868. if (expressType === '3') {
  1869. // 使用运费模板
  1870. var $templateId = $('#c-express_template_id');
  1871. if ($templateId.length > 0 && !$templateId.val()) {
  1872. isValid = false;
  1873. errors.push('请选择运费模板');
  1874. }
  1875. } else if (expressType === '2') {
  1876. // 固定运费
  1877. var $expressPrice = $('#c-express_price');
  1878. if ($expressPrice.length > 0 && (!$expressPrice.val() || parseFloat($expressPrice.val()) < 0)) {
  1879. isValid = false;
  1880. errors.push('请设置正确的运费');
  1881. }
  1882. }
  1883. }
  1884. return {
  1885. valid: isValid,
  1886. errors: errors
  1887. };
  1888. },
  1889. // 验证商品详情选项卡
  1890. validateDetailTab: function() {
  1891. // 详情一般不做必填验证,返回有效
  1892. return {
  1893. valid: true,
  1894. errors: []
  1895. };
  1896. },
  1897. // 验证销售设置选项卡
  1898. validateSalesTab: function() {
  1899. var isValid = true;
  1900. var errors = [];
  1901. // 检查库存显示类型
  1902. var stockShowType = $('input[name="row[stock_show_type]"]:checked').val();
  1903. if (!stockShowType) {
  1904. isValid = false;
  1905. errors.push('请选择库存显示方式');
  1906. }
  1907. // 检查销量显示类型
  1908. var salesShowType = $('input[name="row[sales_show_type]"]:checked').val();
  1909. if (!salesShowType) {
  1910. isValid = false;
  1911. errors.push('请选择销量显示方式');
  1912. }
  1913. return {
  1914. valid: isValid,
  1915. errors: errors
  1916. };
  1917. },
  1918. api: {
  1919. // 解析Config中的JSON字符串的辅助函数
  1920. parseConfigJson: function(configKey, defaultValue) {
  1921. var configValue = Config[configKey] || defaultValue || {};
  1922. // 如果是字符串,尝试解析JSON
  1923. if (typeof configValue === 'string') {
  1924. try {
  1925. return JSON.parse(configValue);
  1926. } catch (e) {
  1927. return defaultValue || {};
  1928. }
  1929. }
  1930. return configValue;
  1931. },
  1932. // 初始化规格类型控制
  1933. initSpecTypeControl: function() {
  1934. // 监听规格类型切换
  1935. $('input[name="row[spec_type]"]').off('change.spectype').on('change.spectype', function() {
  1936. var specType = $(this).val();
  1937. console.log('规格类型切换为:', specType);
  1938. // 使用FastAdmin的Favisible系统自动控制显示隐藏
  1939. $(document).trigger('fa.event.favisible');
  1940. // 如果切换到单规格,清空多规格数据(可选)
  1941. if (specType == '0' && typeof vm !== 'undefined' && vm) {
  1942. console.log('切换到单规格,清空多规格数据');
  1943. // vm.specList = [];
  1944. // vm.tableData = [];
  1945. }
  1946. // 如果切换到多规格,确保Vue组件已初始化
  1947. if (specType == '1' && typeof vm !== 'undefined' && vm) {
  1948. console.log('切换到多规格');
  1949. var $multiSpecForm = $('#multi-spec-form');
  1950. if ($multiSpecForm.length > 0 && !$multiSpecForm.is(':visible')) {
  1951. setTimeout(function() {
  1952. $(document).trigger('fa.event.favisible');
  1953. }, 100);
  1954. }
  1955. }
  1956. });
  1957. // 初始触发一次,确保默认状态正确
  1958. $('input[name="row[spec_type]"]:checked').trigger('change.spectype');
  1959. },
  1960. bindevent: function () {
  1961. // 初始化 popover 组件,用于显示库存和销量显示类型的tip图片
  1962. $('[data-toggle="popover"]').popover({
  1963. trigger: 'hover',
  1964. html: true,
  1965. container: 'body'
  1966. });
  1967. $(document).on("click", ".btn-legal", function (a) {
  1968. Fast.api.ajax({
  1969. url: "shop/ajax/check_content_islegal",
  1970. data: {content: $("#c-content").val()}
  1971. }, function (data, ret) {
  1972. }, function (data, ret) {
  1973. if ($.isArray(data)) {
  1974. Layer.alert(__('Banned words') + ":" + data.join(","));
  1975. }
  1976. });
  1977. });
  1978. $(document).on("click", ".btn-keywords", function (a) {
  1979. Fast.api.ajax({
  1980. url: "shop/ajax/get_content_keywords",
  1981. data: {title: $("#c-title").val(), content: $("#c-content").val()}
  1982. }, function (data, ret) {
  1983. $("#c-keywords").val(data.keywords);
  1984. $("#c-description").val(data.description);
  1985. });
  1986. });
  1987. // 绑定FastAdmin表单验证事件
  1988. var $form = $("form[role=form]");
  1989. // 监听提交按钮点击事件,在表单验证前进行自定义验证
  1990. $form.find('button[type="submit"], input[type="submit"]').off('click.tabvalidation').on('click.tabvalidation', function(e) {
  1991. console.log('提交按钮被点击,开始验证');
  1992. // 进行自定义验证
  1993. if (!Controller.validateFormAndShowErrors()) {
  1994. console.log('自定义验证失败,阻止表单提交');
  1995. e.preventDefault();
  1996. e.stopPropagation();
  1997. return false;
  1998. }
  1999. console.log('自定义验证通过,继续表单提交流程');
  2000. });
  2001. // 使用FastAdmin标准方式绑定表单事件
  2002. Form.api.bindevent($form, function (data, ret) {
  2003. // 提交成功回调
  2004. Controller.clearTabErrors();
  2005. }, function (data, ret) {
  2006. // 提交失败回调
  2007. Controller.showFormError(ret);
  2008. Controller.jumpToErrorTab(ret);
  2009. }, function (success, error) {
  2010. // 提交前验证和数据处理
  2011. console.log('开始提交表单数据');
  2012. // 清除所有选项卡错误标记
  2013. Controller.clearTabErrors();
  2014. // 进行表单验证,如果失败则跳转到错误选项卡
  2015. var validator = $form.data('validator');
  2016. if (validator) {
  2017. console.log('检查表单验证状态');
  2018. // 手动触发验证
  2019. var isValid = validator.isFormValid();
  2020. console.log('表单验证结果:', isValid);
  2021. if (!isValid) {
  2022. console.log('表单验证失败,开始处理错误');
  2023. Controller.handleValidationError(validator);
  2024. return false;
  2025. }
  2026. } else {
  2027. console.log('validator不存在,使用自定义验证');
  2028. // 如果validator不存在,使用我们的自定义验证
  2029. if (!Controller.validateFormAndShowErrors()) {
  2030. console.log('自定义验证失败');
  2031. return false;
  2032. }
  2033. }
  2034. let skus = '[]', spec = '[]';
  2035. var specType = $('input[name="row[spec_type]"]:checked').val();
  2036. console.log('当前规格类型:', specType);
  2037. console.log('vm对象:', typeof vm !== 'undefined' ? vm : 'undefined');
  2038. if (specType == '1') {
  2039. // 多规格处理
  2040. if (typeof vm !== 'undefined' && vm && vm.tableData && vm.tableData.length > 0) {
  2041. console.log('处理多规格商品, tableData长度:', vm.tableData.length);
  2042. try {
  2043. // 不需要特殊处理,直接传输所有数据
  2044. // 后端会根据status字段判断SKU是否有效
  2045. skus = JSON.stringify(vm.tableData);
  2046. spec = JSON.stringify(vm.specList || []);
  2047. console.log('多规格数据处理完成');
  2048. console.log('规格数据 (spec):', vm.specList);
  2049. console.log('SKU数据 (skus):', vm.tableData);
  2050. console.log('规格数据JSON:', spec);
  2051. // 检查规格值中是否包含图片
  2052. vm.specList.forEach(function(spec, specIndex) {
  2053. if (spec.value && spec.value.length > 0) {
  2054. spec.value.forEach(function(value, valueIndex) {
  2055. if (value.image) {
  2056. console.log('规格[' + specIndex + ']值[' + valueIndex + ']包含图片:', value.image);
  2057. }
  2058. });
  2059. }
  2060. });
  2061. } catch (e) {
  2062. console.log('多规格处理出错:', e);
  2063. Toastr.error('多规格数据处理失败');
  2064. return false;
  2065. }
  2066. } else {
  2067. console.log('多规格数据不完整');
  2068. Toastr.error('请设置完整的多规格数据');
  2069. return false;
  2070. }
  2071. } else {
  2072. // 单规格处理 - 统一使用skus和spec格式
  2073. console.log('处理单规格商品');
  2074. var singleSku = {
  2075. sku_sn: $('#c-sku-sn').val() || $('#c-goods_sn').val() || '',
  2076. price: parseFloat($('#c-price').val()) || 0,
  2077. lineation_price: parseFloat($('#c-lineation_price').val()) || 0,
  2078. cost_price: parseFloat($('#c-cost_price').val()) || 0,
  2079. stocks: parseInt($('#c-stocks').val()) || 0,
  2080. weight: parseFloat($('#c-weight').val()) || 0,
  2081. volume: parseFloat($('#c-volume').val()) || 0,
  2082. image: $('#c-single-image').val() || '',
  2083. sales: 0,
  2084. status: 1,
  2085. is_default: 1,
  2086. skus: []
  2087. };
  2088. skus = JSON.stringify([singleSku]);
  2089. spec = JSON.stringify([]);
  2090. console.log('单规格数据处理完成', singleSku);
  2091. }
  2092. //绑定商品属性
  2093. let html = `<textarea id="c-skus" class="form-control hide" rows="5" name="row[skus]" cols="50">${skus}</textarea>
  2094. <textarea id="c-spec" class="form-control hide" rows="5" name="row[spec]" cols="50">${spec}</textarea>`;
  2095. this.find('#goods-sku').html(html);
  2096. console.log(html);
  2097. //提交表单
  2098. Form.api.submit(this, success, error);
  2099. return false;
  2100. });
  2101. require(['backend/shop/card'], function (Card) {
  2102. Card.api.bindcardevent();
  2103. });
  2104. },
  2105. bindUpload: function () {
  2106. if ($('.goods-sku-table table td.td-img button.faupload:not([initialized])').length === 0) {
  2107. return;
  2108. }
  2109. clearTimeout(si);
  2110. si = setTimeout(function () {
  2111. let doms = $('.goods-sku-table table td.td-img').toArray();
  2112. function uploadButtonTask(deadline) {
  2113. while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && doms.length > 0) {
  2114. bindEvent();
  2115. }
  2116. if (doms.length > 0)
  2117. requestIdleCallback(uploadButtonTask);
  2118. }
  2119. function bindEvent() {
  2120. var dom = doms.shift();
  2121. if (dom) {
  2122. var $elements = $(".faselect,.fachoose", dom);
  2123. if ($elements && $elements.length > 0) {
  2124. $elements.off('click');
  2125. }
  2126. Form.events.plupload(dom);
  2127. Form.events.faselect(dom);
  2128. }
  2129. }
  2130. requestIdleCallback(uploadButtonTask, {timeout: 1000});
  2131. }, 250);
  2132. },
  2133. add_sku: function () {
  2134. //移除属性的
  2135. $('.td-img').find('.faupload').removeAttr('initialized');
  2136. require(['vue'], function (Vue) {
  2137. vm = new Vue({
  2138. el: '#vue-app',
  2139. computed: {
  2140. specValueText() {
  2141. return (skus, k) => {
  2142. return !skus || typeof skus[k] == 'undefined' ? '' : skus[k];
  2143. }
  2144. },
  2145. contentHtml() {
  2146. return field => {
  2147. return `<div class='input-group'>
  2148. <input class='form-control' type='text' value=''/>
  2149. <div class='input-group-btn'>
  2150. <span class='btn btn-success sku-confirm' data-field='${field}'>
  2151. 确定
  2152. </span>
  2153. </div>
  2154. </div>`;
  2155. }
  2156. }
  2157. },
  2158. watch: {
  2159. specList: {
  2160. handler: function (val) {
  2161. this.renderTableData(val);
  2162. // 延迟绑定上传功能,确保DOM更新完成
  2163. var that = this;
  2164. that.$nextTick(function() {
  2165. Controller.api.bindSpecValueUpload();
  2166. Controller.api.rebindMultipleEdit();
  2167. // 重新绑定规格值上传按钮
  2168. setTimeout(function() {
  2169. Controller.api.bindUploadButtons();
  2170. // 更新图片预览
  2171. that.updateSpecImagePreviews();
  2172. }, 300);
  2173. });
  2174. },
  2175. deep: true
  2176. }
  2177. },
  2178. data() {
  2179. return {
  2180. spec_name: '',
  2181. specList: [],
  2182. tableData: [],
  2183. result: [],
  2184. skus: [], //
  2185. defaultSpecIndex: 0 // 默认规格索引
  2186. }
  2187. },
  2188. mounted() {
  2189. let that = this;
  2190. that.init();
  2191. // 延迟初始化规格类型切换,确保DOM完全渲染
  2192. setTimeout(function() {
  2193. Controller.api.initSpecTypeControl();
  2194. // 初始绑定规格值上传功能
  2195. Controller.api.bindSpecValueUpload();
  2196. // 如果是编辑模式且是多规格商品,确保多规格表单显示
  2197. if (Config.goods && Config.goods.spec_type == '1') {
  2198. console.log('编辑模式:显示多规格表单');
  2199. var $multiSpecForm = $('#multi-spec-form');
  2200. if ($multiSpecForm.length > 0) {
  2201. $multiSpecForm.show();
  2202. console.log('多规格表单已显示');
  2203. }
  2204. }
  2205. }, 100);
  2206. //批量设置
  2207. this.$nextTick(function () {
  2208. $('body').on('click', function (e) {
  2209. if (!$(e.target).hasClass('multiple-edit') &&
  2210. $(e.target).parents('.multiple-edit').length === 0 &&
  2211. $(e.target).parents('.popover.in').length === 0) {
  2212. $('.multiple-edit').popover('hide');
  2213. }
  2214. });
  2215. $(".multiple-edit").popover({
  2216. sanitize: false,
  2217. container: "body",
  2218. html: true,
  2219. placement: "top",
  2220. trigger: 'manual'
  2221. }).on('click', function (e) {
  2222. $(".popover").hide();
  2223. $(this).popover('show');
  2224. });
  2225. $(document).on('click', '.sku-confirm', function () {
  2226. let value = $(this).parent().prev().val().trim();
  2227. let field = $(this).data('field');
  2228. if (field != 'sku_sn' && Number.isNaN(parseFloat(value))) {
  2229. Toastr.error('请输入数字');
  2230. return;
  2231. }
  2232. for (let [index] of that.tableData.entries()) {
  2233. that.$set(that.tableData[index], field, value);
  2234. }
  2235. });
  2236. require(['selectpage'], function () {
  2237. $('.selectpage', $('.spec-template')).selectPage({
  2238. eAjaxSuccess: function (data) {
  2239. data.totalRow = data.total;
  2240. return data;
  2241. },
  2242. eSelect: function (row) {
  2243. let spec_names = row.spec_names.split(';');
  2244. let spec_values = row.spec_values.split(';');
  2245. let list = [];
  2246. for (let [i, v] of spec_names.entries()) {
  2247. // 转换规格模板数据为新格式
  2248. let valueList = spec_values[i].split(',').map(val => ({
  2249. name: val,
  2250. image: '',
  2251. description: ''
  2252. }));
  2253. list.push({
  2254. name: v,
  2255. type: 'basic', // 默认为基础规格
  2256. value: valueList
  2257. });
  2258. }
  2259. that.tableData = [];
  2260. that.skus = [];
  2261. setTimeout(function () {
  2262. that.specList = list;
  2263. }, 100);
  2264. }
  2265. });
  2266. });
  2267. })
  2268. },
  2269. methods: {
  2270. init() {
  2271. console.log('Vue组件初始化开始');
  2272. console.log('Config数据:', Config);
  2273. let skus = [];
  2274. if (Config.goods_skus && Config.goods_skus.length) {
  2275. console.log('发现商品SKU数据,数量:', Config.goods_skus.length);
  2276. console.log('完整SKU数据:', Config.goods_skus);
  2277. // 如果是多规格商品,解析规格数据
  2278. if (Config.goods && Config.goods.spec_type == '1') {
  2279. console.log('初始化多规格数据');
  2280. let specList = [];
  2281. let specName = {};
  2282. for (let item of Config.goods_skus) {
  2283. console.log('处理SKU项:', item);
  2284. if (item.sku_attr) {
  2285. console.log('SKU属性数据:', item.sku_attr);
  2286. let attr = [];
  2287. let skuAttrs = [];
  2288. // 尝试解析JSON格式
  2289. try {
  2290. skuAttrs = JSON.parse(item.sku_attr);
  2291. console.log('解析JSON格式成功:', skuAttrs);
  2292. } catch (e) {
  2293. // 如果JSON解析失败,尝试旧的字符串格式
  2294. console.log('JSON解析失败,尝试字符串格式:', e);
  2295. let sku_attr = item.sku_attr.split(',');
  2296. skuAttrs = [];
  2297. for (let res of sku_attr) {
  2298. let sku = res.split(':');
  2299. if (sku.length >= 2) {
  2300. skuAttrs.push({
  2301. name: sku[0],
  2302. value: sku[1]
  2303. });
  2304. }
  2305. }
  2306. console.log('转换字符串格式为对象:', skuAttrs);
  2307. }
  2308. // 处理规格属性数组
  2309. for (let attrObj of skuAttrs) {
  2310. if (attrObj.name && attrObj.value) {
  2311. attr.push(attrObj.value);
  2312. //属性名
  2313. if (!specName[attrObj.name]) {
  2314. specName[attrObj.name] = [];
  2315. }
  2316. if (!specName[attrObj.name].includes(attrObj.value)) {
  2317. specName[attrObj.name].push(attrObj.value);
  2318. }
  2319. }
  2320. }
  2321. // 使用字符串作为键,与renderTableData中的查找方式一致
  2322. let attrKey = attr.join(',');
  2323. skus[attrKey] = item;
  2324. console.log('SKU映射:', attrKey, '->', item);
  2325. } else {
  2326. console.warn('SKU缺少sku_attr字段:', item);
  2327. }
  2328. }
  2329. console.log('解析完成的规格名称映射:', specName);
  2330. // 构建规格值映射表(从数据库获取的完整数据)
  2331. let specValueMap = {};
  2332. if (Config.spec_values && Config.spec_values.length > 0) {
  2333. console.log('发现规格值数据:', Config.spec_values);
  2334. console.log('规格值数据类型:', typeof Config.spec_values);
  2335. console.log('规格值数据结构样例:', Config.spec_values[0]);
  2336. Config.spec_values.forEach(function(item) {
  2337. if (!specValueMap[item.spec_name]) {
  2338. specValueMap[item.spec_name] = {};
  2339. }
  2340. specValueMap[item.spec_name][item.value] = {
  2341. name: item.value,
  2342. image: item.image || '',
  2343. description: item.description || ''
  2344. };
  2345. });
  2346. console.log('规格值映射表:', specValueMap);
  2347. } else {
  2348. console.log('没有发现规格值数据,使用默认处理方式');
  2349. console.log('Config.spec_values:', Config.spec_values);
  2350. }
  2351. for (let i in specName) {
  2352. // 转换旧格式数据为新格式,优先使用数据库中的完整数据
  2353. let valueList = specName[i].map(val => {
  2354. if (typeof val === 'string') {
  2355. // 从映射表中查找完整数据,如果没有则使用默认值
  2356. if (specValueMap[i] && specValueMap[i][val]) {
  2357. console.log('找到规格值完整数据:', i, val, specValueMap[i][val]);
  2358. return {
  2359. name: specValueMap[i][val].name,
  2360. image: specValueMap[i][val].image || '',
  2361. description: specValueMap[i][val].description || ''
  2362. };
  2363. } else {
  2364. console.log('使用默认规格值数据:', i, val);
  2365. return {
  2366. name: val,
  2367. image: '',
  2368. description: ''
  2369. };
  2370. }
  2371. }
  2372. // 如果已经是对象格式,确保结构完整
  2373. return {
  2374. name: val.name || val,
  2375. image: val.image || '',
  2376. description: val.description || ''
  2377. };
  2378. });
  2379. specList.push({
  2380. name: i,
  2381. type: 'basic', // 默认为基础规格
  2382. value: valueList
  2383. });
  2384. }
  2385. this.skus = skus;
  2386. this.specList = specList;
  2387. console.log('多规格初始化完成,规格数量:', specList.length);
  2388. console.log('规格列表:', specList);
  2389. // 延迟触发数据渲染,确保DOM已准备好
  2390. this.$nextTick(() => {
  2391. console.log('Vue nextTick: 准备渲染多规格表格数据');
  2392. if (this.specList.length > 0) {
  2393. this.renderTableData(this.specList);
  2394. // 在数据渲染完成后,更新规格值图片预览
  2395. setTimeout(() => {
  2396. this.updateSpecImagePreviews();
  2397. }, 500);
  2398. }
  2399. });
  2400. }
  2401. }
  2402. console.log('Vue组件初始化完成');
  2403. },
  2404. addSpec() {
  2405. if (!this.spec_name.trim()) {
  2406. Toastr.error('请输入规格名称');
  2407. return;
  2408. }
  2409. if (this.specList.some(item => item.name == this.spec_name)) {
  2410. Toastr.error('已存在规格名称');
  2411. return;
  2412. }
  2413. this.specList.push({
  2414. name: this.spec_name,
  2415. type: 'basic', // 默认为基础规格
  2416. value: [{
  2417. name: '',
  2418. image: '',
  2419. description: ''
  2420. }]
  2421. });
  2422. this.spec_name = '';
  2423. },
  2424. showAddSpecForm() {
  2425. // 添加新的规格
  2426. this.specList.push({
  2427. name: '',
  2428. type: 'basic', // 默认为基础规格
  2429. value: [{
  2430. name: '',
  2431. image: '',
  2432. description: ''
  2433. }]
  2434. });
  2435. },
  2436. addSpecValue(key) {
  2437. this.specList[key].value.push({
  2438. name: '',
  2439. image: '',
  2440. description: ''
  2441. });
  2442. // 重新绑定上传功能
  2443. this.$nextTick(function() {
  2444. setTimeout(function() {
  2445. Controller.api.bindUploadButtons();
  2446. }, 100);
  2447. });
  2448. },
  2449. removeSpecValue(key, index) {
  2450. this.specList[key].value.splice(index, 1);
  2451. },
  2452. //渲染表格数据
  2453. renderTableData(list) {
  2454. // 判断是否为编辑模式
  2455. const isEditMode = Config.goods && Config.goods.id;
  2456. // 统一的默认值 - 新增模式使用固定默认值
  2457. const defaultValues = {
  2458. goods_sn: $('#c-goods_sn').val() || '',
  2459. price: '0.01',
  2460. lineation_price: '0.00',
  2461. cost_price: '0.00',
  2462. weight: '0.00',
  2463. volume: '0.00',
  2464. stocks: '1'
  2465. };
  2466. let columns = [];
  2467. this.result = [];
  2468. this.resetSpec(list, 0);
  2469. console.log('渲染表格数据,模式:', isEditMode ? '编辑' : '新增');
  2470. console.log('固定默认值:', defaultValues);
  2471. console.log('SKU数据映射:', this.skus);
  2472. //渲染表格数据
  2473. this.result.forEach((item, index) => {
  2474. let su = this.skus[item];
  2475. console.log('处理规格组合[' + index + ']:', item, '对应SKU数据:', su);
  2476. let row;
  2477. if (isEditMode && su) {
  2478. // 编辑模式:完全使用后台SKU数据
  2479. console.log('编辑模式:使用后台SKU数据:', su);
  2480. row = {
  2481. skus: item ? item.split(',') : [],
  2482. sku_sn: su.sku_sn || '',
  2483. image: su.image || '',
  2484. price: parseFloat(su.price) || 0,
  2485. lineation_price: parseFloat(su.lineation_price) || 0,
  2486. cost_price: parseFloat(su.cost_price) || 0,
  2487. weight: parseFloat(su.weight) || 0,
  2488. volume: parseFloat(su.volume) || 0,
  2489. stocks: parseInt(su.stocks) || 0,
  2490. sales: parseInt(su.sales) || 0,
  2491. status: su.status !== undefined ? parseInt(su.status) : 1,
  2492. is_default: su.is_default !== undefined ? parseInt(su.is_default) : 0
  2493. };
  2494. console.log('编辑模式最终行数据:', row);
  2495. } else {
  2496. // 新增模式或编辑模式下没有对应SKU数据:使用固定默认值
  2497. console.log('新增模式:使用固定默认值');
  2498. row = {
  2499. skus: item ? item.split(',') : [],
  2500. sku_sn: defaultValues.goods_sn,
  2501. image: '',
  2502. price: defaultValues.price,
  2503. lineation_price: defaultValues.lineation_price,
  2504. cost_price: defaultValues.cost_price,
  2505. weight: defaultValues.weight,
  2506. volume: defaultValues.volume,
  2507. stocks: defaultValues.stocks,
  2508. sales: 0,
  2509. status: 1, // 默认显示状态
  2510. is_default: index === 0 ? 1 : 0 // 第一个SKU默认为默认规格
  2511. };
  2512. console.log('新增模式最终行数据:', row);
  2513. }
  2514. // 保留已有的用户修改数据(仅在新增模式下)
  2515. if (!isEditMode) {
  2516. let old = this.tableData[index];
  2517. if (old) {
  2518. console.log('新增模式:保留用户修改的数据:', old);
  2519. for (let i in row) {
  2520. // 只有在新值为空且旧值不为空时才使用旧值
  2521. if ((row[i] === '' || row[i] === 0 || row[i] === '0.00') && old[i]) {
  2522. row[i] = old[i];
  2523. }
  2524. }
  2525. }
  2526. }
  2527. columns.push(row);
  2528. });
  2529. this.tableData = columns;
  2530. console.log('最终表格数据:', this.tableData);
  2531. // 在编辑模式下,设置默认规格的索引
  2532. if (isEditMode) {
  2533. this.defaultSpecIndex = this.tableData.findIndex(item => item.is_default === 1);
  2534. console.log('设置默认规格索引:', this.defaultSpecIndex);
  2535. }
  2536. //更新dom,加载事件
  2537. this.$nextTick(function () {
  2538. Controller.api.bindUpload();
  2539. Controller.api.bindSpecValueUpload();
  2540. // 重新绑定批量编辑popover
  2541. Controller.api.rebindMultipleEdit();
  2542. });
  2543. },
  2544. removeSpec(key) {
  2545. this.specList.splice(key, 1);
  2546. },
  2547. // 更新规格值图片预览
  2548. updateSpecImagePreviews() {
  2549. console.log('开始更新规格值图片预览');
  2550. this.specList.forEach((spec, specKey) => {
  2551. if (spec.value && spec.value.length > 0) {
  2552. spec.value.forEach((value, valueIndex) => {
  2553. if (value.image) {
  2554. const previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
  2555. const $preview = $('#' + previewId);
  2556. if ($preview.length > 0) {
  2557. const img = '<img src="' + Fast.api.cdnurl(value.image) + '" style="width:40px;height:40px;object-fit:cover;border-radius:4px;border:1px solid #ddd;">';
  2558. $preview.html(img);
  2559. console.log('更新规格值图片预览:', previewId, value.image);
  2560. }
  2561. }
  2562. });
  2563. }
  2564. });
  2565. },
  2566. //组合规格属性
  2567. resetSpec(list, index) {
  2568. if (list[index] != undefined) {
  2569. let value = list[index].value.map(item => typeof item === 'string' ? item : item.name);
  2570. if (!index) {
  2571. this.result = value;
  2572. } else {
  2573. let res = [];
  2574. for (let i of this.result) {
  2575. for (let j of value) {
  2576. res.push(i + ',' + j);
  2577. }
  2578. }
  2579. if (res.length) {
  2580. this.result = res;
  2581. }
  2582. }
  2583. this.resetSpec(list, ++index);
  2584. }
  2585. },
  2586. }
  2587. });
  2588. });
  2589. //情况属性
  2590. $(document).on('click', '.btn-del-sku', function () {
  2591. vm.specList = [];
  2592. vm.tableData = [];
  2593. });
  2594. //监听图片变化赋值
  2595. $(document).on('change', '.sku-images', function () {
  2596. let index = $(this).data('index');
  2597. let value = $(this).val();
  2598. vm.tableData[index].image = value;
  2599. });
  2600. },
  2601. // 重新绑定批量编辑功能
  2602. rebindMultipleEdit: function() {
  2603. var $multipleEdit = $(".multiple-edit");
  2604. if (!$multipleEdit || $multipleEdit.length === 0) {
  2605. return;
  2606. }
  2607. // 销毁之前的popover
  2608. $multipleEdit.popover('destroy');
  2609. // 重新初始化popover
  2610. $multipleEdit.popover({
  2611. sanitize: false,
  2612. container: "body",
  2613. html: true,
  2614. placement: "top",
  2615. trigger: 'manual'
  2616. });
  2617. if ($multipleEdit && $multipleEdit.length > 0) {
  2618. $multipleEdit.off('click.multiple').on('click.multiple', function (e) {
  2619. $(".popover").hide();
  2620. $(this).popover('show');
  2621. });
  2622. }
  2623. },
  2624. // 绑定规格值图片上传功能
  2625. bindSpecValueUpload: function() {
  2626. // 检查是否存在规格相关的元素
  2627. if ($('.spec-image-input').length === 0) {
  2628. return;
  2629. }
  2630. // 监听规格值图片变化
  2631. $(document).off('change.specvalue', '.spec-image-input');
  2632. $(document).on('change.specvalue', '.spec-image-input', function () {
  2633. var specKey = parseInt($(this).data('spec-key'));
  2634. var valueIndex = parseInt($(this).data('value-index'));
  2635. var imageUrl = $(this).val();
  2636. if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
  2637. vm.$set(vm.specList[specKey].value[valueIndex], 'image', imageUrl);
  2638. console.log('规格值图片已更新:', {
  2639. specKey: specKey,
  2640. valueIndex: valueIndex,
  2641. imageUrl: imageUrl,
  2642. specData: vm.specList[specKey].value[valueIndex]
  2643. });
  2644. } else {
  2645. console.warn('无法更新规格值图片,数据结构不正确:', {
  2646. specKey: specKey,
  2647. valueIndex: valueIndex,
  2648. hasVm: !!vm,
  2649. hasSpecList: !!(vm && vm.specList),
  2650. hasSpec: !!(vm && vm.specList && vm.specList[specKey]),
  2651. hasValue: !!(vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex])
  2652. });
  2653. }
  2654. });
  2655. // 延迟绑定上传功能,确保DOM已渲染
  2656. setTimeout(function() {
  2657. Controller.api.bindUploadButtons();
  2658. }, 200);
  2659. },
  2660. // 绑定上传按钮
  2661. bindUploadButtons: function() {
  2662. // 检查是否存在上传按钮
  2663. if ($('.spec-upload-btn').length === 0) {
  2664. return;
  2665. }
  2666. // 延迟执行,确保DOM已完全渲染
  2667. setTimeout(function() {
  2668. require(['upload'], function (Upload) {
  2669. // 绑定规格值上传按钮
  2670. $('.spec-upload-btn:not([initialized])').each(function() {
  2671. var $btn = $(this);
  2672. var specKey = $btn.attr('data-spec-key');
  2673. var valueIndex = $btn.attr('data-value-index');
  2674. if (specKey !== undefined && valueIndex !== undefined) {
  2675. $btn.attr('initialized', true);
  2676. if ($btn && $btn.length > 0) {
  2677. $btn.off('click.specUpload').on('click.specUpload', function() {
  2678. var inputId = 'c-spec-image-' + specKey + '-' + valueIndex;
  2679. var previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
  2680. // 创建临时按钮用于上传
  2681. var tempBtn = $('<button type="button" class="faupload" style="display:none;"></button>');
  2682. tempBtn.attr('data-input-id', inputId);
  2683. tempBtn.attr('data-preview-id', previewId);
  2684. tempBtn.attr('data-mimetype', $btn.attr('data-mimetype'));
  2685. tempBtn.attr('data-multiple', $btn.attr('data-multiple'));
  2686. $('body').append(tempBtn);
  2687. // 使用FastAdmin标准上传方法
  2688. Upload.api.upload(tempBtn, function(data, ret) {
  2689. var url = data.url || '';
  2690. console.log('规格值图片上传成功:', {
  2691. inputId: inputId,
  2692. url: url,
  2693. specKey: specKey,
  2694. valueIndex: valueIndex
  2695. });
  2696. // 直接更新Vue数据而不是DOM操作
  2697. if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
  2698. vm.$set(vm.specList[specKey].value[valueIndex], 'image', url);
  2699. console.log('Vue数据已更新:', vm.specList[specKey].value[valueIndex]);
  2700. }
  2701. // 同时更新输入框的值以保持同步
  2702. $('#' + inputId).val(url);
  2703. // 更新预览
  2704. var $preview = $('#' + previewId);
  2705. if (url) {
  2706. var img = '<img src="' + Fast.api.cdnurl(url) + '" style="width:100%;height:100%;object-fit:cover;">';
  2707. $preview.html(img);
  2708. } else {
  2709. $preview.empty();
  2710. }
  2711. // 清理临时按钮
  2712. tempBtn.remove();
  2713. }, function(data, ret) {
  2714. // 错误回调
  2715. console.error('上传失败:', ret);
  2716. Toastr.error(ret.msg || '上传失败');
  2717. tempBtn.remove();
  2718. });
  2719. // 触发上传
  2720. tempBtn.click();
  2721. });
  2722. }
  2723. }
  2724. });
  2725. // 绑定选择按钮
  2726. $('.spec-choose-btn:not([initialized])').each(function() {
  2727. var $btn = $(this);
  2728. if (!$btn || $btn.length === 0) {
  2729. return;
  2730. }
  2731. var specKey = $btn.attr('data-spec-key');
  2732. var valueIndex = $btn.attr('data-value-index');
  2733. if (specKey !== undefined && valueIndex !== undefined) {
  2734. $btn.attr('initialized', true);
  2735. if ($btn && $btn.length > 0) {
  2736. $btn.off('click.specChoose').on('click.specChoose', function() {
  2737. var inputId = 'c-spec-image-' + specKey + '-' + valueIndex;
  2738. var previewId = 'p-spec-image-' + specKey + '-' + valueIndex;
  2739. parent.Fast.api.open("general/attachment/select?element_id=" + inputId + "&multiple=false&mimetype=image/*", __('Choose'), {
  2740. callback: function(data) {
  2741. var url = data.url || '';
  2742. // 直接更新Vue数据
  2743. if (vm && vm.specList && vm.specList[specKey] && vm.specList[specKey].value[valueIndex]) {
  2744. vm.$set(vm.specList[specKey].value[valueIndex], 'image', url);
  2745. console.log('选择图片Vue数据已更新:', vm.specList[specKey].value[valueIndex]);
  2746. }
  2747. // 同时更新输入框的值以保持同步
  2748. $('#' + inputId).val(url);
  2749. // 更新预览
  2750. var $preview = $('#' + previewId);
  2751. if (url) {
  2752. var img = '<img src="' + Fast.api.cdnurl(url) + '" style="width:100%;height:100%;object-fit:cover;">';
  2753. $preview.html(img);
  2754. } else {
  2755. $preview.empty();
  2756. }
  2757. }
  2758. });
  2759. });
  2760. }
  2761. }
  2762. });
  2763. });
  2764. }, 100);
  2765. },
  2766. // 内容处理
  2767. content: function (value, row, index) {
  2768. var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "350px";
  2769. 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>";
  2770. },
  2771. }
  2772. };
  2773. return Controller;
  2774. });