goods.js 148 KB

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