fuliqi
2024-01-24 29c1e7eb5ac16e90d8991a86c1c071bc312ec8d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
<template>
  <div class="batchImportCreateOrder">
    <el-form size="mini" ref="form" :model="form">
      <div class="con-box">
        <div class="inside-box-left">
          <div class="box1">
            <el-form-item label="物流服务商:" prop="warehouseServiceName"
                          :rules="formRules.warehouseServiceName" ref="warehouseServiceName"
                          label-width="120px">
              <el-select v-model="form.warehouseServiceName" placeholder="请选择物流服务商"
                         @change="changeWarehouseVal">
                <el-option :value="item.warehouseService" :label="item.warehouseServiceName"
                           v-for="item in warehouseData" :key="item.warehouseService"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="box2">
            <el-form-item label="仓库名称:" prop="deliveryWarehouse"
                          :rules="formRules.deliveryWarehouse" ref="deliveryWarehouse"
                          label-width="120px">
              <el-select clearable v-model="form.deliveryWarehouse" placeholder="请选择仓库名称">
                <el-option :value="item.entityWarehouseNo" :label="item.warehouseName"
                           v-for="item in deliveryWarehouseData" :key="item.entityWarehouseNo">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="inside-box-right">
          <div class="batchImportDiv">
            <span class="inside-box">
              <span class="itemTip">温馨提示:为保证成功导入,请按照导入模板字段要求进行填写</span>
              <el-button :disabled="cancelBtnIsDisabled" size="mini" type="warning" @click="importOrder" style="margin-left:15px;">
                导入
              </el-button>
              <el-button size="mini" @click="downTemplate">下载模板</el-button>
            </span>
          </div>
        </div>
      </div>
      <list-condition-template ref="tableBox" :tableData="form.tableData" :total="total"
                            @page-info-change="handlePageInfoChange">
          <template slot="columns">
            <el-table-column label="所属渠道" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.orderSource`"
                              :rules="formRules.orderSource">
                  <span v-if="!scope.row.isEdit">{{scope.row.orderSourceName}}</span>
                  <el-select v-else v-model="scope.row.orderSource" placeholder="请选择所属渠道" @change="(val) => changeOrderSource(val, scope.row, scope.$index)">
                    <el-option v-for="item in orderSourceArr" :key="item.id" :value="item.id"
                              :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="门店名称" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.contractId`"
                              :rules="formRules.contractId">
                  <el-select clearable v-model="scope.row.contractId"
                            :disabled="!scope.row.isEdit ? true : false" placeholder="请选择门店名称">
                    <el-option v-for="item in shopNameArr" :key="item.id" :value="item.id"
                              :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="关联订单号" width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.orderSourceCode`">
                  <span v-if="!scope.row.isEdit">{{scope.row.orderSourceCode}}</span>
                  <el-input v-else placeholder="请输入关联订单号(原始订单号/订单编号)"
                            v-model.trim="scope.row.orderSourceCode">
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="商品主编码" min-width="150px">
              <template slot-scope="scope">
                <span>{{scope.row.spuNum}}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.spuName`" :rules="formRules.spuName">
                  <span v-if="!scope.row.isEdit">{{scope.row.spuName}}</span>
                  <el-input v-else v-model.trim="scope.row.spuName"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" width="160px" prop="spuProps">
            </el-table-column>
            <template v-if="form.warehouseServiceName === 'JD'">
              <el-table-column label="规格编码" width="130px">
                <template slot-scope="scope">
                  <el-form-item :prop="`tableData.${scope.$index}.specificationCode`" :rules="[
                            {
                              validator: specificationCodeVail,
                              row: scope.row,
                              warehouseServiceName:form.warehouseServiceName
                            }
                          ]">
                    <el-select v-model="scope.row.specificationCode" multiple placeholder="请选择"
                              @change="changeSpecificationCodeVal($event,scope.row,scope.$index)"
                              :disabled="!scope.row.isEdit ? true : false">
                      <el-option v-for="item in scope.row.specificationCodeList" :key="item.prodSkuNo"
                                :label="item.unitOfMeasurement + '*'+ item.skuUnit"
                                :value="item.prodSkuNo">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="发货数量" min-width="150px">
                <template slot-scope="scope">
                  <span v-if="scope.row.shipmentsCountList.length">
                    <el-form-item v-for="(item,index) in scope.row.shipmentsCountList" :key="index"
                                  :prop="`tableData.${scope.$index}.shipmentsCountList.${index}.shipmentsCount`"
                                  :rules="[
                                  {
                                    validator: shipmentsCountVail,
                                    warehouseServiceName:form.warehouseServiceName
                                  }
                                ]">
                      <el-input-number :min="1" v-model="item.shipmentsCount"
                                      :disabled="!scope.row.isEdit ? true : false"
                                      @change="changeShipmentsCountVal(scope.row.specificationCode,scope.row, scope.$index)">
                      </el-input-number>
                    </el-form-item>
                  </span>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="可用库存" prop="stock" align="center"></el-table-column>
            <el-table-column label="总数量(瓶)" min-width="160px">
              <template slot-scope="scope">
                <template >
                  <el-form-item :prop="`tableData.${scope.$index}.quantity`"
                                :rules="formRules.quantity">
                    <template v-if="form.warehouseServiceName === 'JD'">
                      <span>{{scope.row.totalQuantity}}</span>
                    </template>
                    <div v-else>
                      <span v-if="!scope.row.isEdit">{{scope.row.quantity}}</span>
                      <el-input v-else v-model.trim="scope.row.quantity" @change="changeEnsalequantity(scope.row, scope.$index)" min-width="150px"></el-input>
                    </div>
                  </el-form-item>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="保价(元)" min-width="200px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.insuredPrice`"
                              :rules="formRules.insuredPrice">
                  <span v-if="!scope.row.isEdit">{{scope.row.insuredPrice}}</span>
                  <el-input v-else v-model.trim="scope.row.insuredPrice"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="收货人" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.omsOrderDelivery.contactName`"
                              :rules="formRules.contactName">
                  <span v-if="!scope.row.isEdit">{{scope.row.omsOrderDelivery.contactName}}</span>
                  <el-input v-else v-model.trim="scope.row.omsOrderDelivery.contactName"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="联系方式" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.omsOrderDelivery.contactPhone`"
                              :rules="formRules.contactPhone">
                  <span v-if="!scope.row.isEdit">{{scope.row.omsOrderDelivery.contactPhone}}</span>
                  <el-input v-else v-model.trim="scope.row.omsOrderDelivery.contactPhone"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="省/市/区" width="200px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.provinceCityAera`" :rules="formRules.provinceCityAera">
                  <span v-if="!scope.row.isEdit">{{scope.row.provinceCityAera}}</span>
                  <address-component v-else ref="addressComponent" :clearable="false" :adressArr.sync='scope.row.adress'
                                    :isRequest="false" :allAdress="allAdress"
                                    @hand-adress-validate="handAdressValidate"></address-component>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="详细地址" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.omsOrderDelivery.detail`"
                              :rules="formRules.detail">
                  <span v-if="!scope.row.isEdit">{{scope.row.omsOrderDelivery.detail}}</span>
                  <el-input v-else v-model.trim="scope.row.omsOrderDelivery.detail"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="`tableData.${scope.$index}.memberMemo`"
                              :rules="formRules.memberMemo">
                  <span v-if="!scope.row.isEdit">{{scope.row.memberMemo}}</span>
                  <el-input v-else v-model.trim="scope.row.memberMemo"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" fixed="right">
              <template slot-scope="scope">
                <el-form-item>
                  <el-button type="primary" class="editBtn" :disabled="cancelBtnIsDisabled" v-if="!scope.row.isEdit"
                            @click="editItem(scope.row,scope.$index)" size="mini">编辑</el-button>
                  <el-button v-else type="warning" class="editBtn" :disabled="cancelBtnIsDisabled"
                            @click="saveItem(scope.row,scope.$index)" size="mini">保存</el-button>
                  <el-button type="danger" :disabled="cancelBtnIsDisabled" @click="deleteItem(scope.row,scope.$index)" size="mini">删除
                  </el-button>
                </el-form-item>
              </template>
            </el-table-column>
          </template>
      </list-condition-template>
      <el-form-item label="附件:" label-width="55px" class="file-style" prop="annexBizId">
        <upload-file :limitNumber='10' :uploadPath="'order'"
                     accept=".xls,.xlsx,.doc,.docx,.pdf,.jpg,.jpeg,.png"
                     @handle-success="handleSuccess1" @handle-remove="handleRemove1"
                     :fileList="batchFileList" :reload="reload" :customTips="'附件上传数量不得超过10个'">
          <template>仅支持.xls,.xlsx,.doc,.docx,.pdf,.jpg,.jpeg,.png的附件</template>
        </upload-file>
      </el-form-item>
    </el-form>
    <div class="buttonPosition">
      <el-button type="primary" size="mini" @click="submit" :loading="btnLOading">保存</el-button>
      <el-button size="mini" :disabled="cancelBtnIsDisabled" @click="cancel">取消</el-button>
    </div>
    <el-dialog :visible.sync="importDialogVisible" title="导入" :close-on-click-modal="false"
               :modal-append-to-body="false" width="550px">
      <el-form size="mini">
        <el-progress v-if="loadProgress" :percentage="loadProgress"></el-progress>
        <el-upload class="upload-demo" action="api" ref="upload" :limit="1" :accept="'.xlsx, .xls'"
                   :http-request="handleRequrst" :auto-upload="false" :file-list="fileList"
                   :on-change="handleChange" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传一个文件,且文件格式只支持.xlsx, .xls文件</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer buttonPosition">
        <el-button type="primary" size="mini" :loading="loading" @click="submitImport">确定
        </el-button>
        <el-button size="mini" @click="importDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import orderMgtApi from '@/api/orderMgt'
import { downloadFile } from '@/utils/downloadFile'
import addressComponent from '@/components/formTemplate/addressComponent.vue'
import orderSourceArr from '@/utils/constant/orderSourceArr'
import { limitNumType, inputNumberValid, validateMobileLandlin } from '@/utils/validator'
import uploadFile from '@/components/uploadFile/uploadFile.vue'
import uploadFileApi from '@/api/uploadFile'
import channelInventoryApi from '@/api/stockManagement/channelInventory'
import tipTableDataComponent from './tipTableDataComponent.vue'
 
import { create } from '../mountComponent'
let mouseUp = null;
let mouseDown = null;
const hideDropdown = function(dom) {
  if (!dom) {
    dom = document.querySelector('.batchImportCreateOrder');
  }
  // 创建鼠标事件
  if (!mouseUp || !mouseDown) {
    mouseUp = new MouseEvent('mouseup', {
      view: window,
      bubbles: true,
      cancelable: true
    });
    mouseDown = new MouseEvent('mousedown', {
      view: window,
      bubbles: true,
      cancelable: true
    });
  }
  // 顺序触发mouseDown、mouseUp就能触发element隐藏下拉框事件
  dom.dispatchEvent(mouseDown);
  dom.dispatchEvent(mouseUp);
}
// 清除鼠标事件
const delEvents = function() {
  mouseUp = null;
  mouseDown = null;
}
export default {
  components: { addressComponent, uploadFile },
  props: ['adressArray', 'shopNameArr'],
  data() {
    return {
      // 处理移动滚动条下拉框隐藏
      popperClass: null,
      // 物流服务商下拉列表数据源
      warehouseData: [],
      // 发货仓库下拉列表数据源
      deliveryWarehouseData: [],
      allAdress: [],
      orderSourceArr,
      // giftTypeArr,
      importDialogVisible: false,
      fileList: [],
      batchFileList: [],
      loading: false,
      percentage: 0, // 进度条数值
      isLoading: false, // 是否展示进度条遮罩
      form: {
        warehouseServiceName: null, // 物流服务商
        deliveryWarehouse: null, // 发货仓库
        tableData: [],
        annexBizId: null // 附件id
      },
      btnLOading: false,
      tableMaxHeight: 80,
      formRules: {
        warehouseServiceName: [{ required: true, message: '请选择物流服务商' }],
        deliveryWarehouse: [{ required: true, message: '请选择发货仓库' }],
        orderSource: [{ required: true, message: '请选择所属渠道' }],
        contractId: [{ required: true, message: '请选择门店名称' }],
        spuNum: [
          { required: true, message: '请输入赠品编码', trigger: 'change' },
          { max: 32, message: '赠品编码最多只能输入 32 个字' },
          { validator: limitNumType }
        ],
        quantity: [
          { required: true, message: '请输入赠品数量' },
          { validator: inputNumberValid },
          {
            validator: (rule, value, callback) => {
              const arr = rule.fullField.split('.')
              const row = this.form.tableData[Number(arr[1])]
              if (value > row.stock || row.totalQuantity > row.stock) {
                callback(new Error('总数量不得大于可用库存'))
              } else {
                callback()
              }
            }
          }
        ],
        spuName: [{ required: true, message: '请输入赠品名称', trigger: 'change' },
          { max: 128, message: '赠品名称最多只能输入 128 个字' }
        ],
        skuId: [{ required: true, message: '请选择赠品规格' }],
        insuredPrice: [{
          validator: (rule, value, callback) => {
            const reg = /^(?!0+$)(?!0*\.0*$)\d{1,9}(\.\d{1,2})?$/ // 最多输入两位小数
            const val = Number(value)
            if (typeof (val) === 'number' && isNaN(val)) {
              callback(new Error('保价金额只能输入数字'))
            } else if (val && val < 0) {
              callback(new Error('保价金额不得输入负数'))
            } else if (val && val > 999999999) {
              callback(new Error('保价金额最高仅支持输入999999999元'))
            } if (val && !reg.test(value)) {
              callback(new Error('保价金额最多输入两位小数'))
            } else {
              callback()
            }
          }
        }],
        contactName: [
          { required: true, message: '请输入收货人姓名', trigger: 'change' },
          { message: '收货人姓名最多只能输入 32 个字', max: 32, trigger: 'change' }
        ],
        contactPhone: [{ validator: validateMobileLandlin, required: true, trigger: 'change' }],
        provinceCityAera: [{ required: true, message: '请选择省市区' }],
        detail: [
          { required: true, message: '请输入详细地址', trigger: 'change' },
          { max: 120, message: '详细地址最多只能输入 120 个字', trigger: 'change' }
        ],
        memberMemo: [{ max: 300, message: '备注最多只能输入 300 个字', trigger: 'change' }]
      },
      rowItem: null,
      reload: false, // 不重新加载
      total: 0,
      loadProgress: 0,
      delayedTimer: null, // 定时ID
      errListloading: false, // 导出错误数据loading
      notificationParams: { // 保存进度条参数
        notificationDuration: 0,
        percentage: 0
      },
      cancelBtnIsDisabled: false, // 取消按钮是否禁用
      tableTotal: 0, // 导入数据总数
    }
  },
  mounted() {
    this.setTableHeight()// 设置表格高度
    // 获取物流服务商
    this.getLogisticsProvidersData();
    window.addEventListener('resize', () => {
      // 监听浏览器窗口
      this.setTableHeight()// 设置表格高度
    }, false)
    // 监听当前组件的滚动事件
    const tableBox = this.$refs.tableBox.$refs.table.bodyWrapper;
    tableBox.addEventListener('scroll', () => {
      // select组件层级太高,滚动隐藏
      if (tableBox.scrollLeft > 0) {
        setTimeout(() => {
          hideDropdown();
        }, 50)
      }
    }, false)
  },
  // 在组件生命周期结束时销毁
  beforeDestroy() {
    delEvents();
    window.removeEventListener('click', () => { }, true)
  },
  methods: {
    // 获取导入表格数据
    async getImportCreateOrder(pageInfo = { pageNum: 1, pageSize: 10 }) {
      const res = await orderMgtApi.getImportCreateOrder({ excelId: this.form.excelId, ...pageInfo })
      if (res.data) {
        this.form.tableData = []
        res.data.records.forEach(item => {
          item.isEdit = false
          item.skuInfoSelectList = item.skuInfoSelectList || []
          item.adress = []
          item.skuId = item.currSkuId
          item.spuProps = item.currSkuSpecs
          item.totalQuantity = this.getTotalQuantity(item);
          const address = item.omsOrderDelivery
          item.provinceCityAera = address.province ? address.province + '/' + address.city + '/' + address.aera : null
          this.changeSkuId(item)
          // 获取规格编码、发货数量选中数据
          this.getCheckSpecificationCodeOrCountData(item);
          this.form.tableData.push(item)
        })
        this.total = res.data.total
        this.tableTotal = res.data.total
      }
    },
    async saveItem(item, index) {
      // 表格单行数据验证
      const rowIndex = `tableData.${index}`;
      const arr = [
        `${rowIndex}.orderSource`,
        `${rowIndex}.contractId`,
        `${rowIndex}.spuName`,
        `${rowIndex}.specificationCode`,
        `${rowIndex}.quantity`,
        `${rowIndex}.insuredPrice`,
        `${rowIndex}.omsOrderDelivery.contactName`,
        `${rowIndex}.omsOrderDelivery.contactPhone`,
        `${rowIndex}.provinceCityAera`,
        `${rowIndex}.omsOrderDelivery.detail`
      ]
      if (this.form.warehouseServiceName === 'JD') {
        const shipmentsCountListLength = item.shipmentsCountList.length
        for (let i = 0; i <= shipmentsCountListLength - 1; i++) {
          arr.push(`${rowIndex}.shipmentsCountList.${i}.shipmentsCount`)
        }
      }
      let tag = true
      this.$refs.form.validateField(arr, (err) => {
        if (err) {
          this.$message.info('请完善表单');
          tag = false;
        }
        return tag;
      })
      if (tag) {
        item.quantity = this.form.warehouseServiceName === 'JD' ? item.totalQuantity : item.quantity
        const res = await orderMgtApi.editImportCreateOrderItem(item)
        if (res) {
          item.isEdit = false;
          this.$message.success('保存成功');
        }
      }
    },
    // 判断表格是否存在未保存的数据
    judgeTableIsNotSave() {
      for (const i of this.form.tableData) {
        if (i.isEdit) {
          this.$message.warning('修改数据未保存');
          return false;
        }
      }
      return true;
    },
    /**
       * '分页信息改变时查询列表
       */
    handlePageInfoChange(pageInfo) {
      if (this.judgeTableIsNotSave()) {
        this.$refs.form.clearValidate()
        this.getImportCreateOrder(pageInfo)
      }
    },
    /**
     * 当赠品数量改变时判断与限制数量的大小
     */
    changeEnsalequantity(row, index) {
      if (row.quantity) {
        this.$refs.form.validateField(`tableData.${index}.quantity`)
      }
    },
    // 当改变渠道时,获取对应库存
    async changeOrderSource(val, row, index) {
      row.orderSourceName = this.orderSourceArr.find(item => item.id === val).name
      try {
        const pageParams = {
          current: 1,
          size: 10,
          sortProperties: 'update_time',
          sortDirection: 'DESC',
          spuNum: row.spuNum,
          channel: val
        }
        const res = await channelInventoryApi.getList({ ...this.listQuery, ...pageParams })
        if (res.code === '200') {
          if (res.data.records.length === 0) {
            row.orderSource = null
            this.$message({
              message: '所属渠道下未查到该商品,请重新选择',
              type: 'info'
            })
            return;
          }
          row.stock = res.data.records[0].stock
          this.$refs.form.validateField(`tableData.${index}.quantity`)
        }
      } catch (error) {
      }
    },
    /**
     *验证规格编码
    */
    specificationCodeVail(rule, value, callback) {
      if (rule.warehouseServiceName === 'JD') {
        const specificationCodeList = rule.row.specificationCodeList;
        if (value && value.length) {
          let flag = false;
          for (let i = 0; i < value.length; i++) {
            const obj = specificationCodeList && specificationCodeList.length ? specificationCodeList.find((item) => item.prodSkuNo === value[i]) : null
            if (!obj) {
              flag = true
            }
          }
          // 未找到匹配的规格编码
          if (flag) {
            callback(new Error('请选择规格编码'))
          } else {
            callback()
          }
        } else {
          callback(new Error('请选择规格编码'))
        }
      } else {
        callback()
      }
    },
    /**
     *验证发货数量
    */
    shipmentsCountVail(rule, value, callback) {
      if (rule.warehouseServiceName === 'JD') {
        if (!value) {
          callback(new Error('请输入发货数量'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    /**
     * 获取物流服务商
     */
    async getLogisticsProvidersData() {
      const res = await orderMgtApi.getWarehouseTree({})
      if (res.code === '200' && res.data.length) {
        this.warehouseData = res.data;
      }
    },
    /**
     * 物流服务商值改变获取发货仓库下拉列表数据源
     */
    changeWarehouseVal(val) {
      let arr = [];
      this.$refs.deliveryWarehouse.resetField();
      const obj = this.warehouseData.find((item) => item.warehouseService === val)
      if (obj && Object.keys(obj).length) {
        arr = obj.treeList;
      }
      this.deliveryWarehouseData = arr;
      this.$nextTick(() => {
        this.allAdress = JSON.parse(JSON.stringify(this.adressArray))
      })
      if (val === 'JD') {
        this.form.tableData.forEach(item => {
          if (item.isEdit) {
            this.getSpecificationCodeList(item);
          }
        })
      }
    },
    /**
    * 附件上传成功
    */
    handleSuccess1(arr, businessId) {
      this.reload = false;
      this.batchFileList = arr
      this.form.annexBizId = businessId
    },
    /**
     * 删除附件
     */
    handleRemove1(file) {
      uploadFileApi.removeFile({ key: file.id }).then(res => {
        const index = this.batchFileList.findIndex(item => item.id === file.id)
        if (index !== -1) {
          this.batchFileList.splice(index, 1)
        }
        if (!this.batchFileList.length) {
          this.form.annexBizId = null
        }
      })
    },
    handAdressValidate(val) {
      const cascaderObj = this.getCascaderObj(
        val,
        this.adressArray
      )
      if (val === '810000' || val === '820000') {
        this.rowItem.omsOrderDelivery.provinceId = val[0]
        this.rowItem.omsOrderDelivery.cityId = val[0]
        this.rowItem.omsOrderDelivery.aeraId = val[1]
        this.rowItem.omsOrderDelivery.province = cascaderObj[0]
        this.rowItem.omsOrderDelivery.city = cascaderObj[0]
        this.rowItem.omsOrderDelivery.aera = cascaderObj[1]
      } else {
        this.rowItem.omsOrderDelivery.provinceId = val[0]
        this.rowItem.omsOrderDelivery.cityId = val[1]
        this.rowItem.omsOrderDelivery.aeraId = val[2]
        this.rowItem.omsOrderDelivery.province = cascaderObj[0]
        this.rowItem.omsOrderDelivery.city = cascaderObj[1]
        this.rowItem.omsOrderDelivery.aera = cascaderObj[2]
      }
      this.rowItem.provinceCityAera = cascaderObj.join('')
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      })
    },
    /**
 * 设置除了表格外的点击事件
 */
    setExceptTableDomClick() {
      // 模拟外部点击
      document.addEventListener('click', (e) => {
        this.debounce(this.handle(e), 1000)
      })
    },
    debounce(fn, delay) {
      var timer = null
      return function() {
        if (timer !== null) {
          clearTimeout(timer)
        }
        timer = setTimeout(fn, delay)
      }
    },
    handle(e) {
      if (e.target.innerText !== '编辑') {
        this.form.tableData.forEach(item => {
          this.$set(item, 'isEdit', false)
        })
      }
    },
    /**
     * 编辑表格item
     */
    editItem(row, index) {
      if (this.form?.warehouseServiceName === 'JD') {
        this.getSpecificationCodeList(row);
      }
      this.$set(row, 'isEdit', true)
      this.rowItem = row
      this.$nextTick(() => {
        this.allAdress = JSON.parse(JSON.stringify(this.adressArray))
      })
    },
    // 当文件改变时获取选中的文件
    handleChange(file, fileList) {
      const acceptFile = '.xlsx, .xls'
      var nameType = file.name.substring(file.name.lastIndexOf('.') + 1)
      var fileType = acceptFile.indexOf(nameType) !== -1
      if (!fileType) {
        this.$message.error(`上传失败!仅支持${acceptFile}格式,请重新上传`)
        this.fileList = []
        return false
      }
      return true
    },
    /**
     * 选择规格时触发,获取规格名称
     */
    changeSkuId(row) {
      row.skuInfoSelectList.forEach(item => {
        if (item.skuId === row.skuId) {
          row.spuProps = item.skuProps.map(item => item.propValueName).join('/')
          row.shopId = item.shopId
        }
      })
    },
    /**
     * 设置表格高度
     */
    setTableHeight() {
      const mainContainer = document.getElementById('main-container')
      this.$nextTick(() => {
        this.tableMaxHeight = mainContainer.offsetHeight - 180
      })
    },
    /**
     * 获取级联label
     */
    getCascaderObj(val, opt) {
      return val.map(function(value, index, array) {
        for (var itm of opt) {
          if (itm.value === value) {
            opt = itm.children
            return itm.label
          }
        }
        return null
      })
    },
    /**
  * 物流商品信息(物流对应商品规格单位数量等)
  */
    getLogisticProds(row) {
      const arr = [];
      if (row.specificationCode && row.specificationCode.length) {
        row.specificationCode.forEach((v1, index) => {
          const curObj = row?.specificationCodeList?.find((v2) => v2.prodSkuNo === v1);
          if (curObj && Object.keys(curObj).length) {
            arr.push({
              skuId: curObj.prodSkuNo, // 物流商品规格
              skuUnit: curObj.skuUnit, // 物流商品包装数量
              unit: curObj.unitOfMeasurement, // 物流商品单位
              prodName: curObj.prodName, // 物流商品名称
              quantity: row.shipmentsCountList[index].shipmentsCount, // 物流商品数量
            })
          }
        })
      }
      return arr;
    },
    // 获取保存的进度
    async getSaveOrderProgress() {
      const res = await orderMgtApi.getSaveOrderProgress({ excelId: this.form.excelId })
      if (!this.$refs.progressbar) return;
      this.$refs.progressbar.percentage = res.data;
      this.notificationParams.percentage = res.data;
      if (res.data === 100) {
        this.$notify.closeAll();
        this.cancelBtnIsDisabled = false;
        this.btnLOading = false;
        this.notificationParams.percentage = 0
        clearTimeout(this.delayedTimer)
        this.getManualOrderCreateErrorList();
      }
    },
    // 获取手工单错误列表
    async getManualOrderCreateErrorList() {
      const res = await orderMgtApi.manualOrderCreateErrorList({ excelId: this.form.excelId })
      if (res.data?.length) {
        this.$refs.form.clearValidate()
        this.$message({
          message: `成功保存${this.tableTotal - res.data.length}条,失败${res.data.length}条`,
          type: 'error',
        })
        this.total = 0
        this.form.tableData = []
        const params = {
          tipTableData: res.data,
          tableTotal: this.tableTotal,
          excelId: this.form.excelId,
          visible: true
        }
        // 创建提示弹窗
        create(tipTableDataComponent, params);
      } else {
        this.$message.success('全部上传成功')
        this.$router.push({ name: 'orderMgtList' })
        this.total = 0
        this.form.tableData = []
        this.batchFileList = []
        this.form.tableData = []
        this.form.excelId = null
        this.form.annexBizId = null;
        this.reload = true;
        this.$refs.form.clearValidate()
      }
      clearTimeout(this.delayedTimer)
    },
    /**
 * 批量保存
 */
    submit() {
      if (!this.form.tableData.length) {
        this.$message.info('请导入数据');
        return;
      }
      if (!this.judgeTableIsNotSave()) return;
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          try {
            this.$confirm('请仔细核对上传文件内容?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async() => {
              this.btnLOading = true
              this.cancelBtnIsDisabled = true;
              const params = {
                logisticSupplier: this.form.warehouseServiceName,
                warehouse: this.form.deliveryWarehouse,
                excelId: this.form.excelId,
                annexBizId: this.form.annexBizId
              }
              const res = await orderMgtApi.batchCreateAnalysisOrder(params)
              if (res.code === '0') {
                this.$message({
                  message: '上传中。。。',
                  type: 'info'
                })
                const h = this.$createElement
                const progressbar = h('el-progress', {
                  ref: 'progressbar',
                  props: { percentage: this.notificationParams.percentage },
                });
 
                this.$notify({
                  title: '上传进度',
                  customClass: 'notify-success',
                  message: progressbar,
                  duration: 0,
                  showClose: false
                });
                this.setTimeToInterval(this.getSaveOrderProgress, 1000)
              } else {
                this.btnLOading = false
              }
            }).catch(() => {
              this.btnLOading = false;
              this.cancelBtnIsDisabled = false;
            });
          } catch (error) {
            this.btnLOading = false;
            this.cancelBtnIsDisabled = false;
          }
        } else {
          this.$message({
            message: '请完善表单',
            type: 'info'
          })
        }
      })
    },
    /**
     * 删除选中导入数据
     */
    async deleteItem(row, index) {
      const res = await orderMgtApi.deleteImportCreateOrderItem({ tmpId: row.tmpId })
      if (res.code === '0') {
        this.$refs.form.clearValidate()
        this.getImportCreateOrder()
      }
    },
    /**
     * 取消导入
     */
    cancel() {
      this.form.tableData = []
      this.total = 0
      this.form.excelId = null
      this.$refs.warehouseServiceName.resetField();
      this.$refs.deliveryWarehouse.resetField();
      this.form.annexBizId = null;
      this.batchFileList = [];
      this.reload = true;
    },
    // 导入
    importOrder() {
      this.importDialogVisible = true
    },
    // 导入三方系统会员信息
    submitImport() {
      this.$refs.upload.submit()
    },
    // 手动上传文件
    async handleRequrst(param) {
      this.loading = true
      try {
        const formData = new FormData()
        formData.append('file', param.file)
        const res = await orderMgtApi.importData(formData)
        if (res.code === '0' && res.data) {
          this.form.excelId = res.data
          this.setTimeToInterval(this.getImportProgress, 1000)
        } else {
          this.loading = false
          this.fileList = []
          this.loadProgress = 0
        }
      } catch (error) {
        this.fileList = []
        this.loading = false
        this.loadProgress = 0
      }
    },
    // 轮询
    setTimeToInterval(fn, delay) {
      this.delayedTimer = setTimeout(() => {
        fn();
        this.setTimeToInterval(fn, delay)
      }, delay)
    },
    // 获取导入的进度
    async getImportProgress() {
      const res = await orderMgtApi.getImportProgress({ excelId: this.form.excelId })
      this.loadProgress = res.data
      if (this.loadProgress === 100) {
        clearTimeout(this.delayedTimer)
        setTimeout(() => {
          this.loadProgress = 0
          this.loading = false
          this.fileList = []
          this.form.tableData = []
          this.importDialogVisible = false
          this.$refs.form.clearValidate()
          this.getImportCreateOrder()
        }, 1000)
      }
    },
    /**
     * 根据商品主编码获取所有的规格编码集合
     */
    getSpecificationCodeList(row) {
      orderMgtApi.getSpecificationCodeData({ prodNum: row.spuNum }).then((res) => {
        let arr = [];
        if (res.code === '200' && res.data.length) {
          arr = [...res.data];
        }
        this.$set(row, 'specificationCodeList', arr)
      }).catch(() => {
        this.$set(row, 'specificationCodeList', [])
      })
    },
    /**
     * 根据【单位计数+发货数量】进行自动计算,赠品总数量不可编辑
     */
    getTotalQuantity(obj) {
      let count = 0;
      if (obj.omsOrderLogisticProds && obj.omsOrderLogisticProds.length) {
        obj.omsOrderLogisticProds.forEach((item) => {
          if (item.skuUnit && item.quantity) {
            count += item.skuUnit * item.quantity;
          }
        })
      }
      return count || null;
    },
    /**
     * 获取EXCEL表中输入的规格编码以及发货数量数据
     */
    getCheckSpecificationCodeOrCountData(row) {
      const [specificationCode, shipmentsCountList] = [[], []];
      if (row.omsOrderLogisticProds && row.omsOrderLogisticProds.length) {
        row.omsOrderLogisticProds.forEach((item) => {
          specificationCode.push(item.skuId);
          shipmentsCountList.push({
            skuId: item.skuId,
            shipmentsCount: item.quantity
          });
        })
      }
      row.specificationCode = [...specificationCode];
      // 临时存储上一次选中的数据
      row.oldSpecificationCode = [...specificationCode];
      // 发货数量
      row.shipmentsCountList = [...shipmentsCountList]
    },
    /**
     * 规格编码选中值改变时触发
     */
    changeSpecificationCodeVal(event, row, index) {
      // 当前操作项
      const arr = this.getArrDifference(event, row.oldSpecificationCode);
      // 选中
      if (event.length > row.oldSpecificationCode.length) {
        this.form.tableData[index].shipmentsCountList.push({
          skuId: arr[0],
          shipmentsCount: 1
        })
      } else {
        // 移除
        const curIndnx = this.getArrayIndex(row.oldSpecificationCode, arr[0])
        if (curIndnx !== -1) {
          this.form.tableData[index].shipmentsCountList.splice(curIndnx, 1)
        }
      }
      row.totalQuantity = this.getQuantityTotal(event, row);
      row.quantity = row.totalQuantity
      this.$set(row, 'oldSpecificationCode', event);
      this.$refs.form.validateField(`tableData.${index}.quantity`);
    },
    // 发货数量改变时计算赠品总数量
    changeShipmentsCountVal(specificationCode, row, index) {
      row.totalQuantity = this.getQuantityTotal(specificationCode, row);
      row.quantity = row.totalQuantity
      this.$refs.form.validateField(`tableData.${index}.quantity`)
    },
    // 规格编码改变时计算赠品总数量
    getQuantityTotal(event, row) {
      let count = 0;
      if (event && event.length) {
        for (let i = 0; i < event.length; i++) {
          const curObj = row.specificationCodeList.find((v2) => v2.prodSkuNo === event[i]);
          if (curObj) {
            count += curObj.skuUnit * row.shipmentsCountList[i].shipmentsCount
          }
        }
      }
      return count || null;
    },
    // 获取指定值在数组中的下标
    getArrayIndex(arr, val) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
          return i;
        }
      }
      return -1;
    },
    // 取出两个数组中不同的元素
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function(v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    },
    // 下载模板
    async downTemplate() {
      const config = {
        onUploadProgress: (ProgressEvent) => {
          const progressPercent = Math.round(
            ((ProgressEvent.loaded / ProgressEvent.total) * 100) | 0
          )
          this.percentage = progressPercent === 100 ? 99 : progressPercent
          this.isLoading = true
        },
        url: 'awl-order-service/operation/order/manage/downDemoFile',
        data: null,
        fileName: '手工建单批量导入模板',
        Method: 'get',
        type: '.xlsx'
      }
      const res = await downloadFile(config)
      if (res) {
        this.percentage = 100
        this.isLoading = false
      } else {
        this.percentage = 100
        this.isLoading = false
      }
    },
    /**
     * 导出
     */
    async exportData() {
      this.errListloading = true
      const config = {
        url: `awl-order-service/order/v2/export/manualOrderCreateErrorMsg?excelId=${this.form.excelId}`,
        data: { ...this.exportQuery, ...{ confirmed: true } },
        fileName: '手工建单失败数据',
        type: '.xlsx'
      }
      const res = await downloadFile(config)
      if (res) {
        this.errListloading = false
      } else {
        this.errListloading = false
      }
    }
  }
}
</script>
 
<style lang="scss">
.batchImportCreateOrder {
  .batchImportDiv {
    margin-bottom: 15px;
  }
  .el-form {
    margin: 20px 0;
  }
  .popperClass {
    display: none !important;
  }
}
.file-style {
  margin-top: 20px;
}
.con-box {
  @media (min-width: 1300px) {
    .inside-box-left {
      width: 55%;
    }
    .inside-box-right {
      width: 45%;
      text-align: right;
    }
  }
  .box1,
  .box2 {
    width: 333px;
  }
  .inside-box-left,
  .inside-box-right,
  .box1,
  .box2 {
    display: inline-block;
  }
}
.notify-success .el-notification__group{
  width: 100% !important;
  .el-progress .el-progress-bar{
    width: 95% !important;
  }
}
</style>
<style lang="scss" scoped>
/deep/.el-progress .el-progress-bar{
  width: 90% !important;
  margin-bottom: 10px;
}
</style>