333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
import { default as BaseController } from "../baseController";
import { PurchaseOrder } from "../../entity/inbound/purchase/purchaseOrder";
import { Post } from "egg-shell-decorators";
import * as XLSX from "xlsx";
import * as path from "path";
import { isNumber } from "util";
import moment = require("moment");
import { BaseProductInfo } from "../../entity/basicInfo/base/baseProductInfo";
import { PurchaseOrderList } from "../../entity/inbound/purchase/purchaseOrderList";
import { PurchaseOrderStatusHistory } from "../../entity/inbound/purchase/purchaseOrderStatusHistory";
import { In, Not } from "typeorm";
import * as mssql from "mssql";
import { BasePosition } from "../../entity/basicInfo/base/basePosition";
import { BaseConsignor } from "../../entity/basicInfo/consignor/baseConsignor";
import { BaseStorage } from "../../entity/basicInfo/base/baseStorage";
import { BasePlateType } from "../../entity/basicInfo/base/basePlateType";
import { BasePlate } from "../../entity/basicInfo/base/basePlate";
/**
 * 收货 - 预到货单
 */
export default class OrderController extends BaseController {
  //#region 修改返修状态
  @Post()
  public async updateSatus() {
    let { ctx } = this;
    let body = ctx.request.body;
    let orderCode = body.orderCode;
    let statusText = "返修合格";
    let userInfo = await ctx.helper.userInfo();
    try {
      await this.dbWrite.update(
        PurchaseOrder,
        {
          orderCode: orderCode,
          userProduct_Id: userInfo.userProduct_Id
        },
        {
          statusText: statusText
        }
      );
 
      this.info.result = true;
      this.info.msg = "修改成功";
    } catch (error) {
      this.info.result = false;
      this.info.msg = error.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 添加单据
  @Post()
  public async addNewOrder() {
    let { ctx } = this;
    try {
      let body = ctx.request.body;
      let userInfo = await ctx.helper.userInfo();
      var taskForm = body.taskForm;
      if (!taskForm.product_Id) {
        this.info.result = false;
        this.info.msg = "请选择物料号";
        ctx.body = this.info;
        return;
      }
      let consignorInfo = await this.dbRead.findOne(BaseConsignor, { userProduct_Id: userInfo.userProduct_Id });
      // 根据器具编号id 获取器具
      let getplateCode = await this.dbRead.findOne(BasePlate, { plate_Id: taskForm.plate_Id });
      // 获取物料信息
      let productInfo = await this.dbRead.findOne(BaseProductInfo, {
        product_Id: taskForm.product_Id
      });
      // 获取器具种类
      let plateTypeInfo = await this.dbRead.findOne(BasePlateType, {
        plateType_Id: productInfo.plateType_Id
      });
 
      var orderInfo = new PurchaseOrder();
      orderInfo.orderCode = await ctx.service.common.getCodeRegular(1803);
      orderInfo.consignorName = consignorInfo.consignorName;
      orderInfo.consignor_Id = consignorInfo.consignor_Id;
      orderInfo.consignorCode = consignorInfo.consignorCode;
      orderInfo.storageName = plateTypeInfo.storageName;
      orderInfo.storage_Id = plateTypeInfo.storage_Id;
      orderInfo.repairType = taskForm.repairType;
      orderInfo.statusText = "焊装待返修";
      orderInfo.orderType = "返修单";
      orderInfo.plateCode = getplateCode.plateCode;
      orderInfo.plate_Id = taskForm.plate_Id;
      orderInfo.totalQuantity = taskForm.totalQuantity;
      orderInfo.statusID = 1;
      // orderInfo.sortingStatus = 1;
      // orderInfo.orderType = taskForm.orderType;
      await this.setAccountInfo(orderInfo);
      await this.dbWrite.save(orderInfo);
 
      var orderListInfo = new PurchaseOrderList();
      orderListInfo.order_Id = orderInfo.order_Id;
      orderListInfo.productName = productInfo.productName;
      orderListInfo.productCode = productInfo.productCode;
      orderListInfo.product_Id = productInfo.product_Id;
      orderListInfo.productModel = productInfo.productModel;
      orderListInfo.quantity = taskForm.totalQuantity;
      orderListInfo.images = productInfo.images;
      // orderListInfo.sortingStatus = 1;
      await this.dbWrite.save(orderListInfo);
      this.info.result = true;
      this.info.msg = "添加成功!";
      this.info.data = orderInfo;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 新增到货单
  /**
   * 新增出库单
   */
  @Post()
  public async add() {
    let { ctx } = this;
    let body = ctx.body;
    let userInfo = await this.userInfo;
    let db = this.app.mongodb;
    try {
      // 记录数据到mongodb日志中
      let collection = db.collection("apiPurchaseOrder");
      let mongoData = JSON.parse(JSON.stringify(body));
      mongoData.createDate = new Date();
      mongoData.userProduct_Id = userInfo.userProduct_Id;
      let re = await collection.insert(mongoData);
      ctx.logger.info("apiSaleOrder将数据保存至MongoDB after:" + JSON.stringify(re));
    } catch {}
 
    if (!userInfo && !userInfo.userProduct_Id) {
      this.info.result = false;
      this.info.msg = "数据不存在";
      ctx.body = this.info;
      return;
    }
    let userProduct_Id = userInfo.userProduct_Id;
 
    if (!body.consignorCode) {
      this.info.result = false;
      this.info.msg = "货主编号不能为空";
      ctx.body = this.info;
      return;
    }
 
    if (!body.consignorName) {
      this.info.result = false;
      this.info.msg = "货主名称不能为空";
      ctx.body = this.info;
      return;
    }
 
    if (!body.trackingNumber) {
      this.info.result = false;
      this.info.msg = "ERP订单号不能为空";
      ctx.body = this.info;
      return;
    }
 
    if (!Array.isArray(body.details) || !body.details.length) {
      this.info.result = false;
      this.info.msg = "入库单明细不能为空";
      ctx.body = this.info;
      return;
    }
 
    try {
      // 验证单号是否已推送
      let storeOrderInfo = await this.dbRead.findOne(PurchaseOrder, {
        trackingNumber: body.trackingNumber,
        userProduct_Id: userProduct_Id
      });
      if (storeOrderInfo) {
        this.info.result = true;
        this.info.statusCode = 660;
        this.info.msg = body.trackingNumber + "已存在,不允许重复推送";
        this.info.data = {
          order_Id: storeOrderInfo.order_Id,
          orderCode: storeOrderInfo.orderCode
        };
        ctx.body = this.info;
        return;
      }
 
      // 验证货主
      let consignorInfo = await this.dbRead.findOne(BaseConsignor, {
        consignorName: body.consignorName,
        userProduct_Id: userProduct_Id
      });
      if (!consignorInfo) {
        this.info.result = false;
        this.info.msg = "货主不存在";
        ctx.body = this.info;
        return;
      }
      this.body.consignor_Id = consignorInfo.consignor_Id;
      this.body.consignorCode = consignorInfo.consignorCode;
 
      // 验证仓库
      let storageInfo = await this.dbRead.findOne(BaseStorage, {
        storageName: body.storageName,
        userProduct_Id: userProduct_Id
      });
      if (!storageInfo) {
        this.info.result = false;
        this.info.msg = "仓库不存在";
        ctx.body = this.info;
        return;
      }
      this.body.storage_Id = storageInfo.storage_Id;
      this.body.applyDate = new Date();
 
      for (let detailInfo of this.body.details) {
        let prodInfo = await this.dbRead.findOne(BaseProductInfo, {
          where: {
            productCode: detailInfo.productCode,
            userProduct_Id: userProduct_Id
          }
        });
        if (!prodInfo) {
          this.info.result = false;
          this.info.msg = detailInfo.productCode + "物料编号不存在";
          ctx.body = this.info;
          return;
        }
        detailInfo.product_Id = prodInfo.product_Id;
        detailInfo.productModel = prodInfo.productModel;
        detailInfo.productName = prodInfo.productName;
        detailInfo.productSpec = prodInfo.productSpec;
        if (!isNumber(detailInfo.quantity)) {
          this.info.result = false;
          this.info.msg = detailInfo.productModel + "数量必须为数字";
          ctx.body = this.info;
          return;
        }
        if (!detailInfo.quantity || detailInfo.quantity <= 0) {
          this.info.result = false;
          this.info.msg = detailInfo.productModel + "数量必须大于0";
          ctx.body = this.info;
          return;
        }
      }
 
      // 主表求和字段计算
      let total: any = this.body.details.reduce(
        (totalItem: any, currItem) => {
          totalItem.totalQuantity += currItem["quantity"];
          totalItem.totalMoney += currItem.quantityOrder * (currItem.purchasePrice || 0);
 
          return totalItem;
        },
        { totalQuantity: 0, totalMoney: 0 }
      );
 
      let code = await this.ctx.service.common.getCodeRegular(102);
      let dataInfo = new PurchaseOrder();
      dataInfo = Object.assign(dataInfo, this.body);
      dataInfo.orderCode = code;
      dataInfo.statusID = 1;
      dataInfo.statusText = "新建";
      dataInfo.orderType = body.orderType || "常规预到货";
      dataInfo.totalQuantity = total.totalQuantity;
      dataInfo.totalWeight = 0;
      dataInfo.totalWeight = 0;
      dataInfo.totalMoney = total.totalMoney;
 
      await this.setAccountInfo(dataInfo);
      await this.dbWrite.save(dataInfo);
 
      for (let detailInfo of this.body.details) {
        let detail = new PurchaseOrderList();
        detail = Object.assign(detail, detailInfo);
        detail.order_Id = dataInfo.order_Id;
        await this.dbWrite.save(detail);
      }
 
      this.info.result = true;
      this.info.msg = "订单保存成功";
      this.info.data = {
        order_Id: dataInfo.order_Id,
        orderCode: dataInfo.orderCode
      };
      let logColl = db.collection("taskLogs");
      let data = {
        type: "order.add",
        msg: "入库单保存成功",
        order_Id: dataInfo.order_Id,
        orderCode: dataInfo.orderCode,
        createDate: new Date()
      };
      await logColl.insert(data);
    } catch (error) {
      this.info.result = false;
      this.info.data = error.message;
      let logColl = db.collection("taskLogs");
      let data = {
        type: "order.add",
        msg: "推送入库单失败," + error.messages,
        order_Id: null,
        orderCode: body.trackingNumber,
        createDate: new Date()
      };
      await logColl.insert(data);
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region  预到货单-确认为在途中
  /// <summary>
  /// 预到货单-确认为在途中
  /// </summary>
  /// <param name="order_Id"></param>
  /// <param name="isFullPlate"></param>
  /// <returns></returns>
  @Post()
  public async onInTransit() {
    let { ctx } = this;
    let body = ctx.request.body;
    let order_Ids = body.order_Ids;
    // let statusID = 4;
    // let statusText = "在途中";
    try {
      // this.info = await ctx.service.inbound.inScanService.onInTransit(body.order_Id, statusID, statusText);
      for (let order_Id of order_Ids) {
        let order = await this.dbRead.findOne(PurchaseOrder, {
          order_Id: order_Id
        });
        await this.dbWrite.update(
          PurchaseOrder,
          {
            order_Id: order.order_Id
          },
          {
            statusID: 4,
            statusText: "在途中"
          }
        );
        await this.dbWrite.save(PurchaseOrderStatusHistory, {
          order_Id: order.order_Id,
          statusType: "单据状态",
          operationType: "订单状态",
          fromStatus: "审核成功",
          toStatus: order.statusText,
          remark: order.remark,
          createID: order.user_Id,
          creator: order.userTrueName,
          createDate: new Date()
        });
      }
      this.info.result = true;
      this.info.msg = "操作成功!";
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 批量审核
  /**
   * 批量审核
   */
  @Post()
  public async batchAuditing() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let order_Ids = body.order_Ids;
    if (!order_Ids) {
      this.info.result = false;
      this.info.msg = "数据不存在";
      ctx.body = this.info;
      return;
    }
    try {
      for (let order_Id of order_Ids) {
        let orderInfo = await this.dbRead.findOne(PurchaseOrder, order_Id);
        if (!orderInfo.provider_Id) {
          this.info.result = false;
          this.info.msg = orderInfo.orderCode + "供应商不能为空";
          ctx.body = this.info;
          return;
        }
 
        await this.dbWrite.update(
          PurchaseOrder,
          {
            order_Id: order_Id
          },
          {
            statusID: 2,
            auditor: userInfo.userTrueName,
            auditing: 2,
            auditDate: new Date(),
            statusText: "审核成功"
          }
        );
        await this.dbWrite.save(PurchaseOrderStatusHistory, {
          order_Id: order_Id,
          statusType: "单据状态",
          operationType: "订单状态",
          fromStatus: "新建",
          toStatus: orderInfo.statusText,
          remark: orderInfo.remark,
          createID: userInfo.user_Id,
          creator: userInfo.userTrueName,
          createDate: new Date()
        });
      }
      this.info.result = true;
      this.info.msg = "审核成功";
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 批量导入
  /**
   * 批量导入入口,异步处理
   */
  @Post()
  public async import() {
    setTimeout(async () => {
      await this.importWork();
    }, 0);
 
    this.info.result = true;
    this.ctx.body = this.info;
  }
 
  /**
   * 批量导入业务处理
   */
  private async importWork() {
    let { ctx } = this;
    let body = ctx.request.body;
    let redis = ctx.app.redis.clients.get("common"); // 将消息放入redis缓存
    let fileUrl = body.fileUrl;
    let userInfo = await ctx.helper.userInfo();
 
    redis.expire(body.key, 5 * 60);
    if (!fileUrl) {
      this.setMsg("上传文件不存在", "red");
      return;
    }
    try {
      let rootPath = path.resolve(); // 获得根目录
      let filePath = rootPath + path.sep + fileUrl.replace(/\//gi, path.sep); // 上传文件路径
      var workbook = XLSX.readFile(filePath); //整个 excel 文档
      var sheetNames = workbook.SheetNames; //获取所有工作薄名
      var sheet1 = workbook.Sheets[sheetNames[0]]; //根据工作薄名获取工作薄
      let dataList = XLSX.utils.sheet_to_json(sheet1); // 获得当前sheet表单数据转为json格式
      // let isSuccess = true;
 
      //#region 验证数据正确性
      this.info.result = true;
      if (!dataList.length) {
        this.setMsg("没有可导入的数据", "red");
        return;
      }
      // let storage = await this.dbRead.findOne(BaseStorage, {
      //   storageName: body.storageName,
      //   userProduct_Id: userInfo.userProduct_Id
      // });
      // let msgList = dataList.map(async (item, index) => {
      let index = 0;
      let msgList = [];
      this.isMsgError = false;
      for (let item of dataList) {
        index++;
        //   if (!item["供应商简称"] || !item["数量"] || !item["单位毛重"] || !item["零件条码"] || !item["订单类型"]) {
        //     // isSuccess = false;
        //     this.setMsg(index + "、标黄部分数据不能为空", "red");
        //   }
        // let where = "productCode= :productCode and productModel =:productModel";
 
        let productInfo = await this.dbRead
          .createQueryBuilder(BaseProductInfo, "t")
          .where({
            productCode: "" + item["物料编号"],
            productName: "" + item["物料名称"]
          })
          .getOne();
        if (!productInfo) {
          this.setMsg(index + `、物料[${item["物料编号"]}]不存在,数据导入失败`, "red");
        }
        let poCodeData = await this.dbRead
          .createQueryBuilder(PurchaseOrder, "t")
          .where({
            poCode: "" + item["采购单号"]
          })
          .getOne();
        if (poCodeData) {
          this.setMsg(index + `、采购单号[${item["采购单号"]}]已存在,数据导入失败`, "red");
        }
 
        //判断时间的格式是否输入正确
        // let arrivedDate = item["预计到货时间"];
        // if (arrivedDate) {
        //   if (!isNumber(arrivedDate)) {
        //     this.setMsg(index + `、零件编号[${item["零件编号"]}]预计到货时间的格式不正确!`, "red");
        //   } else {
        //     item["预计到货时间"] = moment(new Date(1900, 0, arrivedDate - 1)).format("YYYY-MM-DD");
        //   }
        // }
 
        // let produceDate = item["生产日期"];
        // if (produceDate) {
        //   if (!isNumber(produceDate)) {
        //     this.setMsg(index + `、零件编号[${item["零件编号"]}]生产时间的格式不正确!`, "red");
        //   } else {
        //     item["生产日期"] = moment(new Date(1900, 0, produceDate - 1)).format("YYYY-MM-DD");
        //   }
        // }
 
        //   let quantityOrder = item["数量"];
        //   if (!quantityOrder) {
        //     this.setMsg(index + `、物料编号[${item["物料编号"]}]数量不能为空!`, "red");
        //   }
        index++;
      }
 
      // 校验失败返回
      if (this.isMsgError) {
        this.setMsg("-1");
        return;
      }
 
      msgList = msgList.filter(msg => msg);
 
      if (msgList.length) {
        this.info.result = false;
        this.info.msg = msgList.join("");
        // return;
        ctx.body = this.info;
      }
      // 分组
      let groupList = dataList.reduce((all: Array<any>, next) => (all.some(item => item["采购单号"] == next["采购单号"]) ? all : [...all, next]), []);
 
      for (let item of groupList) {
        let quotInfo = new PurchaseOrder();
        //处理主表
        let orderCode = await ctx.service.common.getCodeRegular(102);
 
        quotInfo.orderCode = orderCode;
        quotInfo.poCode = item["采购单号"];
        quotInfo.externalNo = item["采购项"];
        quotInfo.externalNo2 = item["删除标志"];
        quotInfo.returnOrderCode = item["文档类型"];
        quotInfo.statusText = "新建";
        quotInfo.providerCode = item["供应商代码"];
        quotInfo.auditRemark = item["采购部门"];
        quotInfo.finStatusText = item["采购组"];
        // quotInfo.platUserCode = item["交易货币"];
        quotInfo.providerShortName = item["供应商名称"];
        // quotInfo.platUserName = item["国家"];
        // quotInfo.platCorpName = item["最大行号"];
        quotInfo.orderType = "采购入库";
 
        quotInfo.trackingNumber = item["跟踪号"];
        quotInfo.saleCode = item["销售单号"];
        quotInfo.storage_Id = 87;
        quotInfo.storageName = "立体库";
        quotInfo.consignor_Id = 30;
        quotInfo.consignorCode = "GX30";
        quotInfo.consignorName = "广州西门子";
        quotInfo.statusID = 1;
 
        quotInfo.remark = null;
        quotInfo.createID = userInfo.user_Id;
        quotInfo.creator = userInfo.userTrueName;
        quotInfo.createDate = new Date();
 
        await this.setAccountInfo(quotInfo);
        //明细数据
        var billDetails = dataList.filter(w => w["采购单号"] == item["采购单号"]);
        // 主表求和字段计算
        let total: any = billDetails.reduce(
          (totalItem: any, currItem) => {
            totalItem.totalQuantityOrder += parseFloat(currItem["PO单位数量"] != null ? currItem["PO单位数量"] : 0);
            totalItem.totalWeight += parseFloat(currItem["数量"]) * parseFloat(currItem["单位毛重"] != null ? currItem["单位毛重"] : 0);
            totalItem.grandTotal += parseFloat(currItem["金额"] != null ? currItem["金额"] : 0);
 
            return totalItem;
          },
          { totalQuantityOrder: 0, totalWeight: 0, grandTotal: 0 }
        );
        quotInfo.totalWeight = total.totalWeight;
        await this.dbWrite.save(quotInfo);
        // let quotation = await this.dbRead.findOne(TMSQuotation, {
        //   quotationCode: orderCode
        // });
 
        index = 0;
        for (let item of billDetails) {
          index++;
          //添加到PurchaseOrderList表
          // var rowTotal = (item["单价"] != null ? item["单价"] : 0) * item["数量"];
          var totalWeight = item["单位毛重"] * item["数量"];
 
          // let where;
          // if (SKU_BarcodeToMultiProduct) {
          //   where = "ProductCode=N'" + item["零件编号"] + "'";
          // } else {
          //   where = "ProductCode=N'" + item["零件编号"] + "'  and  ProductModel=N'" + item["零件条码"] + "'";
          // }
          // let sql = "select * from Base_ProductInfo where " + where;
          // let productInfo = await this.dbRead.query(sql);
 
          let productInfo = await this.dbRead
            .createQueryBuilder(BaseProductInfo, "t")
            .where({
              productCode: "" + item["物料编号"],
              productName: "" + item["物料名称"]
            })
            .getOne();
 
          let listInfo = new PurchaseOrderList();
          listInfo.order_Id = quotInfo.order_Id;
          listInfo.product_Id = productInfo.product_Id;
          listInfo.productName = productInfo.productName;
          listInfo.productCode = productInfo.productCode;
          // listInfo.unitConvert = productInfo.unitConvert;
          listInfo.unitConvert = item["单位转换值"];
          listInfo.overcharges = item["容差率"];
          listInfo.smallUnit = productInfo.smallUnit;
          listInfo.bigUnit = productInfo.bigUnit;
          listInfo.productSpec = productInfo.productSpec;
 
          listInfo.productModel = productInfo.productModel;
 
          listInfo.extendField10 = item["采购单号"];
          listInfo.itemNumber = item["项号"];
          listInfo.extendField01 = item["采购项"];
          listInfo.extendField02 = item["工厂"];
          listInfo.extendField03 = item["储存位置"];
          listInfo.extendField04 = item["跟踪号"];
          listInfo.extendField05 = item["物料组"];
          listInfo.extendField06 = item["消息号"];
          listInfo.bigQty = item["数量"];
          listInfo.enterQuantity = item["单价"];
          listInfo.returnQuantity = item["总价"];
          listInfo.weight = item["重量"];
          listInfo.bigUnit = item["采购单位"];
          listInfo.extendField08 = item["价格单位"];
          listInfo.extendField09 = item["重量单位"];
          listInfo.extendField07 = item["销售单号"];
          listInfo.specAlias = item["销售项号"];
          listInfo.productBarCode = item["仓库号"];
          listInfo.relationCode = item["物料类别"];
          // listInfo.salePrice = productInfo.salePrice != null ? productInfo.salePrice : 0;
          // listInfo.batchNumber = item["批次号"] != null ? item["批次号"] : null;
          listInfo.totalWeight = totalWeight;
          listInfo.createDate = new Date();
          listInfo.creator = userInfo.userTrueName;
          listInfo.createID = userInfo.user_Id;
          await this.dbWrite.save(listInfo);
          this.setMsg(index + `、PO单号[${quotInfo.poCode}]导入成功`);
        }
      }
      this.info.result = true;
    } catch (ex) {
      this.setMsg("出现异常:" + ex.message, "red");
    }
    this.setMsg("-1");
  }
  //#endregion
 
  //#region 强制完成
  /**
   * 强制完成
   */
  @Post()
  public async forceFinish() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let order_Id = body.order_Id;
    if (!order_Id) {
      this.info.result = false;
      this.info.msg = "数据不存在";
      return this.info;
    }
    try {
      await this.dbWrite.update(PurchaseOrder, order_Id, {
        statusID: 13,
        statusText: "强制完成"
      });
 
      let orderInfo = await this.dbRead.findOne(PurchaseOrder, order_Id);
      await this.dbWrite.insert(PurchaseOrderStatusHistory, {
        order_Id: order_Id,
        statusType: "单据状态",
        operationType: "订单状态",
        fromStatus: orderInfo.statusText,
        toStatus: "强制完成",
        remark: orderInfo.remark,
        createID: userInfo.user_Id,
        creator: userInfo.userTrueName,
        createDate: new Date()
      });
      this.info.result = true;
      this.info.msg = "操作成功";
    } catch (error) {
      this.info.result = false;
      this.info.msg = "生成错误:" + error.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region  合并预到货单
  /// <summary>
  /// 合并预到货单
  /// </summary>
  /// <returns></returns>
  @Post()
  public async orderMerge() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let order_Ids = body.order_Ids;
    // let info = new ResultInfo<List<Base_Provider>>();
 
    try {
      let _orders = await this.dbRead.find(PurchaseOrder, {
        order_Id: In(order_Ids)
      });
      for (var itme of _orders) {
        if (itme.statusText != "新建") {
          this.info.result = false;
          this.info.msg = "新建状态才能合并";
          this.ctx.body = this.info;
          return;
        }
      }
 
      // var _oldOrders = _orders;
 
      if (_orders != null && _orders.length > 0) {
        let orderGroup = _orders.reduce(
          (all: Array<any>, next) =>
            all.some(item => item.consignor_Id == next.consignor_Id && item.storage_Id == next.storage_Id && item.provider_Id == next.provider_Id)
              ? all
              : [...all, next],
          []
        );
 
        var countGroup = orderGroup.length;
        if (countGroup > 1) {
          this.info.result = false;
          this.info.msg = "单据类型、货主、仓库、供应商不一致";
          this.ctx.body = this.info;
          return;
        }
 
        var _orderInfo = _orders[0];
        _orderInfo.order_Id = 0;
        _orderInfo.orderCode = await ctx.service.common.getCodeRegular(102);
        _orderInfo.orderType = "合并订单";
 
        _orderInfo.statusID = 1;
        _orderInfo.statusText = "新建";
        _orderInfo.finStatusID = 1;
        _orderInfo.finStatusText = "未付款";
        _orderInfo.arrivedDate = new Date();
        _orderInfo.totalQuantity = 0;
        // _orderInfo.expressFee = 0;
        // _orderInfo.totalMoney = 0;
        // _orderInfo.totalPaidMoney = 0;
        // _orderInfo.surplusTotal = 0;
        // _orderInfo.refund = 0;
 
        // _orderInfo.totalRateMoney = 0;
        // _orderInfo.taxAmountTotal = 0;
        // _orderInfo.totalRateMoney = 0;
 
        _orderInfo.modifyID = null;
        _orderInfo.modifier = null;
        _orderInfo.modifyDate = new Date();
 
        _orderInfo.createID = userInfo.user_Id;
        _orderInfo.creator = userInfo.userTrueName;
        _orderInfo.createDate = new Date();
 
        _orderInfo.platCorpName = userInfo.platCorpName;
        _orderInfo.platUserCode = userInfo.platUserCode;
        _orderInfo.platUserName = userInfo.platUserName;
        _orderInfo.platUser_Id = userInfo.platUser_Id;
        _orderInfo.userProductAlias = userInfo.userProductAlias;
        _orderInfo.userProductCode = userInfo.userProductCode;
        _orderInfo.userProduct_Id = userInfo.userProduct_Id;
        _orderInfo.auditDate = null;
        _orderInfo.applyDate = new Date();
        await this.dbWrite.insert(PurchaseOrder, _orderInfo);
 
        if (_orderInfo.order_Id > 0) {
          let _orderList = await this.dbRead.find(PurchaseOrderList, {
            order_Id: In(order_Ids)
          });
 
          let orderlistGroup = _orderList.reduce((all: Array<any>, next) => {
            let row = all.find(item => item.productCode == next.productCode && item.productSpec == next.productSpec);
            if (row) {
              row.quantity += next.quantity;
            }
            return row ? all : [...all, next];
          }, []);
 
          for (var item of orderlistGroup) {
            let _orderDetailInfo = new PurchaseOrderList();
            _orderDetailInfo = Object.assign(_orderDetailInfo, item);
            _orderDetailInfo.order_Id = _orderInfo.order_Id;
            _orderDetailInfo.discountRate = 1;
            _orderDetailInfo.ratePrice = _orderDetailInfo.purchasePrice / (1 - _orderDetailInfo.rate);
            _orderDetailInfo.rateMoney = _orderDetailInfo.purchaseMoney / (1 - _orderDetailInfo.rate);
            _orderDetailInfo.taxAmount = _orderDetailInfo.rateMoney - _orderDetailInfo.purchaseMoney;
            _orderDetailInfo.rateMoney = _orderDetailInfo.taxAmount;
 
            _orderDetailInfo.marketPrice = _orderDetailInfo.marketPrice;
            _orderDetailInfo.purchasePrice = _orderDetailInfo.marketPrice;
            _orderDetailInfo.purchaseMoney = _orderDetailInfo.marketPrice;
            _orderDetailInfo.rate = _orderDetailInfo.rate;
            _orderDetailInfo.quantity = item.quantity;
 
            await this.dbWrite.save(PurchaseOrderList, _orderDetailInfo);
          }
 
          // 主表求和字段计算
          let total: any = orderlistGroup.reduce(
            (totalItem: any, currItem) => {
              totalItem.totalQuantity += currItem.quantity;
              totalItem.totalRateMoney += currItem.totalRateMoney;
              totalItem.totalMoney += currItem.totalMoney;
              totalItem.surplusTotal += currItem.surplusTotal;
 
              return totalItem;
            },
            {
              totalQuantity: 0,
              totalRateMoney: 0,
              totalMoney: 0,
              surplusTotal: 0
            }
          );
 
          await this.dbWrite.update(PurchaseOrder, _orderInfo.order_Id, {
            totalQuantity: total.totalQuantity,
            totalRateMoney: total.totalRateMoney,
            totalMoney: total.totalMoney,
            surplusTotal: total.surplusTotal,
            statusID: 1,
            statusText: "新建",
            remark: "来源" + _orderInfo.orderCode
          });
          await this.dbWrite.update(
            PurchaseOrder,
            {
              order_Id: In(order_Ids)
            },
            {
              statusText: "已合并"
            }
          );
 
          this.info.result = true;
          this.info.msg = "合并成功,单号为:" + _orderInfo.orderCode;
        } else {
          this.info.result = false;
          this.info.msg = "合并失败";
        }
      } else {
        this.info.result = false;
        this.info.msg = "未找到单据信息";
      }
    } catch (e) {
      this.info.result = false;
      this.info.msg = e.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region getByCode
  /// <summary>
  /// 根据预到货单号Code获取预到货单信息
  /// </summary>
  /// <param name="orderCode">预到货单号,参数需要拼接在地址后,例如:/api/Purchase_Order/GetByCode?orderCode=xxxxxx</param>
  /// <returns>预到货单对象</returns>
  @Post()
  public async getByCode() {
    let userInfo = await this.userInfo;
    if (!this.body.orderCode) {
      this.info.result = false;
      this.info.msg = "参数不能为空!";
      this.ctx.body = this.info;
      return;
    }
 
    var model = await this.dbRead.findOne(PurchaseOrder, {
      orderCode: this.body.orderCode,
      userProduct_Id: userInfo.userProduct_Id
    });
    if (!model) {
      this.info.result = false;
      this.info.msg = "没有找到数据!";
      this.ctx.body = this.info;
      return;
    }
 
    //明细数据
    let detailList = await this.dbRead.find(PurchaseOrderList, {
      order_Id: model.order_Id
    });
    model.purchaseOrderList = detailList;
 
    this.info.result = true;
    this.info.data = model;
    this.ctx.body = this.info;
  }
  //#endregion
 
  // #region 明细转移
  /// <summary>
  /// 预到货单明细转移
  /// </summary>
  /// <returns></returns>
  @Post()
  public async transfer() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let detailIdList = body.detailIdList;
    try {
      // 校验数据
      if (!detailIdList) {
        this.info.result = false;
        this.info.msg = "未选中转移,无法操作!";
        return this.info;
      }
      const connection: any = await this.dbWrite.connection;
      let request = new mssql.Request(connection.driver.master);
      request.input("order_Id_Origin", body.order_Id);
      request.input("detailIdList", detailIdList);
      request.input("orderCode", body.orderCode);
      request.input("user_Id", userInfo.user_Id);
      request.output("outMsg", mssql.NVarChar(2000));
      let result = await request.execute("sp_Purchase_Order_Transfer");
      let outMsg = result.output.outMsg;
      if (outMsg) {
        this.info.msg = outMsg;
        this.info.result = false;
      } else {
        this.info.msg = "转移成功";
        this.info.result = true;
      }
    } catch (error) {
      this.info.result = false;
      this.info.msg = "生成错误:" + error.message;
    }
    ctx.body = this.info;
  }
  // #endregion
 
  //#region 预到货明细导出
  /// <summary>
  /// 预到货明细
  /// </summary>
  /// <param name="body"></param>
  /// <returns></returns>
  @Post()
  public async exportList() {
    let { ctx } = this;
    let body = ctx.request.body;
 
    try {
      let sql = "";
      sql = `SELECT 
 ProductCode AS '物料编号',ProductName AS '物料名称',ProductModel AS '条形码',ProductSpec AS '物料规格',quantity AS '数量',
 smallUnit AS '小单位',enterQuantity AS '已收货数量',returnQuantity AS '退货数量'
FROM  Purchase_OrderList
WHERE orderList_Id IN(select col from dbo.split(@0, ','))`;
 
      let transferList: Array<any> = await this.dbRead.query(sql, [body.ids]);
 
      let root = path.resolve();
      let url = "/download/预到货单明细数据.xlsx";
      let fileName = root + url.replace(/\//g, path.sep);
      let pathToCreate = fileName.substring(0, fileName.lastIndexOf(path.sep));
      ctx.helper.mkdir(pathToCreate);
 
      // wayBillList = wayBillList.splice(0, 0, {
      //   "分运单号":"xxxxxx"
      // }, {"申报类型": "xxxxsssss"}, {});
      let jsonWorkSheet = XLSX.utils.json_to_sheet(transferList);
      // 构造workBook
      let workBook = {
        SheetNames: ["数据"],
        Sheets: {
          数据: jsonWorkSheet
        }
      };
      XLSX.writeFile(workBook, fileName);
 
      this.info.result = true;
      this.info.data = {
        url: url
      };
      this.info.msg = "导出成功!";
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  // #region 导入Excel
  @Post()
  public async importExcel() {
    setTimeout(async () => {
      await this.importDetailExcelWork();
    }, 0);
 
    this.info.result = true;
    this.ctx.body = this.info;
  }
  /// <summary>
  /// 导入Excel
  /// </summary>
  /// <returns></returns>
  public async importDetailExcelWork() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let fileUrl = body.fileUrl;
    if (!fileUrl) {
      this.setMsg(`上传文件不存在`, "red");
      return;
    }
    if (!body.order_Id) {
      this.info.result = false;
      // this.info.msg = "请先保存,在导入数据!";
      this.setMsg(`请先保存,在导入数据!`, "red");
      this.setMsg("-1");
      return false;
      // return;
    }
    try {
      let rootPath = path.resolve(); // 获得根目录
      let filePath = rootPath + path.sep + fileUrl.replace(/\//gi, path.sep); // 上传文件路径
      var workbook = XLSX.readFile(filePath); //整个 excel 文档
      var sheetNames = workbook.SheetNames; //获取所有工作薄名
      var sheet1 = workbook.Sheets[sheetNames[0]]; //根据工作薄名获取工作薄
      let dataList = XLSX.utils.sheet_to_json(sheet1); // 获得当前sheet表单数据转为json格式
 
      // 验证数据正确性
      this.info.result = true;
      if (!dataList.length) {
        this.setMsg(`没有可导入的数据`, "red");
        return false;
      }
      let i = 1,
        successCount = 0,
        updateCount = 0;
      // 物料集合
      // let productList = await this.dbRead.find(BaseProductInfo, {
      //   userProduct_Id: userInfo.userProduct_Id,
      //   productCode: In(dataList.map(item => "" + item["物料编号"]))
      // });
      // 物料集合
      let productList = await this.dbRead.find(BaseProductInfo, {
        userProduct_Id: userInfo.userProduct_Id,
        productCode: In(dataList.map(item => "" + item["物料编号"]))
      });
      let dataRows = []; // 数据集合
      for (let row of dataList) {
        i++;
        let produceDate = row["生产日期"];
        if (produceDate) {
          if (!isNumber(produceDate)) {
            this.setMsg(`第${i}行、产品编号` + row["物料编号"] + `生产时间的格式不正确!`, "red");
            this.setMsg(`${i}、条形码不能为空`);
            updateCount++;
          } else {
            row["生产日期"] = moment(new Date(1900, 0, produceDate - 1)).format("YYYY-MM-DD");
          }
        }
        let data = {
          productCode: row["物料编号"],
          productName: row["物料名称"],
          productModel: row["条形码"],
          quantity: row["数量"],
          productSpec: row["物料规格"],
          smallUnit: row["小单位"],
          bigUnit: row["大单位"],
          shelfLifeDay: row["保质期(天)"],
          weight: row["单位重量"],
          totalWeight: row["小计毛重"],
          purchasePrice: row["不含税单价"],
          rate: row["税率"],
          ratePrice: row["含税单价"],
          // positionName: row["货位名称"],
          produceDate: row["生产日期"],
          batchNumber: row["批次号"],
          paiQty: row["建议拍数"],
          expandFields: {} // 扩展字段
        };
        let expandFields = {}; // 扩展字段值
        if (row["货位名称"]) {
          expandFields["positionName"] = row["货位名称"];
        }
        //#region 校验数据
        if (!data.productCode) {
          this.setMsg(`第${i}行、${data.productCode}、编号不能为空!`, "red");
          this.setMsg(`${i}、编号不能为空`);
          updateCount++;
        }
        if (!data.quantity) {
          this.setMsg(`第${i}行、${data.productCode}、数量不能为空!`, "red");
          updateCount++;
        }
        // 查询物料是否存在
        // let dataInfo = productList.find(item => item.productCode === data.productCode);
        // let productInfo = productList.find(item => item.productCode === data.productCode);
        let dataInfo = productList.find(item => item.productCode === data.productCode);
        if (!dataInfo) {
          this.setMsg(`第${i}行、${data.productCode}编号不存在,请核实信息!`, "red");
          updateCount++;
        }
        //#endregion
        dataRows.push(data);
      }
 
      if (this.isMsgError) {
        this.setMsg(`导入数据有错误,请处理好重新导入`, "red");
        this.setMsg("-1");
        return false;
      }
      i = 1;
      successCount = 0;
      for (let data of dataRows) {
        i++;
        // 查询物料是否存在
        let productinfo = productList.find(item => item.productCode === data.productCode);
 
        let _detail = new PurchaseOrderList();
 
        // 单位毛重 小计毛重都为空
        if (!data.weight && !data.totalWeight) {
          _detail.weight = productinfo.weight || 0;
          _detail.totalWeight = productinfo.weight * data.quantity;
        } else {
          _detail.weight = data.weight;
        }
        if (!data.weight && data.totalWeight) {
          _detail.totalWeight = data.totalWeight || 0;
          _detail.weight = data.totalWeight / data.quantity;
        }
        if (data.weight && !data.totalWeight) {
          _detail.weight = data.weight;
          _detail.totalWeight = data.weight * data.quantity;
        }
        if (data.weight && data.totalWeight) {
          _detail.weight = data.weight;
          _detail.totalWeight = data.totalWeight;
        }
        _detail.order_Id = body.order_Id;
        _detail.createID = userInfo.user_Id;
        _detail.creator = userInfo.userTrueName;
        _detail.product_Id = productinfo.product_Id;
        _detail.productCode = data.productCode;
        _detail.productName = data.productName;
        _detail.productModel = productinfo.productModel;
        _detail.productSpec = data.productSpec ? data.productSpec : productinfo.productSpec;
        _detail.quantity = data.quantity;
        _detail.smallUnit = data.smallUnit ? data.smallUnit : productinfo.smallUnit;
        _detail.bigUnit = data.bigUnit ? data.bigUnit : productinfo.bigUnit;
        _detail.shelfLifeDay = data.shelfLifeDay;
 
        _detail.purchasePrice = data.purchasePrice ? data.purchasePrice : 0;
        _detail.rate = data.rate ? data.rate : 0;
        _detail.ratePrice = data.ratePrice ? data.ratePrice : 0;
        _detail.originPlace = productinfo.originPlace;
        // _detail.totalWeight = _detail.quantity * _detail.weight;
        _detail.purchaseMoney = _detail.quantity * _detail.purchasePrice;
        _detail.taxAmount = _detail.quantity * _detail.ratePrice;
        _detail.paiQty = data.paiQty;
        _detail.batchNumber = data.batchNumber;
        _detail.produceDate = data.produceDate;
        // _detail.positionName = data.positionName;
 
        // 扩展字段处理
        // let expandFields = JSON.parse(dataInfo.expandFields);
        let expandFields = data.expandFields;
        expandFields = Object.assign(expandFields, data.expandFields);
        data.expandFields = JSON.stringify(expandFields);
        await this.dbWrite.insert(PurchaseOrderList, _detail);
        successCount++;
      }
      // 更新主表合计
      let sql = `
        update Purchase_Order set 
          totalQuantity=(select sum(quantity) from Purchase_OrderList where order_Id=Purchase_Order.order_Id),
          totalWeight=(select sum(totalWeight) from Purchase_OrderList where order_Id=Purchase_Order.order_Id),
          totalMoney=(select sum(purchaseMoney) from Purchase_OrderList where order_Id=Purchase_Order.order_Id),
          taxAmountTotal=(select sum(taxAmount) from Purchase_OrderList where order_Id=Purchase_Order.order_Id),
          totalRateMoney=(select sum(taxAmount) from Purchase_OrderList where order_Id=Purchase_Order.order_Id)
          where order_Id=@0;
        `;
      await this.dbWrite.query(sql, [body.order_Id]);
      this.setMsg(`导入成功,新增${successCount}条,更新${updateCount}条`, "blue");
    } catch (ex) {
      this.setMsg("出现异常:" + ex.message, "red");
      this.info.result = false;
    }
    this.setMsg("-1");
  }
  // #endregion
 
  //#region 拆分订单
  @Post()
  public async splitOrder() {
    let { ctx } = this;
    let userInfo = await this.userInfo;
    let body = ctx.request.body;
    let order_Id = body.order_Id;
    let productModelList = body.productModelList;
    let sql = "";
    let orderInfo = await this.dbRead.findOne(PurchaseOrder, {
      order_Id: order_Id
    });
    if (orderInfo.statusText != "新建") {
      this.info.result = false;
      this.info.msg = "只有新建的预到货才允许拆分";
      ctx.body = this.info;
    }
    try {
      let orderList = await this.dbRead.find(PurchaseOrderList, {
        order_Id: order_Id
      });
      let newOrderInfo = new PurchaseOrder();
      newOrderInfo = { ...orderInfo };
      if (productModelList.length > 0) {
        //#region 新订单处理
        newOrderInfo.order_Id = 0;
        // 生成订单号
        newOrderInfo.orderCode = await ctx.service.common.getCodeRegular(102);
        // 状态
        newOrderInfo.statusID = orderInfo.statusID;
        newOrderInfo.statusText = orderInfo.statusText;
        newOrderInfo.auditDate = orderInfo.auditDate;
        newOrderInfo.auditing = orderInfo.auditing;
        newOrderInfo.auditor = orderInfo.auditor;
        newOrderInfo.createID = userInfo.user_Id;
        newOrderInfo.creator = userInfo.userName;
        newOrderInfo.createDate = new Date();
        newOrderInfo.provider_Id = orderInfo.provider_Id;
        newOrderInfo.providerCode = orderInfo.providerCode;
        newOrderInfo.providerShortName = orderInfo.providerShortName;
        // 数量、金额
        newOrderInfo.totalQuantity = 0;
        // newOrderInfo.totalMoney = 0;
        // newOrderInfo.totalRateMoney = 0;
        newOrderInfo.totalWeight = 0;
        // 仓库
        newOrderInfo.storage_Id = orderInfo.storage_Id;
        newOrderInfo.storageName = orderInfo.storageName;
        await this.dbWrite.insert(PurchaseOrder, newOrderInfo);
        let newOrder_Id = newOrderInfo.order_Id;
        // 添加明细
        for (let dyn of productModelList) {
          //查询拆分的明细
          let orderList_Id = dyn.orderList_Id;
          let detail = orderList.filter(s => s.orderList_Id == orderList_Id)[0];
          if (dyn.quantity >= detail.quantity) {
            detail.order_Id = newOrderInfo.order_Id;
            await this.dbWrite.update(
              PurchaseOrderList,
              {
                orderList_Id: detail.orderList_Id
              },
              {
                order_Id: newOrderInfo.order_Id
              }
            );
          } else {
            // 如果拆分的数量小于明细数量,,同时在新订单下面新增明细
            let newdetail = new PurchaseOrderList();
            newdetail = { ...detail };
            newdetail.orderList_Id = 0;
            newdetail.order_Id = newOrderInfo.order_Id;
            newdetail.quantity = dyn.quantity;
            newdetail.product_Id = detail.product_Id;
            newdetail.productCode = detail.productCode;
            newdetail.productName = detail.productName;
            newdetail.productModel = detail.productModel;
            newdetail.weight = detail.weight;
            newdetail.purchasePrice = detail.purchasePrice;
            newdetail.rate = detail.rate;
            newdetail.ratePrice = detail.ratePrice;
            newdetail.produceDate = detail.produceDate;
            newdetail.smallUnit = detail.smallUnit;
            newdetail.productSpec = detail.productSpec;
            await this.dbWrite.insert(PurchaseOrderList, newdetail);
            // 将原来明细数量减少,计算不含税金额,含税金额、小计毛重
            detail.quantity -= dyn.quantity;
            detail.purchaseMoney = detail.quantity * detail.purchasePrice;
            detail.taxAmount = detail.quantity * detail.ratePrice;
            detail.totalWeight = detail.quantity * detail.weight;
            await this.dbWrite.save(detail);
          }
        }
        //#endregion
 
        //#region 新单状态的处理
        if (newOrder_Id > 0) {
          sql = `
          UPDATE Purchase_Order SET
          totalQuantity = (SELECT SUM(quantity) FROM dbo.Purchase_OrderList WHERE Order_Id = Purchase_Order.Order_Id),
          totalMoney = (SELECT SUM(purchaseMoney) FROM dbo.Purchase_OrderList WHERE Order_Id = Purchase_Order.Order_Id),
          totalRateMoney = (SELECT SUM(taxAmount) FROM dbo.Purchase_OrderList WHERE Order_Id = Purchase_Order.Order_Id),
          totalWeight = (SELECT SUM(totalWeight) FROM dbo.Purchase_OrderList WHERE Order_Id = Purchase_Order.Order_Id)
          WHERE Order_Id IN(@0, @1);
          `;
          await this.dbRead.query(sql, [orderInfo.order_Id, newOrder_Id]);
          this.info.result = true;
          this.info.msg = "拆分成功,新单号为" + newOrderInfo.orderCode + "!";
          await this.ctx.service.inbound.orderHelper.setStatusHistory(orderInfo.order_Id, orderInfo.statusText, "拆分", "单据状态", "订单拆分");
        } else {
          this.info.result = false;
          this.info.msg = "拆分失败,请重试!";
        }
        this.ctx.body = this.info;
        //#endregion
      }
    } catch (error) {
      this.info.result = false;
      this.info.msg = "拆分失败," + error.message;
      ctx.body = this.info;
    }
  }
  //#endregion
 
  //#region 一键入库 - 根据预到货单id获取明细数据
  @Post()
  public async getOrderDetails() {
    let body = this.ctx.request.body;
    let order_Id = body.order_Id;
    let storage_Id = body.storage_Id;
    let sql = `
    select P.orderList_Id, P.productCode,quantity,P.productName,(P.quantity - P.enterQuantity) AS enterQuantity,P.plateCode ,P.enterQuantity AS  unQuantity,
    DatEADD(HOUR,8, produceDate) AS produceDate,H.positionName, Pr.typeName,P.product_Id, P.weight, Round((P.weight * (P.quantity - P.enterQuantity)),2) as totalWeight, P.totalPackageQty, P.unitPackage, P.paiQty,
    P.batchNumber, P.singleSignCode,T.applyDate
    from
    Purchase_OrderList P left join Purchase_Order T ON P.order_Id = T.order_Id  LEFT JOIN Base_Position H ON 
    H.Storage_Id = T.Storage_Id AND H.positionType =4 left join Base_Productinfo Pr ON Pr.Product_Id = P.Product_Id
    where T.order_Id =${order_Id}  ORDER BY P.orderList_Id`;
    let orderList = await this.dbRead.query(sql);
 
    let emptysql = `select top 1 positionName from base_position p
    where channelCode in(
      select top 1 channelCode from base_position
      where storage_Id='${storage_Id}' and channelCode is not null
      group by channelCode
      order by count(positionName)
    ) and storage_Id='${storage_Id}'
    and not exists(select 1 from Base_ProductPosition where storage_Id=p.storage_Id and positionName=p.positionName and productStorage>0)
    `;
    let emptyList = await this.dbRead.query(emptysql);
    for (let item of emptyList) {
      for (let list of orderList) {
        list.positionName = item.positionName;
      }
    }
    this.info.result = true;
    this.info.data = orderList;
    this.ctx.body = this.info;
  }
  //#endregion
 
  //#region 一键入库 - 确认入库
  @Post()
  public async saveCheck() {
    let userInfo = await this.userInfo;
    let body = this.ctx.request.body;
    let jsonDetails = JSON.stringify(body.jsonDetails);
    if (!Array.isArray(body.jsonDetails)) {
      this.info.msg = "单据不存在";
      this.info.result = false;
      this.ctx.body = this.info;
      return;
    }
 
    let storageNameInfo = await this.dbRead.findOne(PurchaseOrder, {
      order_Id: body.order_Id
    });
    let jsondate = JSON.parse(jsonDetails);
    for (let itme of jsondate) {
      let Position = await this.dbRead.find(BasePosition, {
        storageName: storageNameInfo.storageName,
        userProduct_Id: userInfo.userProduct_Id,
        positionName: itme.positionName
      });
      if (Position.length == 0) {
        this.info.msg = itme.positionName + "货位不存在,不能入库!";
        this.info.result = false;
        this.ctx.body = this.info;
        return;
      }
    }
    try {
      const connection: any = await this.dbWrite.connection;
      let request = new mssql.Request(connection.driver.master);
      request.input("order_Id", body.order_Id);
      request.input("jsonDetails", jsonDetails);
      request.input("user_Id", userInfo.user_Id);
      request.input("userTrueName", userInfo.userTrueName);
      request.output("outMsg", mssql.NVarChar(2000));
      let result = await request.execute("sp_Purchase_Order_QuickShelve");
      let outMsg = result.output.outMsg;
      if (outMsg != null && outMsg) {
        this.info.msg = outMsg;
        this.info.result = false;
      } else {
        this.info.msg = "确认入库成功";
        this.info.result = true;
        for (let itme of jsondate) {
          await this.dbWrite.update(
            BasePlate,
            {
              plateCode: body.plateCode
            },
            {
              currentArea: storageNameInfo.storageName,
              currentLocation: itme.positionName
            }
          );
        }
      }
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
 
    this.ctx.body = this.info;
  }
  //#endregion
 
  //#region modifyfeeItems 修改一次性收费项
  @Post()
  public async modifyfeeItems() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    //#region 修改一次性收费项
    await this.dbWrite.update(
      PurchaseOrder,
      {
        order_Id: body.order_Id,
        userProduct_Id: userInfo.userProduct_Id
      },
      {
        feeItem_Ids: body.feeItem_Ids
      }
    );
    this.info.result = true;
    this.info.msg = "一次性收费项更新成功!";
 
    ctx.body = this.info;
    //#endregion
  }
  //#endregion
 
  //#region getlist 选择物料编号获取数据
  @Post()
  public async getlist() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let sql = `
      SELECT product_Id, productName, productCode, '' AS quantity, '合格'AS partStatus, 'WX-01' as positionName, CONVERT(VARCHAR(100),GETDATE(),23) as produceDate, productName, productSpec, productModel
      FROM Base_ProductInfo where productCode =@0 and userProduct_Id =@1`;
      let datalist = await this.dbRead.query(sql, [body.productCode, userInfo.userProduct_Id]);
      sql = `
      SELECT T.batchNumber FROM Purchase_OrderList AS P,TMS_QuotationList AS T WHERE P.productCode = T.ProductCode AND P.produceDate =T.produceDate AND T.ProductCode =@0`;
      let batchNumber = await this.dbRead.query(sql, [body.productCode]);
      this.info.data = datalist;
      this.info.data2 = batchNumber;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region savedata 保存数据
  @Post()
  public async savedata() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let details = []; // 记录明细保存的数据
    let masterData = body.masterData;
    let detailList = body.detailList;
 
    try {
      if (!Array.isArray(detailList) || !detailList.length) {
        this.info.result = false;
        this.info.msg = `明细不能为空!`;
        this.ctx.body = this.info;
        return;
      }
      let where = {
        plateCode: masterData.plateCode,
        userProduct_Id: userInfo.userProduct_Id,
        statusText: "新建",
        orderType: In(["PO单入库", "常规入库"])
      };
      // 编辑时排除自己
      if (masterData.order_Id) {
        where["order_Id"] = Not(masterData.order_Id);
      }
      // let orderInfo = await this.dbRead.findOne(PurchaseOrder, where);
      // if (orderInfo) {
      //   this.info.result = false;
      //   this.info.msg = `器具种类${masterData.plateCode}已创建,不可重复创建!`;
      //   this.ctx.body = this.info;
      //   return;
      // }
 
      let mainInfo = new PurchaseOrder(); // 主表数据
      // 必须做这边操作,编辑时才执行更新操作
      mainInfo = Object.assign(mainInfo, masterData);
      // 新建时,生成单据编号
      if (!mainInfo.order_Id) {
        let orderCode = await ctx.service.common.getCodeRegular(102);
        mainInfo.orderCode = orderCode;
      }
 
      // 主表求和字段计算
      let total: any = detailList.reduce(
        (totalItem: any, currItem) => {
          totalItem.totalBigQty += currItem.bigQty;
          return totalItem;
        },
        { totalBigQty: 0 }
      );
 
      // 状态默认为新建
      if (!mainInfo.statusText) {
        mainInfo.statusText = "新建";
      }
 
      mainInfo.orderType = masterData.orderType;
      mainInfo.storage_Id = 87;
      mainInfo.storageName = "立体库";
      mainInfo.plateCode = masterData.plateCode;
      mainInfo.createDate = new Date();
      mainInfo.createID = userInfo.user_Id;
      mainInfo.creator = userInfo.userTrueName;
      mainInfo.totalBigQty = total.totalBigQty; // PO单位数量
      mainInfo.partStatus = masterData.partStatus;
      mainInfo.consignor_Id = 30;
      mainInfo.consignorCode = "GX30";
      mainInfo.consignorName = "广州西门子";
      mainInfo.remark = masterData.remark;
      mainInfo.isPassWeight = masterData.isPassWeight; // 跳过重量检测
      await this.setAccountInfo(mainInfo);
      await this.dbWrite.save(mainInfo); // 保存主表信息,编辑和添加
 
      for (let item of detailList) {
        let detailInfo = new PurchaseOrderList();
        // 必须做这边操作,编辑时才执行更新操作
        detailInfo = Object.assign(detailInfo, item);
        let prodInfo = await this.dbRead.findOne(BaseProductInfo, item.Product_Id);
 
        detailInfo.order_Id = mainInfo.order_Id;
        detailInfo.productCode = item.productCode;
        detailInfo.product_Id = item.product_Id;
        detailInfo.productName = item.productName;
        detailInfo.productModel = item.productModel;
        detailInfo.produceDate = item.produceDate;
        detailInfo.productSpec = item.productSpec;
        detailInfo.produceDate = item.produceDate;
        detailInfo.plateCode = item.plateCode;
        detailInfo.batchNumber = item.batchNumber || mainInfo.orderCode;
        detailInfo.plateType = item.plateType;
        detailInfo.quantity = item.bigQty * item.unitConvert;
        detailInfo.bigQty = item.bigQty;
        detailInfo.itemNumber = item.itemNumber;
        detailInfo.bigUnEnterQuantity = item.bigQty;
        detailInfo.sourceMainID = item.quotation_Id;
        detailInfo.sourceListID = item.quotationList_Id;
        if (prodInfo) {
          detailInfo.images = prodInfo.images;
        }
        await this.setAccountInfo(detailInfo);
        await this.dbWrite.save(detailInfo); // 保存明细数据
        details.push(detailInfo);
      }
 
      this.info.data = mainInfo;
      this.info.data2 = details;
      this.info.result = true;
      this.info.msg = "数据保存成功";
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region getEUDataList EU箱库获取数据
  @Post()
  public async getEUDataList() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      // let posionName = await this.dbRead.findOne(PurchaseOrder, {
      //   plateCode: body.plateCode,
      //   platUser_Id: userInfo.platUser_Id
      // });
      let sql = `
      SELECT productName, productCode, quantity, partStatus,Convert(varchar(10),produceDate,120) as produceDate,batchNumber,storageName FROM  Purchase_Order AS O LEFT JOIN  Purchase_OrderList AS B ON B.order_Id = O.order_Id
      where orderCode =@0 and userProduct_Id =@1`;
      let productCodes = await this.dbRead.query(sql, [body.orderCode, userInfo.userProduct_Id]);
      this.info.data = productCodes;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region getEUDataList EU箱库获取数据
  @Post()
  public async getEUaddDataList() {
    let { ctx } = this;
    // let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let posionName = await this.dbRead.find(BaseProductInfo, {
        typeName: "EU箱库",
        userProduct_Id: userInfo.userProduct_Id
      });
 
      this.info.data = posionName;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region getWxjDataList 外协件库获取数据
  @Post()
  public async getWxjaddDataList() {
    let { ctx } = this;
    // let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let posionName = await this.dbRead.find(BaseProductInfo, {
        typeName: "外协件库",
        userProduct_Id: userInfo.userProduct_Id
      });
 
      this.info.data = posionName;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 获取仓库信息
  @Post()
  public async getStorageList() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let dataInfo = await this.dbRead.findOne(BaseStorage, {
        where: {
          storageName: body.storageName,
          userProduct_Id: userInfo.userProduct_Id
        }
      });
 
      this.info.data = dataInfo;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region sumitoutsoursave 外斜件标签保存数据
  @Post()
  public async sumitoutsoursave() {
    let { ctx } = this;
    let body = ctx.request.body;
    let purchase = new PurchaseOrder();
    // let userInfo = await ctx.helper.userInfo();
    try {
      let orderCode = await ctx.service.common.getCodeRegular(102);
      let orderDate = body.zhubdate;
      purchase.orderCode = orderCode;
      purchase.plateCode = orderDate.plateCode;
      purchase.orderType = "外协件库";
      purchase.storageName = body.storageName;
      purchase.statusText = "新建";
      // purchase.partStatus = "合格";
      await this.setAccountInfo(purchase);
      await this.dbWrite.save(purchase);
      let ordermoel = new PurchaseOrderList();
      let orderlist = body.datalist;
      // let orderlist = JSON.parse(body.datalist);
      let orderInfo = await this.dbRead.findOne(PurchaseOrder, {
        orderCode: orderCode
      });
      for (let item of orderlist) {
        ordermoel.order_Id = orderInfo.order_Id;
        ordermoel.productCode = item.productCode;
        ordermoel.productName = item.productName;
        ordermoel.quantity = item.quantity;
        ordermoel.produceDate = item.produceDate;
        ordermoel.batchNumber = "EU" + moment(new Date()).add("year", 0).format("YYYY-MM-DD") + item.productCode; //item.batchNumber;
        await this.dbWrite.save(ordermoel);
      }
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion  sumitoutsoursave
 
  //#region getEUDataList EU箱库获取数据
  @Post()
  public async getsouraddDataList() {
    let { ctx } = this;
    // let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let posionName = await this.dbRead.find(BaseProductInfo, {
        orderType: "外协件库",
        userProduct_Id: userInfo.userProduct_Id
      });
      this.info.data = posionName;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 外协件入库根据扫描标签获取数据
  @Post()
  public async getoutsourData() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      // let posionName = await this.dbRead.findOne(PurchaseOrder, {
      //   plateCode: body.plateCode,
      //   userProduct_Id: userInfo.userProduct_Id
      // });
      let sqls = `select max(Order_Id) Order_Id,StorageName from Purchase_Order 
      WHERE   PlateCode='${body.plateCode}' AND statusText='新建' 
      AND UserProduct_Id='${userInfo.userProduct_Id}' group by Order_Id,StorageName`;
      let posionName = await this.dbWrite.query(sqls);
      let productCodes = null;
      for (let item of posionName) {
        let sql = `SELECT * FROM  Purchase_Order P  INNER JOIN Purchase_OrderList PL ON PL.Order_Id = P.Order_Id WHERE   P.Order_Id =${item.Order_Id}`;
        productCodes = await this.dbRead.query(sql);
      }
 
      // let order_Id = "";
 
      this.info.data = posionName;
      this.info.data2 = productCodes;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 入库异常修正更改
  @Post()
  public async instorageabnormal() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let posionName = await this.dbRead.findOne(PurchaseOrder, {
        plateCode: body.plateCode,
        userProduct_Id: userInfo.userProduct_Id
      });
      await this.dbWrite.update(
        PurchaseOrderList,
        {
          order_Id: posionName.order_Id,
          productCode: body.productCode
        },
        {
          quantity: body.quantity
        }
      );
      // let sql = ` SELECT productName,productCode,weight,B.totalWeight,quantity,A.partStatus,A.productionLineName ,Convert(varchar(10),produceDate,120) as produceDate FROM Purchase_Order AS A ,Purchase_OrderList AS B
      // WHERE A.Order_Id = B.Order_Id AND  A.plateCode = @0 and platUser_Id =@1`;
      // let productlist = await this.dbRead.query(sql, [body.plateCode, userInfo.platUser_Id]);
      // this.info.data = posionName;
      // this.info.data2 = productlist;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 标签补打 根据器具编号带出数据
  @Post()
  public async lablemakeuplist() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      let sql = ` SELECT TOP 1 B.plateCode,storageName,orderType,productName,productCode,quantity,partStatus,productionLineName,
                 Convert(varchar(10),produceDate,120) as produceDate,weight,A.totalWeight 
                 FROM Purchase_OrderList AS A LEFT JOIN dbo.Purchase_Order AS B ON B.Order_Id = A.Order_Id WHERE B.plateCode =@0 
                 and UserProduct_Id =@1 AND storageName ='立体库' AND B.StatusText ='新建'  ORDER BY B.CreateDate DESC`;
      let productlist = await this.dbRead.query(sql, [body.plateCode, userInfo.userProduct_Id]);
      this.info.data = productlist;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "错误:" + error.message;
    }
    this.info.result = true;
    ctx.body = this.info;
  }
  //#endregion
 
  //#region app 物料信息 加载
  @Post()
  public async getproductlist() {
    let { ctx } = this;
    // let body = ctx.request.body;
    this.info.result = true;
    let userInfo = await ctx.helper.userInfo();
 
    let productdate = await this.dbRead.find(BaseProductInfo, {
      userProduct_Id: userInfo.userProduct_Id
    });
    this.info.data = productdate;
    this.ctx.body = this.info;
  }
 
  //#endregion
 
  //#region 根据订单号、快递单号、波次单号、波次单ID获得出库单ID集合
  /**
   * 根据订单号、快递单号、波次单号、波次单ID获得出库单ID集合
   */
  @Post()
  public async getOrderIds() {
    let { ctx } = this;
    let body = ctx.request.body;
    try {
      let orderPrintDetails = await this.dbRead.find(PurchaseOrderList, {
        order_Id: In(body.ids)
      });
 
      let idArr = orderPrintDetails
        .reduce((all: Array<any>, next) => (all.some(item => item["order_Id"] == next["order_Id"]) ? all : [...all, next]), [])
        .map(item => item.order_Id);
 
      if (idArr.length) {
        this.info.result = true;
        this.info.data = idArr;
      } else {
        this.info.result = false;
        this.info.msg = "未获得订单信息";
      }
      ctx.body = this.info;
    } catch (error) {
      this.info.result = false;
      this.info.msg = "未获得订单信息";
      ctx.body = this.info;
    }
  }
  //#endregion
 
  //#region 更新打印次数
  @Post()
  public async updatePrintCount() {
    try {
      await this.dbWrite.increment(
        PurchaseOrder,
        {
          order_Id: In(this.body.ids)
        },
        this.body.type,
        1
      );
      this.info.result = true;
      this.info.msg = "打印次数更新成功";
    } catch (error) {
      this.info.result = false;
      this.info.msg = "打印次数更新失败," + error.message;
    }
 
    this.ctx.body = this.info;
  }
  //#endregion
 
  //#region AddPosition
  /**
   * 根据入库标签id获取到此条没有货位的数据  并给其赋值
   */
  // @Post()
  // public async addPosition() {
  //   let userInfo = await this.userInfo;
  //   let { ctx } = this;
  //   let body = ctx.request.body;
 
  //   let orderPrintDetails = await this.dbRead.find(PurchaseOrder, {
  //     userProduct_Id: userInfo.userProduct_Id,
  //     order_Id: body.ids
  //   });
  //   for (let item of orderPrintDetails) {
  //     if (item.positionName) {
  //       this.info.result = false;
  //       this.ctx.body = this.info;
  //     }
 
  //     let sql = `SELECT TOP 1 PositionName
  //   FROM(
  //   SELECT Position_Id, PositionName, PlateType, (SELECT SUM(1) FROM dbo.vBase_ProductPosition PP WHERE P.Storage_Id=${
  //     item.storage_Id
  //   } AND PP.ChannelCode=P.ChannelCode) AS ChannelPositonCount
  //   FROM dbo.Base_Position P
  //   WHERE PlateType='${item.plateType}' AND Storage_Id=${item.storage_Id}
  //   AND NOT EXISTS(SELECT 1 FROM Base_Plate PT WHERE P.PositionName=PT.CurrentLocation)
  //   AND NOT EXISTS(SELECT 1 FROM Base_ProductPosition PR WHERE P.PositionName=PR.PositionName AND PR.ProductStorage>0)
  //   ) t
  //   ORDER BY t.ChannelPositonCount`;
  //     let emptyList = await this.dbRead.query(sql);
  //     for (let item of emptyList) {
  //       await this.dbWrite.update(
  //         PurchaseOrder,
  //         {
  //           userProduct_Id: userInfo.userProduct_Id,
 
  //           order_Id: body.ids
  //         },
  //         {
  //           positionName: item.PositionName
  //         }
  //       );
  //     }
  //   }
 
  //   this.info.result = true;
  //   // this.info.msg = "修改成功!";
  //   this.ctx.body = this.info;
  //   return;
  // }
  //#endregion
 
  //#region 打印完成后更改状态
  @Post()
  public async updateStatusText() {
    let userInfo = await this.userInfo;
    let { ctx } = this;
    let body = ctx.request.body;
 
    // let Order = await this.dbRead.findOne(PurchaseOrder, {
    //   orderCode: body.orderCode,
    //   userProduct_Id: userInfo.userProduct_Id;
    // });
 
    await this.dbWrite.update(
      PurchaseOrder,
      {
        statusText: "已打印标签",
        statusID: 1
      },
      {
        orderCode: body.orderCode,
        userProduct_Id: userInfo.userProduct_Id
      }
    );
    this.info.result = true;
    // this.info.msg = "修改成功!";
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region 打印完成后更改状态
  @Post()
  public async UpdatePlate() {
    let userInfo = await this.userInfo;
    let { ctx } = this;
    let body = ctx.request.body;
    await this.dbWrite.update(
      BasePlate,
      {
        plateCode: body.plateCode,
        userProduct_Id: userInfo.userProduct_Id
      },
      {
        currentLocation: "组盘区"
      }
    );
    this.info.result = true;
    // this.info.msg = "修改成功!";
    this.ctx.body = this.info;
    return;
  }
  //#endregion
}