移动系统liao
2025-02-17 557c2711a3e103ebc3d0492344eca9730d5e92b2
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
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
/***********************************************************************
 *            Project: baifenBinfa
 *        ProjectName: 百分兵法管理系统                               
 *                Web: http://chuanyin.com                     
 *             Author:                                        
 *              Email:                               
 *         CreateTime: 202403/02   
 *        Description: 暂无
 ***********************************************************************/
 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.WeChat.Service.HttpClients;
using Essensoft.Paylink.Alipay.Domain;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using SqlSugar;
using Yitter.IdGenerator;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinUserInfoBatchGetRequest.Types;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.ChannelsECLeagueHeadSupplierOrderGetResponse.Types.CommssionOrder.Types.OrderDetail.Types;
 
 
namespace CoreCms.Net.Services
{
    /// <summary>
    /// 订单表 接口实现
    /// </summary>
    public class CoreCmsOrderServices : BaseServices<CoreCmsOrder>, ICoreCmsOrderServices
    {
        private readonly ICoreCmsOrderRepository _dal;
 
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICoreCmsShipServices _shipServices;
        private readonly ICoreCmsCartServices _cartServices;
        private readonly ICoreCmsGoodsServices _goodsServices;
        private readonly ICoreCmsCouponServices _couponServices;
        private readonly ICoreCmsUserPointLogServices _userPointLogServices;
        private readonly ICoreCmsPinTuanRecordServices _pinTuanRecordServices;
        private readonly ICoreCmsBillDeliveryServices _billDeliveryServices;
        private readonly ICoreCmsAreaServices _areaServices;
        private readonly ICoreCmsSettingServices _settingServices;
        private readonly ICoreCmsLogisticsServices _logisticsServices;
        private readonly ICoreCmsInvoiceServices _invoiceServices;
        private readonly ICoreCmsBillAftersalesServices _billAftersalesServices;
        private readonly ICoreCmsOrderItemServices _orderItemServices;
        private readonly ICoreCmsInvoiceRecordServices _invoiceRecordServices;
        private readonly ICoreCmsOrderLogServices _orderLogServices;
        private readonly ICoreCmsUserShipServices _userShipServices;
        private readonly ICoreCmsStoreServices _storeServices;
        private readonly ICoreCmsUserServices _userServices;
        private readonly ICoreCmsBillPaymentsServices _billPaymentsServices;
        private readonly ICoreCmsPaymentsServices _paymentsServices;
        private readonly ICoreCmsBillRefundServices _billRefundServices;
        private readonly ICoreCmsBillLadingServices _billLadingServices;
        private readonly ICoreCmsBillReshipServices _billReshipServices;
        private readonly ICoreCmsMessageCenterServices _messageCenterServices;
        private readonly ICoreCmsGoodsCommentServices _goodsCommentServices;
        private readonly ISysTaskLogServices _taskLogServices;
        private readonly ICoreCmsPromotionRecordServices _promotionRecordServices;
        private readonly IRedisOperationRepository _redisOperationRepository;
        private readonly ICoreCmsUserWeChatInfoServices _userWeChatInfoServices;
        private readonly WeChat.Service.HttpClients.IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
        private readonly ICoreCmsPlanOrderServices _planOrderServices;
     
 
        private IUnitOfWork _unitOfWork;
 
        public CoreCmsOrderServices(ICoreCmsOrderRepository dal
            , IHttpContextAccessor httpContextAccessor
            , ICoreCmsShipServices shipServices
            , ICoreCmsCartServices cartServices
            , ICoreCmsGoodsServices goodsServices
            , ICoreCmsCouponServices couponServices
            , ICoreCmsUserPointLogServices userPointLogServices
            , ICoreCmsPinTuanRecordServices pinTuanRecordServices
            , ICoreCmsBillDeliveryServices billDeliveryServices
            , ICoreCmsAreaServices areaServices
            , ICoreCmsSettingServices settingServices
            , ICoreCmsLogisticsServices logisticsServices
            , ICoreCmsInvoiceServices invoiceServices
            , ICoreCmsBillAftersalesServices billAftersalesServices
            , ICoreCmsOrderItemServices orderItemServices
            , ICoreCmsInvoiceRecordServices invoiceRecordServices
            , ICoreCmsOrderLogServices orderLogServices
            , ICoreCmsUserShipServices userShipServices
            , ICoreCmsStoreServices storeServices
            , ICoreCmsUserServices userServices
            , ICoreCmsBillPaymentsServices billPaymentsServices
            , ICoreCmsPaymentsServices paymentsServices
            , ICoreCmsBillRefundServices billRefundServices
            , ICoreCmsBillLadingServices billLadingServices
            , ICoreCmsBillReshipServices billReshipServices, ICoreCmsMessageCenterServices messageCenterServices, ICoreCmsGoodsCommentServices goodsCommentServices, ISysTaskLogServices taskLogServices, ICoreCmsPromotionRecordServices promotionRecordServices, IRedisOperationRepository redisOperationRepository, ICoreCmsUserWeChatInfoServices userWeChatInfoServices, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, IUnitOfWork unitOfWork
            , ICoreCmsPlanOrderServices planOrderServices)
        {
            this._dal = dal;
            base.BaseDal = dal;
 
            _httpContextAccessor = httpContextAccessor;
            _shipServices = shipServices;
            _cartServices = cartServices;
            _goodsServices = goodsServices;
            _couponServices = couponServices;
            _userPointLogServices = userPointLogServices;
            _pinTuanRecordServices = pinTuanRecordServices;
            _billDeliveryServices = billDeliveryServices;
            _areaServices = areaServices;
            _settingServices = settingServices;
            _logisticsServices = logisticsServices;
            _invoiceServices = invoiceServices;
            _billAftersalesServices = billAftersalesServices;
            _orderItemServices = orderItemServices;
            _invoiceRecordServices = invoiceRecordServices;
            _orderLogServices = orderLogServices;
            _userShipServices = userShipServices;
            _storeServices = storeServices;
            _userServices = userServices;
            _billPaymentsServices = billPaymentsServices;
            _paymentsServices = paymentsServices;
            _billRefundServices = billRefundServices;
            _billLadingServices = billLadingServices;
            _billReshipServices = billReshipServices;
            _messageCenterServices = messageCenterServices;
            _goodsCommentServices = goodsCommentServices;
            _taskLogServices = taskLogServices;
            _promotionRecordServices = promotionRecordServices;
            _redisOperationRepository = redisOperationRepository;
            _userWeChatInfoServices = userWeChatInfoServices;
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            _unitOfWork = unitOfWork;
            _planOrderServices = planOrderServices;
        }
 
        #region 查询团购秒杀下单数量(获取货品的秒杀团购数据)
        /// <summary>
        /// 查询团购秒杀下单数量(获取货品的秒杀团购数据)
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="userId"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public FindLimitOrderDto FindLimitOrder(int productId, int userId, DateTime? startTime, DateTime? endTime, int orderType = 0)
        {
            return _dal.FindLimitOrder(productId, userId, startTime, endTime, orderType);
        }
 
        #endregion
 
        #region 查询团购秒杀下单数量(获取商品序号的秒杀团购数据)
        /// <summary>
        /// 查询团购秒杀下单数量(获取商品序号的秒杀团购数据)
        /// </summary>
        /// <param name="goodId"></param>
        /// <param name="userId"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public FindLimitOrderDto FindLimitOrderByGoodId(int goodId, int userId, DateTime? startTime, DateTime? endTime, int orderType = 0)
        {
            return _dal.FindLimitOrderByGoodId(goodId, userId, startTime, endTime, orderType);
        }
 
        #endregion
 
 
        #region 获取税号
        /// <summary>
        /// 获取税号
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetTaxCode(string name)
        {
            var jm = new WebApiCallBack();
 
            var list = await _invoiceRecordServices.QueryPageAsync(p => p.name.Contains(name) && p.frequency >= 1, p => p.id, OrderByType.Desc, 1, 10);
            jm.data = list;
            jm.status = true;
            jm.msg = "获取成功";
            return jm;
        }
 
        #endregion
 
        #region 创建订单
 
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="userId">用户序列</param>
        /// <param name="orderType">订单类型,1是普通订单,2是拼团订单</param>
        /// <param name="cartIds">购物车货品序列</param>
        /// <param name="receiptType">收货方式,1快递物流,2同城配送,3门店自提</param>
        /// <param name="ushipId">用户地址库序列</param>
        /// <param name="storeId">门店序列</param>
        /// <param name="ladingName">提货人姓名</param>
        /// <param name="ladingMobile">提货人联系方式</param>
        /// <param name="memo">备注</param>
        /// <param name="point">积分</param>
        /// <param name="couponCode">优惠券码</param>
        /// <param name="source">来源平台</param>
        /// <param name="scene">场景值(一般小程序才有)</param>
        /// <param name="taxType">发票信息</param>
        /// <param name="taxName">发票抬头</param>
        /// <param name="taxCode">发票税务编码</param>
        /// <param name="objectId">关联非普通订单营销功能的序列</param>
        /// <param name="teamId">拼团订单分组序列</param>
        /// <param name="requireOrder">微信自定义组件(是否需要推单,1:需要,0:不需要)</param>
        /// <param name="requiredFundType">微信自定义组件(requireOrder = 1时生效,0,非二级商户号订单,1,二级商户号订单,2,两种方式皆可(后续只会存在1))</param>
        /// <param name="traceId">微信自定义组件(跟踪ID,有效期十分钟,会影响主播归因、分享员归因等,需创建订单前调用,调用生成订单 api 时需传入该参数)</param>
        /// <param name="planorderId">计划订单id</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> ToAdd(int userId, int orderType, string cartIds, int receiptType, int ushipId, int storeId, string ladingName, string ladingMobile, string memo, int point, string couponCode, int source, int scene, int taxType, string taxName, string taxCode, int objectId, int teamId, int requireOrder, int requiredFundType, string traceId, string planorderId)
        {
            var jm = new WebApiCallBack() { methodDescription = "创建订单" };
            try
            {
                //开始事务处理
                _unitOfWork.BeginTran();
                var order = new CoreCmsOrder
                {
                    orderId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.订单编号),
                    userId = userId,
                    orderType = orderType,
                    point = point,
                    coupon = couponCode,
                    receiptType = receiptType,
                    objectId = objectId
                };
 
                //生成收货信息
                var areaId = 0;
                var deliveryRes = await FormatOrderDelivery(order, receiptType, ushipId, storeId, ladingName, ladingMobile);
                if (!deliveryRes.status)
                {
                    _unitOfWork.RollbackTran();
                    return deliveryRes;
                }
                else
                {
                    areaId = Convert.ToInt32(deliveryRes.data);
                }
 
                //通过购物车生成订单信息和订单明细信息
                List<CoreCmsOrderItem> orderItems;
                var ids = CommonHelper.StringToIntArray(cartIds);
                var orderRes = await FormatOrder(order, userId, ids, areaId, point, couponCode, ushipId, receiptType, objectId);
                if (!orderRes.status)
                {
                    _unitOfWork.RollbackTran();
                    return orderRes;
                }
                else
                {
                    orderItems = orderRes.data as List<CoreCmsOrderItem>;
                }
 
                //以下值不是通过购物车得来的,是直接赋值的,就写这里吧,不写formatOrder里了。
                order.memo = memo;
                order.source = source;
                order.taxType = taxType;
                order.taxTitle = taxName;
                order.taxCode = taxCode;
                order.shipStatus = (int)GlobalEnumVars.OrderShipStatus.No;
                order.status = (int)GlobalEnumVars.OrderStatus.Normal;
                order.confirmStatus = (int)GlobalEnumVars.OrderConfirmStatus.ReceiptNotConfirmed;
                order.createTime = DateTime.Now;
                order.scene = scene;
                order.planorderId = planorderId;
 
                //上面保存好订单表,下面保存订单的其他信息
                if (orderItems == null)
                {
                    jm.msg = "订单明细获取失败";
                    return jm;
                }
 
                jm.msg = "更改库存";
                //更改库存
                var avaliableOrderItems = orderItems.Where(item =>
                {
                    var res = _goodsServices.ChangeStock(item.productId,
                        GlobalEnumVars.OrderChangeStockType.order.ToString(), item.nums);
                    if (!res.status)
                    {
                        jm.msg += $"{item.name}库存不足";
                    }
 
                    return res.status;
                }).ToList();
 
                if (avaliableOrderItems.Count == 0)
                {
                    await _orderItemServices.InsertCommandAsync(orderItems);
 
                    await _dal.UpdateAsync(n => new CoreCmsOrder()
                    {
                        status = (int)GlobalEnumVars.OrderStatus.Cancel,
                        updateTime = DateTime.Now
                    },
                        m => m.orderId == order.orderId);
 
                    //清除购物车信息
                    _unitOfWork.RollbackTran();
                    await _cartServices.DeleteAsync(p =>
                        ids.Contains(p.id) && p.userId == userId && p.type == orderType);
                    jm.msg = "下单失败,库存不足";
                    return jm;
                }
 
                jm.msg = "订单明细更新" + avaliableOrderItems.Count;
                var outItems = await _orderItemServices.InsertCommandAsync(avaliableOrderItems);
                var outItemsBool = outItems > 0;
                if (!outItemsBool)
                {
                    _unitOfWork.RollbackTran();
                    jm.msg = "订单明细更新失败";
                    jm.data = outItems;
                    return jm;
                }
 
                //优惠券核销
                if (!string.IsNullOrEmpty(couponCode))
                {
                    var arr = CommonHelper.StringToStringArray(couponCode);
                    var couponRes = await _couponServices.UsedMultipleCoupon(arr, order.orderId);
                    if (!couponRes.status)
                    {
                        _unitOfWork.RollbackTran();
                        return couponRes;
                    }
                }
 
                //积分核销
                if (order.point > 0)
                {
                    jm.msg += "积分核销";
                    var pointLogRes = await _userPointLogServices.SetPoint(userId, 0 - order.point,
                        (int)GlobalEnumVars.UserPointSourceTypes.PointTypeDiscount, "订单" + order.orderId + "使用");
                    if (!pointLogRes.status)
                    {
                        _unitOfWork.RollbackTran();
                        return pointLogRes;
                    }
                }
 
                //不同的订单类型会有不同的操作
                switch (orderType)
                {
                    case (int)GlobalEnumVars.OrderType.Common:
                        //标准模式不需要修改订单数据和商品数据
                        break;
                    case (int)GlobalEnumVars.OrderType.PinTuan:
                        //拼团模式去校验拼团是否存在,并添加拼团记录
                        var pinTuanRes = await _pinTuanRecordServices.OrderAdd(order, avaliableOrderItems, teamId);
                        if (!pinTuanRes.status)
                        {
                            _unitOfWork.RollbackTran();
                            return pinTuanRes;
                        }
 
                        break;
                    case (int)GlobalEnumVars.OrderType.Group:
                        var groupRes =
                            await _promotionRecordServices.OrderAdd(order, avaliableOrderItems, objectId,
                                orderType);
                        if (!groupRes.status)
                        {
                            _unitOfWork.RollbackTran();
                            return groupRes;
                        }
 
                        break;
                    case (int)GlobalEnumVars.OrderType.Seckill:
                        var seckillRes =
                            await _promotionRecordServices.OrderAdd(order, avaliableOrderItems, objectId,
                                orderType);
                        if (!seckillRes.status)
                        {
                            _unitOfWork.RollbackTran();
                            return seckillRes;
                        }
 
                        break;
                    case (int)GlobalEnumVars.OrderType.Bargain:
                        //砍价模式
 
                        break;
                }
 
 
                //校验后再创建订单
                await _dal.InsertAsync(order);
 
                //清除购物车信息
                await _cartServices.DeleteAsync(p => ids.Contains(p.id) && p.userId == userId && p.type == orderType);
 
                //订单记录
                var orderLog = new CoreCmsOrderLog
                {
                    userId = userId,
                    orderId = order.orderId,
                    type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_CREATE,
                    msg = "订单创建",
                    data = JsonConvert.SerializeObject(order),
                    createTime = DateTime.Now
                };
                await _orderLogServices.InsertAsync(orderLog);
 
                //企业发票信息记录
                if (taxType == (int)GlobalEnumVars.OrderTaxType.Company)
                {
                    var invoiceRecord = await _invoiceRecordServices.QueryByClauseAsync(p => p.code == taxCode && p.name == taxName);
                    if (invoiceRecord != null)
                    {
                        invoiceRecord.frequency += 1;
                        await _invoiceRecordServices.UpdateAsync(invoiceRecord);
                    }
                    else
                    {
                        invoiceRecord = new CoreCmsInvoiceRecord { code = taxCode, name = taxName, frequency = 1 };
                        await _invoiceRecordServices.InsertAsync(invoiceRecord);
                    }
                }
                order.taxTitle = taxName;
                order.taxCode = taxCode;
 
                //发送消息
                //0元订单记录支付成功
                if (order.orderAmount <= 0)
                {
                    //创建支付单
                    var billPayments = new CoreCmsBillPayments();
                    billPayments.paymentId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.支付单编号);
                    billPayments.sourceId = order.orderId;
                    billPayments.money = 0;
                    billPayments.userId = userId;
                    billPayments.type = order.orderType;
                    billPayments.status = (int)GlobalEnumVars.BillPaymentsStatus.Payed;
                    billPayments.paymentCode = GlobalEnumVars.PaymentsTypes.balancepay.ToString();
                    billPayments.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1";
                    billPayments.payedMsg = "0元订单直接支付成功";
                    billPayments.parameters = "";
                    billPayments.createTime = DateTime.Now;
                    billPayments.updateTime = DateTime.Now;
 
 
                    await _billPaymentsServices.InsertAsync(billPayments);
 
                    //调整直接支付成功
                    await _dal.UpdateAsync(p => new CoreCmsOrder()
                    {
                        payedAmount = 0,
                        paymentTime = DateTime.Now,
                        updateTime = DateTime.Now,
                        paymentCode = GlobalEnumVars.PaymentsTypes.balancepay.ToString(),
                        payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes,
                        orderAmount = 0
                    }, p => p.orderId == order.orderId);
 
                    //记录订单日志
                    orderLog = new CoreCmsOrderLog
                    {
                        userId = userId,
                        orderId = order.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_PAY,
                        msg = "0元订单直接支付成功",
                        data = JsonConvert.SerializeObject(order),
                        createTime = DateTime.Now
                    };
                    await _orderLogServices.InsertAsync(orderLog);
 
 
                    ////拆单
                    //var jms  = await  Chaidan(order.orderId);
                    //var orderchai = await _dal.QueryByClauseAsync(p => p.orderId == order.orderId);
                    //orderchai.Orderitems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
 
                    //如果是门店自提,应该自动跳过发货,生成提货单信息,使用提货单核销。
                    if (order.receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
                    {
                        var allConfigs = await _settingServices.GetConfigDictionaries();
                        var storeOrderAutomaticDelivery = CommonHelper
                            .GetConfigDictionary(allConfigs, SystemSettingConstVars.StoreOrderAutomaticDelivery)
                            .ObjectToInt(1);
                        if (storeOrderAutomaticDelivery == 1)
                        {
                            //订单自动发货
                            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAutomaticDelivery, JsonConvert.SerializeObject(order));
                        }
                    }
 
                    //用户升级处理
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.UserUpGrade, JsonConvert.SerializeObject(order));
                    //发送支付成功信息,增加发送内容
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString(), JObject.FromObject(order));
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.SellerOrderNotice.ToString(), JObject.FromObject(order));
                    //易联云打印机打印
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(order));
                }
                else
                {
                    if (!string.IsNullOrEmpty(planorderId))
                    {
                        //查询计划订单
                      var planOrder = await _planOrderServices.QueryByIdAsync(planorderId);
                        //上面保存好订单表,下面保存订单的其他信息
                        if (planOrder == null || planOrder.isdelete == true)
                        {
                            _unitOfWork.RollbackTran();
                            jm.msg = "计划订单获取失败";
                            return jm;
                        }
                        //if (planOrder.status != 2)
                        //{
                        //    _unitOfWork.RollbackTran();
                        //    jm.msg = "计划订单没有锁单";
                        //    return jm;
                        //}
 
                        if ((planOrder.keYongAmount - planOrder.huaFeiAmount - order.orderAmount)<0)
                        {
                            _unitOfWork.RollbackTran();
                            jm.msg = "计划订单可用余额不足";
                            return jm;
                        }
                        planOrder.huaFeiAmount = planOrder.huaFeiAmount + order.orderAmount;
                        //修改计划订单的已花费金额
                       var crr  = await _planOrderServices.UpdateAsync(planOrder);
 
 
 
                        //创建支付单
                        var billPayments = new CoreCmsBillPayments();
                        billPayments.paymentId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.支付单编号);
                        billPayments.sourceId = order.orderId;
                        billPayments.money = order.orderAmount;
                        billPayments.userId = userId;
                        billPayments.type = order.orderType;
                        billPayments.status = (int)GlobalEnumVars.BillPaymentsStatus.Payed;
                        billPayments.paymentCode = GlobalEnumVars.PaymentsTypes.planorderpay.ToString();
                        billPayments.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1";
                        billPayments.payedMsg = "计划订单直接支付成功";
                        billPayments.parameters = "";
                        billPayments.createTime = DateTime.Now;
                        billPayments.updateTime = DateTime.Now;
 
 
                        await _billPaymentsServices.InsertAsync(billPayments);
 
                        //调整直接支付成功
                        await _dal.UpdateAsync(p => new CoreCmsOrder()
                        {
                            payedAmount = order.orderAmount,
                            paymentTime = DateTime.Now,
                            updateTime = DateTime.Now,
                            paymentCode = GlobalEnumVars.PaymentsTypes.planorderpay.ToString(),
                            payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes,
                            orderAmount = order.orderAmount
                        }, p => p.orderId == order.orderId);
 
                        //记录订单日志
                        orderLog = new CoreCmsOrderLog
                        {
                            userId = userId,
                            orderId = order.orderId,
                            type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_PAY,
                            msg = "计划订单直接支付成功",
                            data = JsonConvert.SerializeObject(order),
                            createTime = DateTime.Now
                        };
                        await _orderLogServices.InsertAsync(orderLog);
 
 
                        //拆单
                        //var jms = await Chaidan(order.orderId);
                        //var orderchai = await _dal.QueryByClauseAsync(p => p.orderId == order.orderId);
                        //orderchai.Orderitems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
                        //如果是门店自提,应该自动跳过发货,生成提货单信息,使用提货单核销。
                        if (order.receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
                        {
                            var allConfigs = await _settingServices.GetConfigDictionaries();
                            var storeOrderAutomaticDelivery = CommonHelper
                                .GetConfigDictionary(allConfigs, SystemSettingConstVars.StoreOrderAutomaticDelivery)
                                .ObjectToInt(1);
                            if (storeOrderAutomaticDelivery == 1)
                            {
                                //订单自动发货
                                await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAutomaticDelivery, JsonConvert.SerializeObject(order));
                            }
                        }
 
                        //结佣处理
                        await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAgentOrDistribution, JsonConvert.SerializeObject(order));
 
                        //用户升级处理
                        await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.UserUpGrade, JsonConvert.SerializeObject(order));
                        //发送支付成功信息,增加发送内容
                        await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString(), JObject.FromObject(order));
                        await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.SellerOrderNotice.ToString(), JObject.FromObject(order));
                        //易联云打印机打印
                        await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(order));
 
                    }
                    else
                    {
                        await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString(), JObject.FromObject(order));
                    }
                      
                }
 
                _unitOfWork.CommitTran();
 
                jm.status = true;
                jm.data = order;
 
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                jm.status = false;
                jm.otherData = e.ToString();
            }
            return jm;
        }
 
        #endregion
 
        #region 生成订单的收货信息
        /// <summary>
        /// 生成订单的收货信息
        /// </summary>
        /// <param name="order">订单信息</param>
        /// <param name="receiptType">收货方式,1快递物流,2同城配送,3门店自提</param>
        /// <param name="ushipId">用户地址库序列</param>
        /// <param name="storeId">门店序列</param>
        /// <param name="ladingName">提货人姓名</param>
        /// <param name="ladingMobile">提货人联系方式</param>
        /// <returns></returns>
        private async Task<WebApiCallBack> FormatOrderDelivery(CoreCmsOrder order, int receiptType, int ushipId, int storeId, string ladingName, string ladingMobile)
        {
            var res = new WebApiCallBack() { methodDescription = "生成订单的收货信息" };
 
            var areaId = 0;
            if (receiptType == (int)GlobalEnumVars.OrderReceiptType.Logistics || receiptType == (int)GlobalEnumVars.OrderReceiptType.IntraCityService)
            {
                //快递邮寄
                var userShipInfo = await _userShipServices.QueryByClauseAsync(p => p.userId == order.userId && p.id == ushipId);
                if (userShipInfo == null)
                {
                    res.data = 11050;
                    res.msg = GlobalErrorCodeVars.Code11050;
                    return res;
                }
                areaId = userShipInfo.areaId;
 
                //快递邮寄
                order.shipAreaId = userShipInfo.areaId;
                order.shipAddress = userShipInfo.street + " " + userShipInfo.address;
                order.shipName = userShipInfo.name;
                order.shipMobile = userShipInfo.mobile;
                order.shipCoordinate = userShipInfo.latitude + "," + userShipInfo.longitude;
 
                var ship = await _shipServices.GetShip(userShipInfo.areaId);
                if (ship != null)
                {
                    order.logisticsId = ship.id;
                    order.logisticsName = ship.name;
                    order.storeId = 0;
                }
            }
            else
            {
                //门店自提
                var storeInfo = await _storeServices.QueryByIdAsync(storeId);
                if (storeInfo == null)
                {
                    res.data = 11055;
                    res.msg = GlobalErrorCodeVars.Code11055;
                    return res;
                }
                areaId = storeInfo.areaId;
 
                //门店自提
                order.shipAreaId = storeInfo.areaId;
                order.shipAddress = storeInfo.address;
                order.shipName = ladingName;
                order.shipMobile = ladingMobile;
                order.storeId = storeId;
                order.logisticsId = 0;
 
            }
            res.status = true;
            res.msg = "订单的收货信息生成成功";
            res.data = areaId;
 
            return res;
        }
        #endregion
 
        #region 生成订单的时候,根据购物车信息生成订单信息及明细信息
 
        /// <summary>
        /// 生成订单的时候,根据购物车信息生成订单信息及明细信息
        /// </summary>
        /// <param name="order">订单数组</param>
        /// <param name="userId">用户id</param>
        /// <param name="cartIds">购物车信息</param>
        /// <param name="areaId">收货地区</param>
        /// <param name="point">使用积分</param>
        /// <param name="couponCode">使用优惠券</param>
        /// <param name="userShipId"></param>
        /// <param name="deliveryType">收货方式,1快递物流,2同城配送,3门店自提</param>
        /// <param name="groupId">团队明细</param>
        /// <returns>返回订单明细信息</returns>
        private async Task<WebApiCallBack> FormatOrder(CoreCmsOrder order, int userId, int[] cartIds, int areaId, int point,
            string couponCode, int userShipId = 0, int deliveryType = (int)GlobalEnumVars.OrderReceiptType.Logistics, int groupId = 0)
        {
            var res = new WebApiCallBack() { methodDescription = "生成订单信息及明细信息" };
 
            var cartModel = await _cartServices.GetCartInfos(userId, cartIds, order.orderType, areaId, point, couponCode, deliveryType, userShipId, groupId);
            if (!cartModel.status)
            {
                return cartModel;
            }
 
            if (cartModel.data is CartDto cartDto)
            {
                order.goodsAmount = cartDto.goodsAmount;
                order.orderAmount = cartDto.amount;
                if (order.orderAmount == 0)
                {
                    order.payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes;
                    order.paymentTime = DateTime.Now;
                }
                else
                {
                    order.payStatus = (int)GlobalEnumVars.OrderPayStatus.No;
                }
                order.costFreight = cartDto.costFreight;
                //优惠信息存储
                var promotionList = new Dictionary<int, WxNameTypeDto>();
                foreach (var item in cartDto.promotionList)
                {
                    if (item.Value.type == 2)
                    {
                        promotionList.Add(item.Key, item.Value);
                    }
                }
                order.promotionList = promotionList.Any() ? JsonConvert.SerializeObject(promotionList) : "";
                //积分使用情况
                order.point = cartDto.point;
                order.pointMoney = cartDto.pointExchangeMoney;
                order.weight = cartDto.weight;
                order.orderDiscountAmount = cartDto.orderPromotionMoney > 0 ? cartDto.orderPromotionMoney : 0;
                order.goodsDiscountAmount = cartDto.goodsPromotionMoney > 0 ? cartDto.goodsPromotionMoney : 0;
                order.couponDiscountAmount = cartDto.couponPromotionMoney;
                order.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1";
                //以上保存了订单主体表信息,以下生成订单明细表
                var items = FormatOrderItems(cartDto.list, order.orderId);
                if (!items.Any())
                {
                    res.status = false;
                    res.data = 10000;
                    res.msg = GlobalErrorCodeVars.Code10000;
                    return res;
                }
                res.status = true;
                res.data = items;
            }
 
            return res;
        }
 
        #endregion
 
        #region 根据购物车的明细生成订单明细
 
        /// <summary>
        /// 根据购物车的明细生成订单明细
        /// </summary>
        private static List<CoreCmsOrderItem> FormatOrderItems(List<CartProducts> list, string orderId)
        {
            var res = new List<CoreCmsOrderItem>();
            foreach (var item in list)
            {
                if (item.isSelect == false) continue;
                var model = new CoreCmsOrderItem
                {
                    orderId = orderId,
                    goodsId = (int)item.products.goodsId,
                    productId = item.products.id,
                    sn = item.products.sn,
                    bn = item.products.bn,
                    name = item.products.name,
                    price = (decimal)item.products.price,
                    costprice = (decimal)item.products.costprice,
                    mktprice = (decimal)item.products.mktprice,
                    imageUrl = item.products.images,
                    nums = item.nums,
                    amount = item.products.amount,
                    promotionAmount = item.products.promotionAmount > 0 ? item.products.promotionAmount : 0,
                    weight = Math.Round(item.weight * item.nums, 2),
                    sendNums = 0,
                    addon = item.products.spesDesc,
                    createTime = DateTime.Now,
                     CustomizableMoney= item.CustomizableMoney,
                    IsCustomizable = item.isCustomizable,
 
                };
                if (item.products.promotionList.Count > 0)
                {
                    var promotionList = new Dictionary<int, WxNameTypeDto>();
                    foreach (var proDto in item.products.promotionList)
                    {
                        if (proDto.Value.type == 2)
                        {
                            promotionList.Add(proDto.Key, proDto.Value);
                        }
                    }
                    model.promotionList = JsonConvert.SerializeObject(promotionList);
                }
                res.Add(model);
            }
            return res;
        }
        #endregion
 
        #region 获取单个订单所有详情
        /// <summary>
        /// 根据订单编号获取单个订单所有详情
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderInfoByOrderId(string id, int userId = 0, int aftersaleLevel = 0)
        {
            var jm = new WebApiCallBack();
 
            var order = new CoreCmsOrder();
            order = userId > 0
                ? await _dal.QueryByClauseAsync(p => p.orderId == id && p.userId == userId)
                : await _dal.QueryByClauseAsync(p => p.orderId == id);
            if (order == null)
            {
                jm.msg = "获取订单失败";
                return jm;
            }
            //订单详情(子货品数据)
            order.items = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
            if (order.items.Any())
            {
                order.items.ForEach(p =>
                {
                    if (!string.IsNullOrEmpty(p.promotionList))
                    {
                        var jobj = JObject.Parse(p.promotionList);
                        p.promotionObj = jobj.Values();
                        //if (jobj.Values().Any())
                        //{
                        //    p.promotionObj = jobj.Values().FirstOrDefault();
                        //}
                    }
                });
            }
 
            //获取相关状态描述说明转换
            order.statusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderStatus>(order.status);
            order.payStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderPayStatus>(order.payStatus);
            order.shipStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderShipStatus>(order.shipStatus);
            order.sourceText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.Source>(order.source);
            order.typeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderType>(order.orderType);
            order.confirmStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderConfirmStatus>(order.confirmStatus);
            order.taxTypeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderTaxType>(order.taxType);
            order.paymentCodeText = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(order.paymentCode);
            //获取日志
            order.orderLog = await _orderLogServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
            if (order.orderLog.Any())
            {
                order.orderLog.ForEach(p =>
                {
                    p.typeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderLogTypes>(p.type);
                });
            }
 
            //用户信息
            order.user = await _userServices.QueryByIdAsync(order.userId);
            if (order.user != null)
            {
                order.user.passWord = "";
            }
            //支付单
            order.paymentItem = await _billPaymentsServices.QueryListByClauseAsync(p => p.sourceId == order.orderId);
            //退款单
            order.refundItem = await _billRefundServices.QueryListByClauseAsync(p => p.sourceId == order.orderId);
            //提货单
            order.ladingItem = await _billLadingServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
            //退货单
            order.returnItem = await _billReshipServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
            //售后单
            order.aftersalesItem = await _billAftersalesServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
            //发货单
            order.delivery = await _billDeliveryServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
            if (order.delivery != null && order.delivery.Any())
            {
                foreach (var item in order.delivery)
                {
                    if (item.logiCode == "Distributor")
                    {
                        //是供应商送货
                     var ds=   await  _unitOfWork.GetDbClient().Queryable<CoreCmsDistribution>().Where(x => x.id == item.sendDistributionID).FirstAsync();
                        if(ds==null)
                        {
                            item.logiName = "经销商配送,但是经销商已经退出或者不存在";
                        }
                        else
                        {
                            item.logiName = $"经销商配送({ds.schoolName}--{ds.name})";
                        }
                        item.distributionAcceptStr = item.sendDistributionAccept?.GetDescription() ?? "经销商未确认接受配送";
 
                    }
                    else
                    {
                        var outFirstAsync = await _logisticsServices.QueryByClauseAsync(p => p.logiCode == item.logiCode);
                        item.logiName = outFirstAsync != null ? outFirstAsync.logiName : item.logiCode;
                    }
                }
            }
            //获取提货门店
            if (order.storeId != 0)
            {
                order.store = await _storeServices.QueryByIdAsync(order.storeId);
                if (order.store != null)
                {
                    var areaBack = await _areaServices.GetAreaFullName(order.store.areaId);
                    order.store.allAddress = areaBack.status ? areaBack.data + order.store.address : order.store.address;
                }
            }
            //获取配送方式
            if (order.logisticsId > 0)
            {
                order.logistics = await _shipServices.QueryByIdAsync(order.logisticsId);
            }
            //获取订单状态及中文描述
            order.globalStatus = GetGlobalStatus(order);
 
            order.globalStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderAllStatusType>(order.globalStatus);
            //收货地区三级地址
            var shipAreaBack = await _areaServices.GetAreaFullName(order.shipAreaId);
 
            order.shipAreaName = shipAreaBack.status ? shipAreaBack.data.ToString() : "";
 
            //获取支付方式
            var pm = await _paymentsServices.QueryByClauseAsync(p => p.code == order.paymentCode);
            order.paymentName = pm != null ? pm.name : "未知支付方式";
            //优惠券
            //if (!string.IsNullOrEmpty(order.coupon))
            //{
            //    order.couponObj = await _couponServices.QueryWithAboutAsync(p => p.usedId == order.orderId);
            //}
            order.couponObj = await _couponServices.QueryWithAboutAsync(p => p.usedId == order.orderId);
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            //获取该状态截止时间
            switch (order.globalStatus)
            {
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_PAYMENT: ////待付款
                    var cancelTime = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderCancelTime).ObjectToInt(1) * 86400;
                    var dt = order.createTime.AddSeconds(cancelTime);
                    order.remainingTime = dt;
                    order.remaining = CommonHelper.GetRemainingTime(dt);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_RECEIPT: //待收货
                    var autoSignTime = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderAutoSignTime).ObjectToInt(1) * 86400;
                    var dtautoSignTime = order.createTime.AddSeconds(autoSignTime);
                    order.remainingTime = dtautoSignTime;
                    order.remaining = CommonHelper.GetRemainingTime(dtautoSignTime);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_EVALUATE:  //待评价
                    var autoEvalTime = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderAutoEvalTime).ObjectToInt(1) * 86400;
                    var dtautoEvalTime = order.createTime.AddSeconds(autoEvalTime);
                    order.remainingTime = dtautoEvalTime;
                    order.remaining = CommonHelper.GetRemainingTime(dtautoEvalTime);
                    break;
 
                default:
                    order.remaining = string.Empty;
                    order.remainingTime = null;
                    break;
 
            }
            //支付单
            if (order.paymentItem != null && order.paymentItem.Any())
            {
                foreach (var item in order.paymentItem)
                {
                    item.paymentCodeName = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(item.paymentCode);
                    item.statusName = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillPaymentsStatus>(item.status);
                }
            }
            //退款单
            if (order.refundItem != null && order.refundItem.Any())
            {
                foreach (var item in order.refundItem)
                {
                    item.paymentCodeName = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(item.paymentCode);
                    item.statusName = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillRefundStatus>(item.status);
                }
            }
            //发货单
            if (order.delivery != null && order.delivery.Any())
            {
                foreach (var item in order.delivery)
                {
                    var logisticsModel = await _logisticsServices.GetLogiInfo(item.logiCode);
                    if (logisticsModel.status)
                    {
                        var logisticsData = logisticsModel.data as CoreCmsLogistics;
                        item.logiName = logisticsData.logiName;
                    }
                    var areaModel = await _areaServices.GetAreaFullName(item.shipAreaId);
                    if (areaModel.status)
                    {
                        item.shipAreaIdName = areaModel.data as string;
                    }
                }
            }
            //提货单
            if (order.ladingItem != null && order.ladingItem.Any())
            {
                foreach (var item in order.ladingItem)
                {
                    var storeModel = await _storeServices.QueryByIdAsync(item.storeId);
                    item.storeName = storeModel != null ? storeModel.storeName : "";
                    item.statusName = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillLadingStatus>(item.status ? 2 : 1);
 
                    if (item.clerkId != 0)
                    {
                        var userModel = await _userServices.QueryByIdAsync(item.clerkId);
                        if (userModel != null)
                        {
                            item.clerkIdName = !string.IsNullOrEmpty(userModel.nickName) ? userModel.nickName : userModel.mobile;
                        }
                    }
                }
            }
            //退货单
            if (order.returnItem != null && order.returnItem.Any())
            {
                foreach (var item in order.returnItem)
                {
                    var logisticsModel = await _logisticsServices.GetLogiInfo(item.logiCode);
                    if (logisticsModel.status)
                    {
                        var logisticsData = logisticsModel.data as CoreCmsLogistics;
                        item.logiName = logisticsData.logiName;
                    }
                    item.statusName = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillReshipStatus>(item.status);
                }
            }
            //售后单取当前活动的收货单
            if (order.aftersalesItem != null && order.aftersalesItem.Any())
            {
                foreach (var item in order.aftersalesItem)
                {
                    order.billAftersalesId = item.aftersalesId;
                    //如果售后单里面有待审核的活动售后单,那就直接拿这条
                    if (item.status == (int)GlobalEnumVars.BillAftersalesStatus.WaitAudit) break;
                }
            }
            //把退款金额和退货商品查出来判断是否能进行售后
            AfterSalesVal(order, aftersaleLevel);
            //促销信息
            if (!string.IsNullOrEmpty(order.promotionList))
            {
                order.promotionObj = JsonConvert.DeserializeObject(order.promotionList);
            }
 
            //发票信息
            var invoiceModel = await _invoiceServices.GetOrderInvoiceInfo(order.orderId);
            if (invoiceModel is { status: true })
            {
                order.invoice = invoiceModel.data;
            }
            else
            {
                order.invoice = new
                {
                    type = order.taxType,
                    title = order.taxTitle,
                    taxNumber = order.taxCode
                };
            }
 
            jm.status = true;
            jm.data = order;
            jm.msg = GlobalConstVars.GetDataSuccess;
 
            return jm;
        }
 
        #endregion
 
        #region 把退款金额和退货商品查出来判断是否能进行售后
        /// <summary>
        /// 把退款金额和退货商品查出来判断是否能进行售后
        /// </summary>
        /// <param name="order"></param>
        /// <param name="aftersaleLevel">取售后单的时候,售后单的等级,0:待审核的和审核通过的售后单,1未审核的,2审核通过的</param>
        public void AfterSalesVal(CoreCmsOrder order, int aftersaleLevel)
        {
            var addAftersalesStatus = false;
            var res = _billAftersalesServices.OrderToAftersales(order.orderId, aftersaleLevel);
            var resData = res.data as OrderToAfterSalesDto;
            //已经退过款的金额
            order.refunded = resData.refundMoney;
            //算退货商品数量
            foreach (var item in order.items)
            {
                if (resData.reshipGoods.ContainsKey(item.id))
                {
                    item.reshipNums = resData.reshipGoods[item.id].reshipNums;
                    item.reshipedNums = resData.reshipGoods[item.id].reshipedNums;
 
                    //商品总数量 - 已发货数量 - 未发货的退货数量(总退货数量减掉已发货的退货数量)
                    if (!addAftersalesStatus && (item.nums - item.reshipNums) > 0)//如果没退完,就可以再次发起售后
                    {
                        addAftersalesStatus = true;
                    }
                }
                else
                {
                    item.reshipNums = 0;  //退货商品
                    item.reshipedNums = 0;//已发货的退货商品
                    if (!addAftersalesStatus) //没退货,就能发起售后
                    {
                        addAftersalesStatus = true;
                    }
                }
            }
            //商品没退完或没退,可以发起售后,但是订单状态不对的话,也不能发起售后
            if (order.payStatus == (int)GlobalEnumVars.OrderPayStatus.No || order.status != (int)GlobalEnumVars.OrderStatus.Normal)
            {
                addAftersalesStatus = false;
            }
            order.addAftersalesStatus = addAftersalesStatus;
        }
 
        #endregion
 
        #region 获取订单不同状态的数量
        /// <summary>
        /// 获取订单不同状态的数量
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="ids"></param>
        /// <param name="isAfterSale"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderStatusNum(int userId, int[] ids, bool isAfterSale = false)
        {
            var jm = new WebApiCallBack();
 
            var data = new Dictionary<string, int>();
            foreach (var id in ids)
            {
                var count = await OrderCount(id, userId);
                data.Add(id.ToString(), count);
            }
            if (isAfterSale)
            {
                var number = await _billAftersalesServices.GetUserAfterSalesNum(p => p.userId == userId, true);
                data.Add("isAfterSale", number);
            }
            else
            {
                data.Add("isAfterSale", 0);
            }
            jm.status = true;
            jm.data = data;
 
            return jm;
        }
 
 
        /// <summary>
        /// 订单数量统计
        /// </summary>
        /// <param name="type"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<int> OrderCount(int type = 0, int userId = 0)
        {
            var count = 0;
            var where = GetReverseStatus(type);
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
 
            count = await _dal.GetCountAsync(where);
            return count;
 
        }
 
 
        #endregion
 
        #region 获取订单全局状态
        /// <summary>
        /// 获取订单全局状态
        /// </summary>
        /// <param name="orderInfo">订单数据</param>
        /// <returns></returns>
        public static int GetGlobalStatus(CoreCmsOrder orderInfo)
        {
            var status = 0;
            if (orderInfo.status == (int)GlobalEnumVars.OrderStatus.Complete)
            {
                status = (int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED; //已完成
            }
            else if (orderInfo.status == (int)GlobalEnumVars.OrderStatus.Cancel)
            {
                status = (int)GlobalEnumVars.OrderAllStatusType.ALL_CANCEL; //已取消
            }
            else if (orderInfo.status == (int)GlobalEnumVars.OrderStatus.Normal)
            {
                if (orderInfo.payStatus == (int)GlobalEnumVars.OrderPayStatus.No)
                {
                    status = (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_PAYMENT;//待付款
                }
                else
                {
                    if (orderInfo.shipStatus == (int)GlobalEnumVars.OrderShipStatus.No || orderInfo.shipStatus == (int)GlobalEnumVars.OrderShipStatus.PartialYes)
                    {
                        status = (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_DELIVERY;//待发货
 
                    }
                    else if ((orderInfo.shipStatus == (int)GlobalEnumVars.OrderShipStatus.Yes || orderInfo.shipStatus == (int)GlobalEnumVars.OrderShipStatus.PartialYes) && orderInfo.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ReceiptNotConfirmed)
                    {
                        status = (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_RECEIPT;//待收货
 
                    }
                    else if (orderInfo.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No && orderInfo.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt && orderInfo.isComment == false)
                    {
                        status = (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_EVALUATE;//待评价
                    }
                    else if (orderInfo.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No && orderInfo.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt && orderInfo.isComment == true)
                    {
                        status = (int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED_EVALUATE;//已评价
 
                    }
                }
            }
            return status;
        }
        #endregion
 
        #region 获取订单状态反查
        /// <summary>
        /// 获取订单状态反查
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public Expression<Func<CoreCmsOrder, bool>> GetReverseStatus(int status)
        {
            var where = PredicateBuilder.True<CoreCmsOrder>();
            switch (status)
            {
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_PAYMENT: //待付款
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
                    where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.No);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_DELIVERY: //待发货
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
                    where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No);
                    where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.No || p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.PartialYes);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_RECEIPT: //待收货
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
                    where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No);
                    where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.Yes || p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.PartialYes);
                    where = where.And(p => p.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ReceiptNotConfirmed);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_EVALUATE: //待评价
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
                    where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No);
                    where = where.And(p => p.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No);
                    where = where.And(p => p.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
                    where = where.And(p => p.isComment == false);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED_EVALUATE: //已评价
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
                    where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No);
                    where = where.And(p => p.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No);
                    where = where.And(p => p.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
                    where = where.And(p => p.isComment == true);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_CANCEL: //已取消
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Cancel);
                    where = where.And(p => p.isdel == false);
                    break;
                case (int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED: //已完成
                    where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Complete);
                    where = where.And(p => p.isdel == false);
                    break;
                default:
                    where = where.And(p => p.isdel == false);
                    break;
            }
            return where;
        }
 
        #endregion
 
        #region 获取订单列表微信小程序
        /// <summary>
        /// 获取订单列表微信小程序
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderList(int status = -1, int userId = 0, int page = 1, int limit = 5)
        {
            var jm = new WebApiCallBack { status = true };
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
 
            if (status > -1)
            {
                where = GetReverseStatus(status);
            }
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
            var list = await _dal.QueryPageAsync(where, p => p.createTime, OrderByType.Desc, page, limit);
 
            if (list.Any())
            {
                foreach (var order in list)
                {
                    //获取相关状态描述说明转换
                    order.statusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderStatus>(order.status);
                    order.payStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderPayStatus>(order.payStatus);
                    order.shipStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderShipStatus>(order.shipStatus);
                    order.sourceText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.Source>(order.source);
                    order.typeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderType>(order.orderType);
                    order.confirmStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderConfirmStatus>(order.confirmStatus);
                    order.taxTypeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderTaxType>(order.taxType);
                    order.paymentCodeText = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(order.paymentCode);
                }
            }
            jm.data = new
            {
                list,
                count = list.TotalCount,
                page,
                limit,
                status
            };
 
            return jm;
        }
 
 
        #endregion
 
        #region 商家获取订单列表-微信小程序
        /// <summary>
        /// 商家获取订单列表-微信小程序
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderPageByMerchant(string dateType, string[] date, int status = 0, int receiptType = 0, int storeId = 0, int page = 1, int limit = 5)
        {
            var jm = new WebApiCallBack { status = true };
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            @where = status > 0 ? GetReverseStatus(status) : @where.And(p => p.isdel == false);
 
 
            if (storeId > 0)
            {
                where = where.And(p => p.storeId == storeId);
            }
 
            if (receiptType > 0)
            {
                where = where.And(p => p.receiptType == receiptType);
 
            }
 
 
            DateTime dt = DateTime.Now;
            if (dateType == "today")
            {
                var startTime = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
                var entTime = new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59);
                where = where.And(p => p.createTime > startTime && p.createTime < entTime);
            }
            else if (dateType == "yesterday")
            {
                var yesterday = dt.AddDays(-1);
                var startTime = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 0, 0, 0);
                var entTime = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 23, 59, 59);
                where = where.And(p => p.createTime > startTime && p.createTime < entTime);
            }
            else if (dateType == "week")
            {
                int dayOfWeek = -1 * (int)dt.Date.DayOfWeek;
                DateTime weekStartTime = dt.AddDays(dayOfWeek + 1);//取本周一
                if (dayOfWeek == 0) weekStartTime = weekStartTime.AddDays(-7);//如果今天是周日,则开始时间是上周一
                var weekEndTime = weekStartTime.AddDays(7);
 
                var startTime = new DateTime(weekStartTime.Year, weekStartTime.Month, weekStartTime.Day, 0, 0, 0);
                var entTime = new DateTime(weekEndTime.Year, weekEndTime.Month, weekEndTime.Day, 23, 59, 59);
 
                where = where.And(p => p.createTime > startTime && p.createTime < entTime);
            }
            else if (dateType == "month")
            {
                //本月第一天时间      
                DateTime dtFirst = dt.AddDays(1 - (dt.Day));
                dtFirst = new DateTime(dtFirst.Year, dtFirst.Month, dtFirst.Day, 0, 0, 0);
 
                //获得某年某月的天数    
                int dayCount = DateTime.DaysInMonth(dt.Date.Year, dt.Date.Month);
                //本月最后一天时间    
                DateTime dtLast = dtFirst.AddDays(dayCount - 1);
 
                var startTime = new DateTime(dtFirst.Year, dtFirst.Month, dtFirst.Day, 0, 0, 0);
                var entTime = new DateTime(dtLast.Year, dtLast.Month, dtLast.Day, 23, 59, 59);
 
 
                where = where.And(p => p.createTime > startTime && p.createTime < entTime);
            }
            else if (dateType == "custom" && date is { Length: 2 })
            {
                var st = date[0].ObjectToDate();
                var et = date[1].ObjectToDate();
 
                var startTime = new DateTime(st.Year, st.Month, st.Day, 0, 0, 0);
                var entTime = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);
 
                where = where.And(p => p.createTime > startTime && p.createTime < entTime);
            }
 
            var pages = await _dal.QueryPageAsync(where, p => p.createTime, OrderByType.Desc, page, limit);
 
            if (pages.Any())
            {
                foreach (var order in pages)
                {
                    //获取相关状态描述说明转换
                    order.statusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderStatus>(order.status);
                    order.payStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderPayStatus>(order.payStatus);
                    order.shipStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderShipStatus>(order.shipStatus);
                    order.sourceText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.Source>(order.source);
                    order.typeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderType>(order.orderType);
                    order.confirmStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderConfirmStatus>(order.confirmStatus);
                    order.taxTypeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderTaxType>(order.taxType);
                    order.paymentCodeText = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(order.paymentCode);
                }
            }
 
 
            var totalMoney = await _dal.GetSumAsync(where, p => p.payedAmount, true);
 
            jm.data = new
            {
                pages,
                pages.TotalCount,
                pages.PageSize,
                pages.HasNextPage,
                pages.HasPreviousPage,
                pages.PageIndex,
                pages.TotalPages,
                totalMoney
            };
 
            return jm;
        }
 
        #endregion
 
        #region 商家获取订单列表通过检索手机号码和订单号-微信小程序
        /// <summary>
        /// 商家获取订单列表通过检索手机号码和订单号-微信小程序
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderPageByMerchantSearch(string keyword, int status = 0, int receiptType = 0, int storeId = 0, int page = 1, int limit = 5)
        {
            var jm = new WebApiCallBack { status = true };
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            @where = status > 0 ? GetReverseStatus(status) : @where.And(p => p.isdel == false);
 
            if (storeId > 0)
            {
                where = where.And(p => p.storeId == storeId);
            }
            if (receiptType > 0)
            {
                where = where.And(p => p.receiptType == receiptType);
 
            }
 
            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(p =>
                    p.shipMobile.Contains(keyword) || p.shipName.Contains(keyword) || p.orderId.Contains(keyword));
            }
 
            var pages = await _dal.QueryPageAsync(where, p => p.createTime, OrderByType.Desc, page, limit);
 
            if (pages.Any())
            {
                foreach (var order in pages)
                {
                    //获取相关状态描述说明转换
                    order.statusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderStatus>(order.status);
                    order.payStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderPayStatus>(order.payStatus);
                    order.shipStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderShipStatus>(order.shipStatus);
                    order.sourceText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.Source>(order.source);
                    order.typeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderType>(order.orderType);
                    order.confirmStatusText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderConfirmStatus>(order.confirmStatus);
                    order.taxTypeText = EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.OrderTaxType>(order.taxType);
                    order.paymentCodeText = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.PaymentsTypes>(order.paymentCode);
                }
            }
 
            var totalMoney = await _dal.GetSumAsync(where, p => p.payedAmount, true);
 
            jm.data = new
            {
                pages,
                pages.TotalCount,
                pages.PageSize,
                pages.HasNextPage,
                pages.HasPreviousPage,
                pages.PageIndex,
                pages.TotalPages,
                totalMoney
            };
            return jm;
        }
 
        #endregion
 
        #region 订单支付
 
        /// <summary>
        /// 订单支付
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="paymentCode">支付方式</param>
        /// <param name="billPaymentInfo">支付单据</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> Pay(string orderId, string paymentCode, CoreCmsBillPayments billPaymentInfo)
        {
            var jm = new WebApiCallBack() { msg = "订单支付失败" };
 
            //获取订单
            var order = await _dal.QueryByClauseAsync(p => p.orderId == orderId && p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            if (order == null)
            {
                return jm;
            }
            if (order.payStatus == (int)GlobalEnumVars.OrderPayStatus.Yes || order.payStatus == (int)GlobalEnumVars.OrderPayStatus.PartialNo || order.payStatus == (int)GlobalEnumVars.OrderPayStatus.Refunded)
            {
                jm.msg = "订单" + orderId + "支付失败,订单已经支付";
                jm.data = order;
            }
            else
            {
                //赋值,用于传递完整数据到事件处理中
                order.payedAmount = order.orderAmount;
                order.paymentTime = DateTime.Now;
                order.updateTime = DateTime.Now;
                order.paymentCode = paymentCode;
                order.payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes;
 
                var isUpdate = await _dal.UpdateAsync(p => new CoreCmsOrder()
                {
                    paymentCode = paymentCode,
                    payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes,
                    paymentTime = order.paymentTime,
                    payedAmount = order.orderAmount,
                    updateTime = order.updateTime
                }, p => p.orderId == order.orderId);
                jm.data = isUpdate;
 
                if (isUpdate)
                {
                    order.payStatus = (int)GlobalEnumVars.OrderPayStatus.Yes;
                    jm.status = true;
                    jm.msg = "订单支付成功";
 
                    //发票存储
                    if (order.taxType != (int)GlobalEnumVars.OrderTaxType.No)
                    {
                        //组装发票信息
                        var taxInfo = new CoreCmsInvoice
                        {
                            category = (int)GlobalEnumVars.OrderTaxCategory.Order,
                            sourceId = order.orderId,
                            userId = order.userId,
                            type = order.taxType,
                            title = order.taxTitle,
                            taxNumber = order.taxCode,
                            amount = order.orderAmount,
                            status = (int)GlobalEnumVars.OrderTaxStatus.No,
                            createTime = DateTime.Now
                        };
 
                        await _invoiceServices.InsertAsync(taxInfo);
                    }
 
                    //拆单
                    //var jms = await Chaidan(order.orderId);
                    //var orderchai = await _dal.QueryByClauseAsync(p => p.orderId == order.orderId);
                    //orderchai.Orderitems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
 
 
 
                    //如果是门店自提,应该自动跳过发货,生成提货单信息,使用提货单核销。
                    if (order.receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
                    {
                        var allConfigs = await _settingServices.GetConfigDictionaries();
                        var storeOrderAutomaticDelivery = CommonHelper
                            .GetConfigDictionary(allConfigs, SystemSettingConstVars.StoreOrderAutomaticDelivery)
                            .ObjectToInt(1);
                        if (storeOrderAutomaticDelivery == 1)
                        {
                            //订单自动发货
                            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAutomaticDelivery, JsonConvert.SerializeObject(order));
                        }
                    }
 
                    //新版自定义交易组件已经不需要同步订单支付状态。
                    //if (order.orderType == (int)GlobalEnumVars.OrderType.Common && order.scene > 0)
                    //{
                    //    order.paymentItem = new List<CoreCmsBillPayments> { billPaymentInfo };
                    //    //自定义交易组件同步
                    //    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.TransactionComponentPayOrderSync, JsonConvert.SerializeObject(order));
                    //}
 
                    //结佣处理
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAgentOrDistribution, JsonConvert.SerializeObject(order));
                    //易联云打印机打印
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(order));
 
                    //发送支付成功信息,增加发送内容
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString(), JObject.FromObject(order));
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.SellerOrderNotice.ToString(), JObject.FromObject(order));
 
                    //用户升级处理
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.UserUpGrade, JsonConvert.SerializeObject(order));
 
                }
            }
            //订单记录
            var orderLog = new CoreCmsOrderLog
            {
                orderId = order.orderId,
                userId = order.userId,
                type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_PAY,
                msg = jm.msg,
                data = JsonConvert.SerializeObject(jm),
                createTime = DateTime.Now
            };
            await _orderLogServices.InsertAsync(orderLog);
 
            return jm;
        }
        #endregion
 
        #region 取消订单
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> CancelOrder(string[] ids, int userId = 0)
        {
            var jm = new WebApiCallBack();
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => ids.Contains(p.orderId));
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.No);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.No);
 
            var msg = "后台订单取消操作";
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
                msg = "订单取消操作";
            }
            var orderInfo = await _dal.QueryListByClauseAsync(where);
            if (orderInfo != null && orderInfo.Any())
            {
                //更改状态和库存
                foreach (var item in orderInfo)
                {
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        orderId = item.orderId,
                        userId = item.userId,
                        type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_CANCEL,
                        msg = msg,
                        data = JsonConvert.SerializeObject(orderInfo),
                        createTime = DateTime.Now
                    };
                    await _orderLogServices.InsertAsync(orderLog);
 
                    if (item.point > 0)
                    {
                        await _userPointLogServices.SetPoint(item.userId, item.point, (int)GlobalEnumVars.UserPointSourceTypes.PointCanCelOrder, "取消订单:" + item.orderId + "返还积分");
                    }
 
                    if (!string.IsNullOrEmpty(item.coupon))
                    {
                        await _couponServices.CancelReturnCoupon(item.coupon);
                    }
 
                }
                //状态修改
                await _dal.UpdateAsync(
                    p => new CoreCmsOrder()
                    {
                        status = (int)GlobalEnumVars.OrderStatus.Cancel,
                        updateTime = DateTime.Now
                    }, p => ids.Contains(p.orderId));
 
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => ids.Contains(p.orderId));
                //更改库存
                foreach (var item in orderItems)
                {
                    _goodsServices.ChangeStock(item.productId, GlobalEnumVars.OrderChangeStockType.cancel.ToString(), item.nums);
                }
 
                jm.status = true;
                jm.msg = "订单取消成功";
            }
            else
            {
                jm.msg = "订单取消失败";
            }
 
            return jm;
        }
        #endregion
 
        #region 后端根据订单状态生成不同的操作按钮
 
        /// <summary>
        /// 后端根据订单状态生成不同的操作按钮
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="payStatus">支付状态</param>
        /// <param name="shipStatus">发货状态</param>
        /// <param name="receiptType">收货方式</param>
        /// <param name="isDel">是否删除</param>
        /// <returns></returns>
        public string GetOperating(string orderId, int orderStatus, int payStatus, int shipStatus, int receiptType, bool isDel)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<button class='layui-btn layui-btn-primary layui-btn-xs view-order' lay-active='viewOrder' data-id='" + orderId + "'>查看</button><br>");
            //正常订单
            if (orderStatus == (int)GlobalEnumVars.OrderStatus.Normal)
            {
                if (payStatus == (int)GlobalEnumVars.OrderPayStatus.No)
                {
                    //html.Append("<a class='layui-btn layui-btn-xs pay-order' lay-active='payOrder' data-id='" + orderId + "'>支付</a><br>");
                    html.Append("<a class='layui-btn layui-btn-xs edit-order' lay-active='editOrder' data-id='" + orderId + "'>编辑</a><br>");
                    html.Append("<a class='layui-btn layui-btn-xs cancel-order' lay-active='cancelOrder' data-id='" + orderId + "'>取消</a><br>");
                }
                else
                {
                    if ((shipStatus == (int)GlobalEnumVars.OrderShipStatus.No || shipStatus == (int)GlobalEnumVars.OrderShipStatus.PartialYes))
                    {
                        html.Append("<a class='layui-btn layui-btn-xs edit-order' lay-active='editOrder' data-id='" + orderId + "'>编辑</a><br>");
                        html.Append("<a class='layui-btn layui-btn-xs ship-order' lay-active='shipOrder' data-id='" + orderId + "'>发货</a><br>");
 
                        if (receiptType == (int)GlobalEnumVars.OrderReceiptType.IntraCityService || receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
                        {
                            html.Append("<a class='layui-btn layui-btn-xs  layui-btn-normal seconds-ship-order' lay-active='secondsShipOrder' data-id='" + orderId + "'>秒发</a><br>");
                        }
                    }
                    else
                    {
                        html.Append("<a class='layui-btn layui-btn-xs complete-order' lay-active='completeOrder' data-id='" + orderId + "'>完成</a><br>");
                    }
                }
            }
            //已取消的订单
            if (orderStatus == (int)GlobalEnumVars.OrderStatus.Cancel && isDel == false)
            {
                html.Append("<a class='layui-btn layui-btn-danger layui-btn-xs del-order' lay-active='delOrder' data-id='" + orderId + "'>删除</a><br>");
            }
 
            //已取消的订单
            if (isDel == true)
            {
                html.Append("<a class='layui-btn layui-btn-warm layui-btn-xs restore-order' lay-active='restoreOrder' data-id='" + orderId + "'>还原</a><br>");
            }
 
            return html.ToString();
        }
        #endregion
 
        #region 构建多个需要发货的数据,和发货单密切关联
        /// <summary>
        /// 构建多个需要发货的数据,和发货单密切关联
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderShipInfo(string[] ids)
        {
            var jm = new WebApiCallBack { status = true };
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => ids.Contains(p.orderId));
 
            var orderInfo = await _dal.QueryListByClauseAsync(where);
            if (orderInfo == null || !orderInfo.Any())
            {
                jm.msg = "请选择订单";
                return jm;
            }
            var orderItems = await _orderItemServices.QueryListByClauseAsync(p => ids.Contains(p.orderId));
            var isStoreId = 0;//校验是普通快递收货,还是门店自提,这两种收货方式不能混着发
                              //更改状态和库存
            foreach (var item in orderInfo)
            {
                item.items = orderItems.Where(p => p.orderId == item.orderId).ToList();
 
                if (item.status != (int)GlobalEnumVars.OrderStatus.Normal)
                {
                    jm.status = false;
                    jm.msg = "订单号:" + item.orderId + "非正常状态不能发货。<br />";
                }
                else if (item.payStatus == (int)GlobalEnumVars.OrderPayStatus.No)
                {
                    jm.status = false;
                    jm.msg = "订单号:" + item.orderId + "未支付不能发货。<br />";
                }
                else if (item.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No && item.shipStatus != (int)GlobalEnumVars.OrderShipStatus.PartialYes)
                {
                    jm.status = false;
                    jm.msg = "订单号:" + item.orderId + "不是待发货和部分发货状态不能发货。<br />";
                }
                //校验,不能普通快递和门店自提,不能混发
                if (isStoreId != 0)
                {
                    if (isStoreId != item.storeId)
                    {
                        jm.status = false;
                        jm.msg = "门店自提订单和普通订单不能混合发货";
                        return jm;
                    }
                }
                else
                {
                    isStoreId = item.storeId;
                }
                //判断是否有未审核的售后单,如果有,就不能发货,已做拦截
                var isHaveBillAfterSales = await _billAftersalesServices.ExistsAsync(p =>
                    p.orderId == item.orderId &&
                    p.status == (int)GlobalEnumVars.BillAftersalesStatus.WaitAudit);
                if (isHaveBillAfterSales)
                {
                    jm.status = false;
                    jm.msg = "订单号:" + item.orderId + "有未审核的售后单,请先处理掉才能发货。";
                    return jm;
                }
                AfterSalesVal(item, 0);
            }
 
            if (!jm.status)
            {
                return jm;
            }
 
            var userIdArr = true;
            var userId = 0;
            var shipInfoArr = true;
            var shipInfoId = string.Empty;
 
 
 
            var newOrder = new AdminOrderShipResult()
            {
                orderId = ids,
                weight = 0,
                costFreight = 0,
                storeId = orderInfo[0].storeId,
                shipAreaId = orderInfo[0].shipAreaId,
                shipAddress = orderInfo[0].shipAddress,
                shipName = orderInfo[0].shipName,
                shipMobile = orderInfo[0].shipMobile,
                logisticsId = orderInfo[0].logisticsId,
                logisticsName = orderInfo[0].logisticsName,
                Coordinate= orderInfo[0].shipCoordinate,
                items = new List<CoreCmsOrderItem>(),
                orders = orderInfo  //把订单信息冗余上去
            };
            newOrder.memo = new List<string>();
 
            if (newOrder.logisticsId > 0)
            {
                newOrder.ship = await _shipServices.QueryByClauseAsync(p => p.id == newOrder.logisticsId);
            }
 
            foreach (var item in orderInfo)
            {
                //组合总重量
                newOrder.weight += item.weight;
                //组合总运费
                newOrder.costFreight += item.costFreight;
                //组合备注信息
                if (!string.IsNullOrEmpty(item.memo))
                {
                    newOrder.memo.Add(item.orderId + ":" + item.memo);
                }
 
                foreach (var orderItem in item.items)
                {
                    var model = newOrder.items.FirstOrDefault(p => p.productId == orderItem.productId);
                    if (model == null)
                    {
                        newOrder.items.Add(orderItem);
                    }
                    else
                    {
                        var index = newOrder.items.IndexOf(model);
                        newOrder.items[index].nums += orderItem.nums;//总数量
                        newOrder.items[index].weight += orderItem.weight;//总重量
                        newOrder.items[index].sendNums += orderItem.sendNums;//已发送数量
                        newOrder.items[index].reshipNums += orderItem.reshipNums;//退货数量
                    }
                }
                //判断是否有多个用户的订单
                if (userIdArr && userId == 0)
                {
                    userId = item.userId;
                }
                else
                {
                    if (userId != item.userId)
                    {
                        userIdArr = false;
                    }
                }
                //判断是否是多个收货地址
                if (shipInfoArr && shipInfoId == string.Empty)
                {
                    shipInfoId = item.shipAreaId + item.shipAddress;
                }
                else
                {
                    if (shipInfoId != item.shipAreaId + item.shipAddress)
                    {
                        shipInfoArr = false;
                    }
                }
            }
 
            //判断用户
            if (userIdArr == false) jm.msg += "多个用户订单";
            //判断多个收货地址
            if (shipInfoArr == false) jm.msg += "多个收货地址";
            //是否有警告
            if (string.IsNullOrEmpty(jm.msg))
            {
                //多地址多用户禁止 合并发货 20240605
 
                jm.msg = jm.msg + "。不可合并发货";
                jm.status = false;
                return jm;
               // jm.msg = "请注意!合并发货订单中存在:" + jm.msg + "。确定发货吗?";
            }
            jm.status = true;
            jm.data = newOrder;
 
            return jm;
        }
        #endregion
 
        #region 构建单个需要发货的数据,和发货单密切关联
        /// <summary>
        /// 构建单个需要发货的数据,和发货单密切关联
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetOrderShipInfo(string orderId)
        {
            var jm = new WebApiCallBack { status = true };
 
            var orderInfo = await _dal.QueryByClauseAsync(p => p.orderId == orderId);
            if (orderInfo == null)
            {
                jm.msg = "请选择订单";
                return jm;
            }
            orderInfo.items = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == orderId);
            var isStoreId = 0;//校验是普通快递收货,还是门店自提,这两种收货方式不能混着发
                              //更改状态和库存
 
            if (orderInfo.status != (int)GlobalEnumVars.OrderStatus.Normal)
            {
                jm.status = false;
                jm.msg = "订单号:" + orderInfo.orderId + "非正常状态不能发货。<br />";
            }
            else if (orderInfo.payStatus == (int)GlobalEnumVars.OrderPayStatus.No)
            {
                jm.status = false;
                jm.msg = "订单号:" + orderInfo.orderId + "未支付不能发货。<br />";
            }
            else if (orderInfo.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No && orderInfo.shipStatus != (int)GlobalEnumVars.OrderShipStatus.PartialYes)
            {
                jm.status = false;
                jm.msg = "订单号:" + orderInfo.orderId + "不是待发货和部分发货状态不能发货。<br />";
            }
            //校验,不能普通快递和门店自提,不能混发
            isStoreId = orderInfo.storeId;
 
            //判断是否有未审核的售后单,如果有,就不能发货,已做拦截
            var isHaveBillAfterSales = await _billAftersalesServices.ExistsAsync(p =>
                p.orderId == orderInfo.orderId &&
                p.status == (int)GlobalEnumVars.BillAftersalesStatus.WaitAudit);
            if (isHaveBillAfterSales)
            {
                jm.status = false;
                jm.msg = "订单号:" + orderInfo.orderId + "有未审核的售后单,请先处理掉才能发货。";
                return jm;
            }
            AfterSalesVal(orderInfo, 0);
 
            if (!jm.status)
            {
                return jm;
            }
 
            var newOrder = new AdminOrderShipOneResult()
            {
                orderId = orderId,
                weight = orderInfo.weight,
                costFreight = orderInfo.costFreight,
                storeId = orderInfo.storeId,
                shipAreaId = orderInfo.shipAreaId,
                shipAddress = orderInfo.shipAddress,
                shipName = orderInfo.shipName,
                shipMobile = orderInfo.shipMobile,
                logisticsId = orderInfo.logisticsId,
                logisticsName = orderInfo.logisticsName,
                items = new List<CoreCmsOrderItem>(),
                orderInfo = orderInfo,
                memo = orderInfo.memo
            };
 
            if (newOrder.logisticsId > 0)
            {
                newOrder.ship = await _shipServices.QueryByClauseAsync(p => p.id == newOrder.logisticsId);
            }
 
            //组合总运费
            foreach (var orderItem in orderInfo.items)
            {
                var model = newOrder.items.FirstOrDefault(p => p.productId == orderItem.productId);
                if (model == null)
                {
                    newOrder.items.Add(orderItem);
                }
                else
                {
                    var index = newOrder.items.IndexOf(model);
                    newOrder.items[index].nums += orderItem.nums;//总数量
                    newOrder.items[index].weight += orderItem.weight;//总重量
                    newOrder.items[index].sendNums += orderItem.sendNums;//已发送数量
                    newOrder.items[index].reshipNums += orderItem.reshipNums;//退货数量
                }
            }
 
            jm.status = true;
            jm.data = newOrder;
 
            return jm;
        }
        #endregion
 
        #region 发货改状态
        /// <summary>
        /// 发货改状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> EditShipStatus(string orderId, Dictionary<int, int> items)
        {
            var jm = new WebApiCallBack();
 
            //未发货,部分发货,部分退货状态(怕部分发货中的部分退货这种业务场景,所以加这个字段)
            var shipStatus = new[] { (int)GlobalEnumVars.OrderShipStatus.No, (int)GlobalEnumVars.OrderShipStatus.PartialNo, (int)GlobalEnumVars.OrderShipStatus.PartialYes };
            var orderItem = await _dal.QueryByClauseAsync(p => p.orderId == orderId && p.status == (int)GlobalEnumVars.OrderStatus.Normal && shipStatus.Contains(p.shipStatus));
            if (orderItem == null)
            {
                jm.msg = GlobalErrorCodeVars.Code10000;
                return jm;
            }
            //更新订单明细发货数量,并校验是否发完
            var isOver = await _orderItemServices.ship(orderId, items);
            if (isOver)
            {
                await _dal.UpdateAsync(
                    p => new CoreCmsOrder() { shipStatus = (int)GlobalEnumVars.OrderShipStatus.Yes },
                    p => p.orderId == orderId);
            }
            else
            {
                await _dal.UpdateAsync(
                    p => new CoreCmsOrder() { shipStatus = (int)GlobalEnumVars.OrderShipStatus.PartialYes },
                    p => p.orderId == orderId);
            }
            jm.status = true;
 
            return jm;
        }
        #endregion
 
        #region 订单批量发货
 
        /// <summary>
        /// 订单批量发货
        /// </summary>
        /// <param name="ids">订单标号</param>
        /// <param name="logiCode">物流公司编码</param>
        /// <param name="logiNo">物流单号</param>
        /// <param name="items">发货明细</param>
        /// <param name="shipName">收货人姓名</param>
        /// <param name="shipMobile">收货人电话</param>
        /// <param name="shipAddress">收货地址</param>
        /// <param name="memo">发货描述</param>
        /// <param name="storeId">店铺收货地址</param>
        /// <param name="shipAreaId">省市区id</param>
        /// <param name="deliveryCompanyId">第三方对接物流编码</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> BatchShip(string[] ids, string logiCode, string logiNo,
            Dictionary<int, int> items, string shipName, string shipMobile, string shipAddress, string memo, int storeId = 0, int shipAreaId = 0, string deliveryCompanyId = "", int? sendDistributionID = null)
        {
 
            var result = await _billDeliveryServices.BatchShip(ids, logiCode, logiNo, items, storeId, shipName, shipMobile, shipAreaId, shipAddress, memo, deliveryCompanyId,sendDistributionID);
            return result;
 
        }
        #endregion
 
        #region 订单单个发货
 
        /// <summary>
        /// 订单单个发货
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="logiCode">物流公司编码</param>
        /// <param name="logiNo">物流单号</param>
        /// <param name="items">发货明细</param>
        /// <param name="shipName">收货人姓名</param>
        /// <param name="shipMobile">收货人电话</param>
        /// <param name="shipAddress">收货地址</param>
        /// <param name="memo">发货描述</param>
        /// <param name="storeId">店铺收货地址</param>
        /// <param name="shipAreaId">省市区id</param>
        /// <param name="deliveryCompanyId">第三方对接物流编码</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> Ship(string orderId, string logiCode, string logiNo,
            Dictionary<int, int> items, string shipName, string shipMobile, string shipAddress, string memo, int storeId = 0, int shipAreaId = 0, string deliveryCompanyId = "", int? sendDistributionID = null)
        {
            var result = await _billDeliveryServices.Ship(orderId, logiCode, logiNo, items, storeId, shipName, shipMobile, shipAreaId, shipAddress, memo, deliveryCompanyId,sendDistributionID);
            return result;
 
        }
        #endregion
 
        #region 完成订单
 
        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="score">有序队列积分</param>
        /// <param name="remark"></param>
        /// <param name="source">来源/system(系统)/wxpost(微信消息推送)</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> CompleteOrder(string orderId, int score = 0, string remark = "后台订单完成操作", string source = "system")
        {
            var jm = new WebApiCallBack();
 
            //等待售后审核的订单,不自动操作完成。
            var billAftersalesCount = await _billAftersalesServices.GetCountAsync(p => p.orderId == orderId && p.status == (int)GlobalEnumVars.BillAftersalesStatus.WaitAudit);
 
            if (billAftersalesCount > 0)
            {
                jm.msg = "售后单未处理";
                return jm;
            }
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No && p.orderId == orderId);
            var orderInfo = await _dal.QueryByClauseAsync(where);
            if (orderInfo != null)
            {
                await _dal.UpdateAsync(p => new CoreCmsOrder() { status = (int)GlobalEnumVars.OrderStatus.Complete, updateTime = DateTime.Now }, p => p.orderId == orderId);
 
                //计算订单实际支付金额(要减去售后退款的金额)
                var money = orderInfo.payedAmount;
 
                //查询售后单
                var baList = await _billAftersalesServices.QueryListByClauseAsync(p =>
                    p.orderId == orderId && p.status == (int)GlobalEnumVars.BillAftersalesStatus.Success);
                if (baList != null && baList.Count > 0)
                {
                    decimal refundMoney = 0;
                    foreach (var item in baList)
                    {
                        refundMoney = Math.Round(refundMoney + item.refundAmount, 2);
                    }
                    money = Math.Round(money - refundMoney, 2);
                }
                //奖励积分
                await _userPointLogServices.OrderComplete(orderInfo.userId, money, orderInfo.orderId);
 
                //如果订单是已完成,但是订单的未发货商品还有的话,需要解冻库存
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == orderId);
                foreach (var item in orderItems)
                {
                    var nums = item.nums - item.sendNums - (item.reshipNums - item.reshipedNums);//还未发货的数量
                    if (nums > 0)
                    {
                        _goodsServices.ChangeStock(item.productId, GlobalEnumVars.OrderChangeStockType.complete.ToString(), nums);
                    }
                }
 
                //订单记录
                var orderLog = new CoreCmsOrderLog
                {
                    userId = orderInfo.userId,
                    orderId = orderInfo.orderId,
                    type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_COMPLETE,
                    msg = "后台订单完成操作",
                    data = JsonConvert.SerializeObject(orderInfo),
                    createTime = DateTime.Now
                };
                await _orderLogServices.InsertAsync(orderLog);
                //百分兵法特殊奖励
                var allConfigs = await _settingServices.GetConfigDictionaries();
                var pointExchangeModel = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.DictionaryAchievementOnOff).ObjectToInt();
                if (pointExchangeModel == 1)
                {
                    //开启业绩奖励模式
                    var user = await _userServices.QueryByIdAsync(orderInfo.userId, isDataCache: true, cacheTimes: 1);
                    if (user.parentId != 0)
                    {
                        //如果是
                        CreateDAOrderInParam data = new CreateDAOrderInParam
                        {
                            Money = money,
                            OderId = orderInfo.orderId,
                            SourceTypes = GlobalEnumVars.UserBalanceSourceTypes.GoodsOder,
                            UserID = user.parentId,
 
 
                        };
                        //经销商业务订单结算
                        await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.DistributionAchievementOder, JsonConvert.SerializeObject(data));
                    }
                }
                //订单完成结算订单
                await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderFinishCommand, orderInfo.orderId);
 
                jm.status = true;
                jm.msg = "订单完成";
 
            }
            else
            {
                jm.status = false;
                jm.msg = "未获取到对应订单数据";
            }
 
            return jm;
        }
        #endregion
 
        #region 确认签收订单
        /// <summary>
        /// 确认签收订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> ConfirmOrder(string orderId, int userId = 0)
        {
            var jm = new WebApiCallBack();
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.orderId == orderId);
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
            where = where.And(p => p.payStatus != (int)GlobalEnumVars.OrderPayStatus.No);
            where = where.And(p => p.shipStatus != (int)GlobalEnumVars.OrderShipStatus.No);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => p.confirmStatus != (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
 
            var orderInfo = await _dal.QueryByClauseAsync(where);
            if (orderInfo == null)
            {
                jm.status = false;
                jm.msg = "订单查询失败";
                return jm;
            }
 
            var bl = await _dal.UpdateAsync(
                p => new CoreCmsOrder()
                {
                    confirmStatus = (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt,
                    confirmTime = DateTime.Now
                }, p => p.orderId == orderInfo.orderId);
            if (!bl)
            {
                jm.msg = "确认收货失败";
                return jm;
            }
            //修改发货单,如果有为确认收货的发货单,那么给他们回传上去确认收货时间
 
            //订单记录
            var orderLog = new CoreCmsOrderLog
            {
                orderId = orderId,
                userId = userId,
                type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_SIGN,
                msg = "确认收货成功",
                data = JsonConvert.SerializeObject(jm),
                createTime = DateTime.Now
            };
            await _orderLogServices.InsertAsync(orderLog);
 
            jm.status = true;
            jm.msg = "确认收货成功";
 
 
 
            return jm;
        }
        #endregion
 
        #region 判断订单是否可以进行评论
        /// <summary>
        /// 判断订单是否可以进行评论
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> IsOrderComment(string orderId, int userId)
        {
            var jm = new WebApiCallBack();
 
            var order = await _dal.QueryByClauseAsync(p => p.orderId == orderId && p.userId == userId);
            if (order != null)
            {
                if (order.payStatus > (int)GlobalEnumVars.OrderPayStatus.No && order.status == (int)GlobalEnumVars.OrderStatus.Normal && order.shipStatus > (int)GlobalEnumVars.OrderShipStatus.No && order.status == (int)GlobalEnumVars.OrderStatus.Normal && order.isComment == false)
                {
                    jm.status = true;
                    jm.msg = "可以评价";
                    jm.data = order;
                }
                else
                {
                    jm.status = false;
                    jm.msg = "订单状态存在问题,不能评价";
                    jm.data = order;
                }
            }
            else
            {
                jm.status = false;
                jm.msg = "不存在这个订单";
            }
 
            return jm;
        }
        #endregion
 
        #region 重写根据条件列表数据
        /// <summary>
        ///     重写根据条件列表数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public async Task<List<CoreCmsOrder>> QueryListAsync(Expression<Func<CoreCmsOrder, bool>> predicate,
            Expression<Func<CoreCmsOrder, object>> orderByExpression, OrderByType orderByType)
        {
 
            return await _dal.QueryListAsync(predicate, orderByExpression, orderByType);
        }
 
        #endregion
 
        #region 重写根据条件查询分页数据
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public async Task<IPageList<CoreCmsOrder>> QueryPageAsync(Expression<Func<CoreCmsOrder, bool>> predicate,
            Expression<Func<CoreCmsOrder, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            return await _dal.QueryPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize, blUseNoLock);
        }
        #endregion
 
        #region 自动取消订单(定时任务使用)
        /// <summary>
        /// 自动取消订单(定时任务使用)
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> AutoCancelOrder()
        {
            var jm = new WebApiCallBack();
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var time = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderCancelTime).ObjectToInt(1);
            var endTime = DateTime.Now.AddMinutes(-time);
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.No);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            //where = where.And(p => p.orderType == (int)GlobalEnumVars.OrderType.Common || p.orderType == (int)GlobalEnumVars.OrderType.PinTuan);
            where = where.And(p => p.createTime <= endTime);
 
            var orderInfos = await _dal.QueryListByClauseAsync(where);
 
            jm.status = true;
            jm.msg = "取消成功";
 
 
            if (orderInfos != null && orderInfos.Any())
            {
                var ids = orderInfos.Select(p => p.orderId).ToArray();
                jm = await CancelOrder(ids);
            }
 
            //插入日志
            var model = new SysTaskLog
            {
                createTime = DateTime.Now,
                isSuccess = jm.status,
                name = "自动取消订单",
                parameters = JsonConvert.SerializeObject(jm)
            };
            await _taskLogServices.InsertAsync(model);
 
            return jm;
        }
        #endregion
 
        #region 自动完成订单(定时任务使用)
        /// <summary>
        /// 自动完成订单(定时任务使用)
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> AutoCompleteOrder()
        {
            var jm = new WebApiCallBack();
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var time = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderCompleteTime).ObjectToInt(30);
            var endTime = DateTime.Now.AddDays(-time);
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.Yes);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.Yes);
            where = where.And(p => p.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
            where = where.And(p => p.paymentTime <= endTime);
 
            var orderInfos = await _dal.QueryListByClauseAsync(where);
 
            jm.status = true;
            jm.msg = "完成成功";
 
            if (orderInfos != null && orderInfos.Any())
            {
                for (var i = 0; i < orderInfos.Count; i++)
                {
                    var item = orderInfos[i];
                    var score = 2 * (i + 1);
                    await CompleteOrder(item.orderId, score, "定时任务操作");
                }
            }
            //插入日志
            var model = new SysTaskLog
            {
                createTime = DateTime.Now,
                isSuccess = jm.status,
                name = "订单自动完成",
                parameters = JsonConvert.SerializeObject(jm)
            };
            await _taskLogServices.InsertAsync(model);
 
            return jm;
        }
        #endregion
 
        #region 自动评价订单(定时任务使用)
        /// <summary>
        /// 自动评价订单(定时任务使用)
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> AutoEvaluateOrder()
        {
            var jm = new WebApiCallBack();
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var time = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderAutoEvalTime).ObjectToInt(5);
            var endTime = DateTime.Now.AddDays(-time);
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.Yes);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.Yes);
            where = where.And(p => p.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
            where = where.And(p => p.isComment == false);
            where = where.And(p => p.confirmTime <= endTime);
 
            var orderInfos = await _dal.QueryListByClauseAsync(where);
 
 
            if (orderInfos != null && orderInfos.Any())
            {
                //订单记录
                var logs = new List<CoreCmsOrderLog>();
                foreach (var orderInfo in orderInfos)
                {
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = orderInfo.userId,
                        orderId = orderInfo.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_AUTO_EVALUATION,
                        msg = "订单后台自动评价(定时任务)",
                        data = JsonConvert.SerializeObject(orderInfo),
                        createTime = DateTime.Now
                    };
                    logs.Add(orderLog);
                }
                await _orderLogServices.InsertAsync(logs);
 
                //更新订单
                var ids = orderInfos.Select(p => p.orderId).ToList();
                await _dal.UpdateAsync(p => new CoreCmsOrder() { isComment = true, updateTime = DateTime.Now },
                    p => ids.Contains(p.orderId));
 
                //查询评价商品
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => ids.Contains(p.orderId));
 
                var listGoodsComment = new List<CoreCmsGoodsComment>();
                foreach (var item in orderItems)
                {
                    var orderInfo = orderInfos.Find(p => p.orderId == item.orderId);
                    var commentModel = new CoreCmsGoodsComment
                    {
                        commentId = 0,
                        score = 5,
                        userId = orderInfo?.userId ?? 0,
                        goodsId = item.goodsId,
                        orderId = item.orderId,
                        contentBody = "用户" + time + "天内未对商品做出评价,已由系统自动评价。",
                        addon = item.addon,
                        isDisplay = true,
                        createTime = DateTime.Now
                    };
                    listGoodsComment.Add(commentModel);
                }
 
                await _goodsCommentServices.InsertAsync(listGoodsComment);
            }
 
 
            jm.status = true;
            jm.msg = "评价订单成功";
 
 
            //插入日志
            var model = new SysTaskLog
            {
                createTime = DateTime.Now,
                isSuccess = jm.status,
                name = "订单自动评价",
                parameters = JsonConvert.SerializeObject(jm)
            };
            await _taskLogServices.InsertAsync(model);
 
            return jm;
        }
        #endregion
 
        #region 自动签收订单(定时任务使用)
        /// <summary>
        /// 自动签收订单(定时任务使用)
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> AutoSignOrder()
        {
            var jm = new WebApiCallBack();
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var time = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.OrderAutoSignTime).ObjectToInt(20);
            var endTime = DateTime.Now.AddDays(-time);
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.Yes);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => p.shipStatus == (int)GlobalEnumVars.OrderShipStatus.Yes);
            where = where.And(p => p.updateTime <= endTime);
 
            var orderInfos = await _dal.QueryListByClauseAsync(where);
 
            if (orderInfos != null && orderInfos.Any())
            {
                foreach (var item in orderInfos)
                {
                    await ConfirmOrder(item.orderId);
                }
            }
 
            jm.status = true;
            jm.msg = "自动签收订单成功";
 
            //插入日志
            var model = new SysTaskLog
            {
                createTime = DateTime.Now,
                isSuccess = jm.status,
                name = "自动签收订单",
                parameters = JsonConvert.SerializeObject(jm)
            };
            await _taskLogServices.InsertAsync(model);
 
            return jm;
        }
        #endregion
 
        #region 催付款订单(定时任务使用)
        /// <summary>
        /// 催付款订单(定时任务使用)
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> RemindOrderPay()
        {
            var jm = new WebApiCallBack();
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var time = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.RemindOrderTime).ObjectToInt(1);
            var dt = DateTime.Now;
            //var endTime = DateTime.Now.AddHours(-time);
 
            var where = PredicateBuilder.True<CoreCmsOrder>();
            where = where.And(p => p.payStatus == (int)GlobalEnumVars.OrderPayStatus.No);
            where = where.And(p => p.status == (int)GlobalEnumVars.OrderStatus.Normal);
            where = where.And(p => dt <= SqlFunc.DateAdd(p.createTime, time, DateType.Minute));
            //where = where.And(p => p.createTime >= SqlFunc.DateAdd(p.createTime, -time, DateType.Minute));
 
            var orderInfos = await _dal.QueryListByClauseAsync(where);
 
            if (orderInfos != null && orderInfos.Any())
            {
                foreach (var item in orderInfos)
                {
                    await _messageCenterServices.SendMessage(item.userId, GlobalEnumVars.PlatformMessageTypes.RemindOrderPay.ToString(), JObject.FromObject(item));
                }
            }
 
            jm.status = true;
            jm.msg = "催付款订单成功";
 
            //插入日志
            var model = new SysTaskLog
            {
                createTime = DateTime.Now,
                isSuccess = jm.status,
                name = "催付款订单",
                parameters = JsonConvert.SerializeObject(jm)
            };
            await _taskLogServices.InsertAsync(model);
 
            return jm;
        }
        #endregion
 
 
 
        #region 订单拆单
 
        /// <summary>
        /// 订单拆单(根据商品所属对订单进行拆单)
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> Chaidan(string orderId)
        {
            var jm = new WebApiCallBack() { msg = "订单拆单失败" };
 
            //获取订单
            var order = await _dal.QueryByClauseAsync(p => p.orderId == orderId);
            if (order == null)
            {
                return jm;
            }
            //查询订单明细
            //订单详情(子货品数据)
            var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
            var goodsids = orderItems.Select(x => x.goodsId).ToArray();
            //查询订单包含的货品
            var coreCmsGoods = await _goodsServices.QueryListByClauseAsync(p => goodsids.Contains(p.id));
            coreCmsGoods = coreCmsGoods.OrderBy(x => x.publisherId).ToList();
            //判断订单是否属于多个供应商,如果属于多个供应商,则拆单发货
            int publisherIdcount = 1 ;
            int publisherId = coreCmsGoods[0].publisherId.HasValue? coreCmsGoods[0].publisherId.Value : 0;
 
            for (int i = 1; i < coreCmsGoods.Count; i++)
            {
                int publisherIdnow = coreCmsGoods[i].publisherId.HasValue ? coreCmsGoods[i].publisherId.Value : 0;
 
                if ( publisherId == publisherIdnow)
                {
                    continue;
                }else  
                {
                    publisherIdcount += 1;
                }       
            }
          
 
            if (publisherIdcount <= 1)
            {
                //修改订单的货权人
                if (coreCmsGoods[0].publisherId.HasValue)
                {
                    order.publisherId = coreCmsGoods[0].publisherId;
                    await _dal.UpdateAsync(order);
                }
                jm.status = true;
                jm.msg = "订单不需要拆单";
                return jm;
            }
 
            foreach (var orderItem in orderItems)
            {
                var coreCmsGoods1 = coreCmsGoods.Where(x => x.id == orderItem.goodsId).FirstOrDefault();
                if (coreCmsGoods1 != null)
                {
                    orderItem.publisherId = coreCmsGoods1.publisherId;
                }
            }
            orderItems = orderItems.OrderBy(x => x.publisherId).ToList() ;
            //订单商品总价
            var amount = orderItems.Sum(x => x.amount);
            //开始拆单
            int orderItemscount = 1;
            while(orderItemscount < orderItems.Count)
            {
                if (orderItems[orderItemscount].publisherId != orderItems[orderItemscount - 1].publisherId)
                {
                    //当前供应商的所有商品
                    var coreCmsOrderItems = orderItems.Where(x=>x.publisherId == orderItems[orderItemscount].publisherId).ToList();
                    var coreCmsamount = coreCmsOrderItems.Sum(x => x.amount);
                    //当前供应商所占商品价格比值
                    var bizhi = coreCmsamount / amount;
 
                    //生成新的订单
                    var coreCmsOrder = new CoreCmsOrder();
                    coreCmsOrder.orderId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.订单编号);
                    if (order.goodsAmount > 0)
                    {
                        coreCmsOrder.goodsAmount = Math.Round(order.goodsAmount * bizhi,2);
                        order.goodsAmount = order.goodsAmount - coreCmsOrder.goodsAmount;
                    }
                    else
                    {
                        coreCmsOrder.goodsAmount = 0;
                    }
 
                    if (order.payedAmount > 0)
                    {
                        coreCmsOrder.payedAmount = Math.Round(order.payedAmount * bizhi, 2);
                        order.payedAmount = order.payedAmount - coreCmsOrder.payedAmount;
                    }
                    else
                    {
                        coreCmsOrder.payedAmount = 0;
                    }
 
                    if (order.orderAmount > 0)
                    {
                        coreCmsOrder.orderAmount = Math.Round(order.orderAmount * bizhi, 2);
                        order.orderAmount = order.orderAmount - coreCmsOrder.orderAmount;
                    }
                    else
                    {
                        coreCmsOrder.orderAmount = 0;
                    }
 
                    coreCmsOrder.payStatus = order.payStatus;
                    coreCmsOrder.shipStatus = order.shipStatus;
                    coreCmsOrder.status = order.status;
                    coreCmsOrder.orderType = order.orderType;
                    coreCmsOrder.receiptType = order.receiptType;
                    coreCmsOrder.paymentCode = order.paymentCode;
                    coreCmsOrder.paymentTime = order.paymentTime;
                    coreCmsOrder.logisticsId = order.logisticsId;
                    coreCmsOrder.logisticsName = order.logisticsName;
 
                    if (order.costFreight > 0)
                    {
                        coreCmsOrder.costFreight = Math.Round(order.costFreight * bizhi, 2);
                        order.costFreight = order.costFreight - coreCmsOrder.costFreight;
                    }
                    else
                    {
                        coreCmsOrder.costFreight = 0;
                    }
 
                    coreCmsOrder.userId = order.userId;
                    coreCmsOrder.sellerId = order.sellerId;
                    coreCmsOrder.confirmStatus = order.confirmStatus;
                    coreCmsOrder.confirmTime = order.confirmTime;
                    coreCmsOrder.storeId = order.storeId;
                    coreCmsOrder.shipAreaId = order.shipAreaId;
                    coreCmsOrder.shipAddress = order.shipAddress;
                    coreCmsOrder.shipCoordinate = order.shipCoordinate;
                    coreCmsOrder.shipName = order.shipName;
                    coreCmsOrder.shipMobile = order.shipMobile;
 
                    coreCmsOrder.weight = coreCmsOrderItems.Sum(x=>x.weight);
                    order.weight = order.weight - coreCmsOrder.weight;
 
                    coreCmsOrder.taxType = order.taxType;
                    coreCmsOrder.taxCode = order.taxCode;
                    coreCmsOrder.taxTitle = order.taxTitle;
 
                    if (order.point > 0)
                    {
                        coreCmsOrder.point = Convert.ToInt32(order.point * bizhi);
                        order.point = order.point - coreCmsOrder.point;
                    }
                    else
                    {
                        coreCmsOrder.point = 0;
                    }
 
                    if (order.pointMoney > 0)
                    {
                        coreCmsOrder.pointMoney = Math.Round(order.pointMoney * bizhi, 2);
                        order.pointMoney = order.pointMoney - coreCmsOrder.pointMoney;
                    }
                    else
                    {
                        coreCmsOrder.pointMoney = 0;
                    }
 
                    if (order.orderDiscountAmount > 0)
                    {
                        coreCmsOrder.orderDiscountAmount = Math.Round(order.orderDiscountAmount * bizhi, 2);
                        order.orderDiscountAmount = order.orderDiscountAmount - coreCmsOrder.orderDiscountAmount;
                    }
                    else
                    {
                        coreCmsOrder.orderDiscountAmount = 0;
                    }
 
 
                    if (order.goodsDiscountAmount > 0)
                    {
                        coreCmsOrder.goodsDiscountAmount = Math.Round(order.goodsDiscountAmount * bizhi, 2);
                        order.goodsDiscountAmount = order.goodsDiscountAmount - coreCmsOrder.goodsDiscountAmount;
                    }
                    else
                    {
                        coreCmsOrder.goodsDiscountAmount = 0;
                    }
 
                    if (order.couponDiscountAmount > 0)
                    {
                        coreCmsOrder.couponDiscountAmount = Math.Round(order.couponDiscountAmount * bizhi, 2);
                        order.couponDiscountAmount = order.couponDiscountAmount - coreCmsOrder.couponDiscountAmount;
                    }
                    else
                    {
                        coreCmsOrder.couponDiscountAmount = 0;
                    }
 
                    coreCmsOrder.coupon = order.coupon;
                    coreCmsOrder.promotionList = order.promotionList;
                    coreCmsOrder.memo = order.memo;
                    coreCmsOrder.ip = order.ip;
                    coreCmsOrder.mark = order.mark;
                    coreCmsOrder.source = order.source;
                    coreCmsOrder.scene = order.scene;
                    coreCmsOrder.isComment = order.isComment;
                    coreCmsOrder.isdel = order.isdel;
                    coreCmsOrder.objectId = order.objectId;
                    coreCmsOrder.createTime = order.createTime;
                    coreCmsOrder.updateTime = order.updateTime;
                    coreCmsOrder.planorderId = order.planorderId;
                    coreCmsOrder.publisherId = order.publisherId;
                    coreCmsOrder.oldOderId = order.oldOderId;
 
 
                    var res =  await _dal.InsertAsync(coreCmsOrder);
 
                    //修改订单的所有明细
                    foreach (var coreCmsOrderItem in coreCmsOrderItems)
                    {
                        coreCmsOrderItem.orderId = coreCmsOrder.orderId;
                        var sss = await _orderItemServices.UpdateAsync(coreCmsOrderItem);
                    }
 
                    coreCmsOrder.Orderitems = coreCmsOrderItems;
 
 
 
                    //生成支付信息
 
                    //创建支付单
                    var billPayments = new CoreCmsBillPayments();
                    billPayments.paymentId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.支付单编号);
                    billPayments.sourceId = coreCmsOrder.orderId;
                    billPayments.money = coreCmsOrder.orderAmount;
                    billPayments.userId = coreCmsOrder.userId;
                    billPayments.type = coreCmsOrder.orderType;
                    billPayments.status = (int)GlobalEnumVars.BillPaymentsStatus.Payed;
                    billPayments.paymentCode = coreCmsOrder.paymentCode;
                    billPayments.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1";
                    billPayments.payedMsg = "订单拆单支付成功";
                    billPayments.parameters = "";
                    billPayments.createTime = DateTime.Now;
                    billPayments.updateTime = DateTime.Now;
 
 
                    await _billPaymentsServices.InsertAsync(billPayments);
 
                    //各种处理
                    //如果是门店自提,应该自动跳过发货,生成提货单信息,使用提货单核销。
                    if (coreCmsOrder.receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
                    {
                        var allConfigs = await _settingServices.GetConfigDictionaries();
                        var storeOrderAutomaticDelivery = CommonHelper
                            .GetConfigDictionary(allConfigs, SystemSettingConstVars.StoreOrderAutomaticDelivery)
                            .ObjectToInt(1);
                        if (storeOrderAutomaticDelivery == 1)
                        {
                            //订单自动发货
                            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAutomaticDelivery, JsonConvert.SerializeObject(coreCmsOrder));
                        }
                    }
 
                   
 
                    //结佣处理
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderAgentOrDistribution, JsonConvert.SerializeObject(coreCmsOrder));
                    //易联云打印机打印
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(coreCmsOrder));
 
                    //发送支付成功信息,增加发送内容
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.OrderPayed.ToString(), JObject.FromObject(coreCmsOrder));
                    await _messageCenterServices.SendMessage(order.userId, GlobalEnumVars.PlatformMessageTypes.SellerOrderNotice.ToString(), JObject.FromObject(coreCmsOrder));
 
                    //用户升级处理
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.UserUpGrade, JsonConvert.SerializeObject(coreCmsOrder));
 
 
                    //跳转到下一个订单
                    orderItemscount += coreCmsOrderItems.Count;
                }
                else
                {
                    orderItemscount += 1;
                }
            }
 
            //修改订单的货权人
            if (coreCmsGoods[0].publisherId.HasValue)
            {
                order.publisherId = coreCmsGoods[0].publisherId;
 
            }
            var ssssss = await _dal.UpdateAsync(order);
 
            jm.status = true;
            jm.msg = "订单拆单成功";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
            //订单记录
            var orderLog = new CoreCmsOrderLog
            {
                orderId = order.orderId,
                userId = order.userId,
                type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_PAY,
                msg = jm.msg,
                data = JsonConvert.SerializeObject(jm),
                createTime = DateTime.Now
            };
            await _orderLogServices.InsertAsync(orderLog);
 
            return jm;
        }
        #endregion
 
    }
}