1
llj
1 天以前 033d6d49fbb0a924653c7fd3ef3700a24f37ee59
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Pub_Class;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Http;
using WebAPI.Models;
 
namespace WebAPI.Controllers
{
    public class Gy_SteppedPriceCoefficientController : ApiController
    {
        public DBUtility.ClsPub.Enum_BillStatus BillStatus;
        private json objJsonResult = new json();
        SQLHelper.ClsCN oCN = new SQLHelper.ClsCN();
        DataSet ds;
 
        #region 新增:工序唯一性检查
        [Route("Gy_SteppedPriceCoefficientBill/CheckProcessUnique")]
        [HttpPost]
        public object CheckProcessUnique([FromBody] JObject data)
        {
            try
            {
                Console.WriteLine("=== 工序唯一性检查开始 ===");
 
                string HProcID = data["HProcID"]?.ToString() ?? "";
                string HStockOrgID = data["HStockOrgID"]?.ToString() ?? "";
                string ExcludeID = data["ExcludeID"]?.ToString() ?? "0";
                string user = data["user"]?.ToString() ?? "";
 
                Console.WriteLine($"参数: HProcID={HProcID}, HStockOrgID={HStockOrgID}, ExcludeID={ExcludeID}, user={user}");
 
                if (string.IsNullOrEmpty(HProcID) || HProcID == "0")
                {
                    return new
                    {
                        code = "1",
                        data = new { exists = false, message = "" }
                    };
                }
 
                if (string.IsNullOrEmpty(HStockOrgID) || HStockOrgID == "0")
                {
                    return new
                    {
                        code = "0",
                        Message = "组织不能为空"
                    };
                }
 
                // 查询该工序是否已存在任何单据中(无论状态如何)
                // 特别注意:这里检查的是同一个工序ID在同一个组织下是否已存在
                string sql = $@"
                    SELECT TOP 1 HBillNo, HBillStatus, HDeleteMan 
                    FROM Gy_SteppedPriceCoefficientBillMain 
                    WHERE HProcID = {HProcID} 
                      AND HStockOrgID = {HStockOrgID} 
                      AND HInterID != {ExcludeID}";
 
                Console.WriteLine($"查询SQL: {sql}");
 
                ds = oCN.RunProcReturn(sql, "CheckProcess");
 
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    string billNo = ds.Tables[0].Rows[0]["HBillNo"]?.ToString() ?? "";
                    int billStatus = ds.Tables[0].Rows[0]["HBillStatus"] == DBNull.Value ? 1 : Convert.ToInt32(ds.Tables[0].Rows[0]["HBillStatus"]);
                    string deleteMan = ds.Tables[0].Rows[0]["HDeleteMan"]?.ToString() ?? "";
 
                    Console.WriteLine($"找到重复记录: BillNo={billNo}, BillStatus={billStatus}, DeleteMan={deleteMan}");
 
                    // 只要有记录就返回存在(无论什么状态)
                    return new
                    {
                        code = "1",
                        data = new
                        {
                            exists = true,
                            billNo = billNo,
                            message = $"该工序已在单据[{billNo}]中使用,一个工序只能对应一条阶梯工价系数数据!"
                        }
                    };
                }
 
                Console.WriteLine("未找到重复记录,工序可用");
 
                return new
                {
                    code = "1",
                    data = new { exists = false }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"工序唯一性检查异常: {ex.Message}");
                return new
                {
                    code = "0",
                    Message = "检查工序唯一性时出错:" + ex.Message
                };
            }
        }
        #endregion
 
        #region 修改:保存方法,添加工序唯一性验证
        [Route("Gy_SteppedPriceCoefficientBill/ModifyByID")]
        [HttpPost]
        public object ModifyByID([FromBody] JObject oMain)
        {
            bool transactionStarted = false;
            string HBillNo = "";
            long newHInterID = 0;
            List<string> errorLogs = new List<string>();
 
            try
            {
                
                errorLogs.Add($"=== {DateTime.Now:yyyy-MM-dd HH:mm:ss} 保存开始 ===");
 
                // 1. 解析数据
                var _value = oMain["oMain"].ToString();
                string[] sArray = _value.Split(';');
                string jsonData = sArray[0];
                string user = sArray.Length > 1 ? sArray[1] : "unknown";
 
                // 查看权限检查
                if (!DBUtility.ClsPub.Security_Log("Gy_SteppedPriceCoefficient_Edit", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无编辑权限";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                errorLogs.Add($"解析数据: user={user}");
 
                // 2. 解析JSON
                jsonData = "[" + jsonData + "]";
                JArray jArray = JArray.Parse(jsonData);
 
                if (jArray.Count == 0)
                {
                    return new { code = "0", Message = "数据不能为空!" };
                }
 
                JToken jToken = jArray[0];
 
                // 3. 提取字段
                long HInterID = 0;
                if (jToken["HInterID"] != null && long.TryParse(jToken["HInterID"].ToString(), out long tempId))
                {
                    HInterID = tempId;
                }
 
                string HBillNoFromJson = jToken["HBillNo"]?.ToString() ?? "";
                string HRemark = jToken["HRemark"]?.ToString() ?? "";
 
                // 数值字段
                int HProcID = 0, HEmpID = 0, HDeptID = 0, HStockOrgID = 0;
                if (jToken["HProcID"] != null) int.TryParse(jToken["HProcID"].ToString(), out HProcID);
                if (jToken["HEmpID"] != null) int.TryParse(jToken["HEmpID"].ToString(), out HEmpID);
                if (jToken["HDeptID"] != null) int.TryParse(jToken["HDeptID"].ToString(), out HDeptID);
                if (jToken["HStockOrgID"] != null) int.TryParse(jToken["HStockOrgID"].ToString(), out HStockOrgID);
 
                errorLogs.Add($"提取字段: HInterID={HInterID}, HProcID={HProcID}, HStockOrgID={HStockOrgID}");
 
                // 日期字段
                DateTime HDate = DateTime.Now;
                if (jToken["HDate"] != null && DateTime.TryParse(jToken["HDate"].ToString(), out DateTime tempDate))
                {
                    HDate = tempDate;
                }
 
                // 4. 验证基础数据
                if (string.IsNullOrEmpty(HBillNoFromJson))
                {
                    return new { code = "0", Message = "单据号不能为空!" };
                }
 
                if (HInterID <= 0)
                {
                    return new { code = "0", Message = "单据ID无效!" };
                }
 
                if (HProcID == 0)
                {
                    return new { code = "0", Message = "工序不能为空!" };
                }
 
                if (HStockOrgID == 0)
                {
                    return new { code = "0", Message = "组织不能为空!" };
                }
 
                // 5. 检查工序唯一性
                errorLogs.Add($"开始检查工序唯一性");
 
                bool isEditMode = false;
                string originalProcID = "";
 
                // 检查是否已存在
                string checkExistSql = $"SELECT COUNT(*), HProcID FROM Gy_SteppedPriceCoefficientBillMain WHERE HInterID = {HInterID} GROUP BY HProcID";
                DataSet existDs = oCN.RunProcReturn(checkExistSql, "CheckExist");
 
                if (existDs != null && existDs.Tables[0].Rows.Count > 0)
                {
                    // 编辑模式
                    isEditMode = true;
                    originalProcID = existDs.Tables[0].Rows[0]["HProcID"]?.ToString() ?? "";
                    errorLogs.Add($"编辑模式: 原始工序ID={originalProcID}");
                }
                else
                {
                    // 新增模式
                    errorLogs.Add($"新增模式");
                }
 
                // 判断是否需要检查工序唯一性
                bool needCheckProcess = true;
 
                if (isEditMode && !string.IsNullOrEmpty(originalProcID))
                {
                    // 编辑模式:如果工序ID没有变化,则不需要检查
                    if (originalProcID == HProcID.ToString())
                    {
                        needCheckProcess = false;
                        errorLogs.Add($"工序未修改,跳过唯一性检查");
                    }
                    else
                    {
                        errorLogs.Add($"工序从{originalProcID}修改为{HProcID},需要检查唯一性");
                    }
                }
 
                // 执行工序唯一性检查
                if (needCheckProcess)
                {
                    string checkProcessSql = $@"
                        SELECT TOP 1 HBillNo 
                        FROM Gy_SteppedPriceCoefficientBillMain 
                        WHERE HProcID = {HProcID} 
                          AND HStockOrgID = {HStockOrgID} 
                          AND HInterID != {HInterID}";
 
                    DataSet processDs = oCN.RunProcReturn(checkProcessSql, "CheckProcess");
 
                    if (processDs != null && processDs.Tables[0].Rows.Count > 0)
                    {
                        string existingBillNo = processDs.Tables[0].Rows[0]["HBillNo"]?.ToString() ?? "";
                        errorLogs.Add($"发现重复工序: 单据号={existingBillNo}");
 
                        return new
                        {
                            code = "0",
                            Message = $"该工序已在单据[{existingBillNo}]中使用,一个工序只能对应一条阶梯工价系数数据!",
                            logs = errorLogs
                        };
                    }
                    errorLogs.Add($"工序唯一性检查通过");
                }
 
                // 6. 开始事务
                oCN.BeginTran();
                transactionStarted = true;
 
                newHInterID = HInterID;
                HBillNo = HBillNoFromJson;
 
                // 安全处理字符串
                string safeHBillNo = HBillNo.Replace("'", "''");
                string safeHRemark = HRemark.Replace("'", "''");
                string safeUser = user.Replace("'", "''");
 
                // 7. 保存主表数据
                if (isEditMode)
                {
                    // 编辑模式
                    errorLogs.Add($"HInterID={HInterID} 已存在,进入编辑模式");
 
                    // 更新主表
                    string updateSql = $@"
                        UPDATE Gy_SteppedPriceCoefficientBillMain SET 
                            HDate = '{HDate.ToString("yyyy-MM-dd HH:mm:ss")}', 
                            HRemark = '{safeHRemark}', 
                            HProcID = {HProcID}, 
                            HEmpID = {HEmpID}, 
                            HDeptID = {HDeptID}, 
                            HStockOrgID = {HStockOrgID}, 
                            HUpDater = '{safeUser}', 
                            HUpDateDate = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' 
                        WHERE HInterID = {HInterID}";
 
                    errorLogs.Add($"执行更新SQL: {updateSql}");
                    oCN.RunProc(updateSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                    // 删除原有子表
                    string deleteSubSql = $"DELETE FROM Gy_SteppedPriceCoefficientBillSub WHERE HInterID = {HInterID}";
                    oCN.RunProc(deleteSubSql, ref DBUtility.ClsPub.sExeReturnInfo);
                }
                else
                {
                    // 新增模式
                    errorLogs.Add($"HInterID={HInterID} 不存在,进入新增模式");
 
                    // 获取年份和期间
                    int HYear = HDate.Year;
                    int HPeriod = HDate.Month;
 
                    // 构建主表插入SQL
                    string mainSql = $@"
                        INSERT INTO Gy_SteppedPriceCoefficientBillMain (
                            HYear, HPeriod, HBillType, HBillSubType,
                            HInterID, HDate, HBillNo, HBillStatus, HRemark,
                            HBackRemark, HMaker, HMakeDate,
                            HMainSourceBillType, HMainSourceInterID, HMainSourceEntryID, HMainSourceBillNo,
                            HPrintQty, HProcID, HEmpID, HDeptID, HStockOrgID
                        ) VALUES (
                            {HYear}, {HPeriod}, '3341', '',
                            {HInterID}, '{HDate.ToString("yyyy-MM-dd HH:mm:ss")}', '{safeHBillNo}', 1, '{safeHRemark}',
                            '', '{safeUser}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',
                            '', 0, 0, '', 0, 
                            {HProcID}, {HEmpID}, {HDeptID}, {HStockOrgID}
                        )";
 
                    errorLogs.Add($"执行主表插入SQL");
                    oCN.RunProc(mainSql, ref DBUtility.ClsPub.sExeReturnInfo);
                }
 
                // 8. 插入子表
                if (jToken["SubItems"] != null)
                {
                    JArray subItems = jToken["SubItems"] as JArray;
 
                    if (subItems != null && subItems.Count > 0)
                    {
                        errorLogs.Add($"开始插入{subItems.Count}条子表数据");
 
                        for (int i = 0; i < subItems.Count; i++)
                        {
                            JToken subToken = subItems[i];
 
                            int hSeq = subToken["HSeq"]?.ToObject<int>() ?? (i + 1);
                            int hMinQty = subToken["HMinQty"]?.ToObject<int>() ?? 0;
                            int hMaxQty = subToken["HMaxQty"]?.ToObject<int>() ?? 0;
                            decimal hPriceCoefficient = subToken["HPriceCoefficient"]?.ToObject<decimal>() ?? 1.0m;
                            decimal hMaxPrice = subToken["HMaxPrice"]?.ToObject<decimal>() ?? 0m;
                            string hRemark = subToken["HRemark"]?.ToString() ?? "";
 
                            string safeSubRemark = hRemark.Replace("'", "''");
 
                            string insertSubSql = $@"
                                INSERT INTO Gy_SteppedPriceCoefficientBillSub (
                                    HInterID, HBillNo_bak, HEntryID, HRemark,
                                    HSourceInterID, HSourceEntryID, HSourceBillNo, HSourceBillType,
                                    HRelationQty, HRelationMoney, HSeq,
                                    HMinQty, HMaxQty, HPriceCoefficient,
                                    HMaxPrice, HStockOrgID
                                ) VALUES (
                                    {HInterID}, '{safeHBillNo}', {i + 1}, '{safeSubRemark}',
                                    0, 0, '', '', 0, 0,
                                    {hSeq}, {hMinQty}, {hMaxQty},
                                    {hPriceCoefficient.ToString().Replace(",", ".")},
                                    {(hMaxPrice == 0 ? "NULL" : hMaxPrice.ToString().Replace(",", "."))},
                                    {HStockOrgID}
                                )";
 
                            oCN.RunProc(insertSubSql, ref DBUtility.ClsPub.sExeReturnInfo);
                        }
                        errorLogs.Add($"子表数据插入完成");
                    }
                }
 
                // 9. 提交事务
                oCN.Commit();
                transactionStarted = false;
 
                errorLogs.Add($"=== 保存成功完成 ===");
 
                return new
                {
                    code = "1",
                    Message = "保存成功!",
                    data = new { HInterID = newHInterID, HBillNo = HBillNo },
                    logs = errorLogs
                };
            }
            catch (Exception ex)
            {
                errorLogs.Add($"=== 发生异常 ===");
                errorLogs.Add($"异常信息: {ex.Message}");
                errorLogs.Add($"堆栈跟踪: {ex.StackTrace}");
 
                // 回滚事务
                if (transactionStarted)
                {
                    try { oCN.RollBack(); errorLogs.Add("事务已回滚"); } catch { errorLogs.Add("事务回滚失败"); }
                }
 
                return new
                {
                    code = "0",
                    Message = $"保存失败:{ex.Message}",
                    logs = errorLogs
                };
            }
        }
        #endregion
 
        #region 新增:获取工序对应的名称
        [Route("Gy_SteppedPriceCoefficientBill/GetProcessName")]
        [HttpGet]
        public object GetProcessName(int HProcID, int HStockOrgID)
        {
            try
            {
                if (HProcID == 0)
                {
                    return new { code = "0", Message = "工序ID不能为空" };
                }
 
                // 查询工序名称,这里需要根据你的数据库结构调整
                string sql = $@"
                    SELECT TOP 1 
                        FItemID as HProcID,
                        FName as HProcName
                    FROM t_ICItem  -- 这里需要替换成你的工序表名
                    WHERE FItemID = {HProcID} 
                      AND FStockOrgID = {HStockOrgID}";
 
                // 如果工序信息不在t_ICItem表中,需要调整查询
                // 先尝试用通用查询
                DataSet nameDs = oCN.RunProcReturn(sql, "ProcessName");
 
                if (nameDs != null && nameDs.Tables[0].Rows.Count > 0)
                {
                    return new
                    {
                        code = "1",
                        data = new
                        {
                            HProcID = HProcID,
                            HProcName = nameDs.Tables[0].Rows[0]["HProcName"]?.ToString() ?? $"工序{HProcID}"
                        }
                    };
                }
                else
                {
                    // 如果查不到,返回默认值
                    return new
                    {
                        code = "1",
                        data = new
                        {
                            HProcID = HProcID,
                            HProcName = $"工序{HProcID}"
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                return new { code = "0", Message = "获取工序名称失败:" + ex.Message };
            }
        }
        #endregion
 
 
        #region 阶梯工价系数 查询-页面赋值  
        [Route("Gy_SteppedPriceCoefficientBill/list")]
        [HttpGet]
        public object list(string sWhere, string user)
        {
            try
            {
                List<object> columnNameList = new List<object>();
 
                // 查看权限检查
                if (!DBUtility.ClsPub.Security_Log("Gy_SteppedPriceCoefficient_Query", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无查看权限";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 构建基础SQL
                string baseSql = @"select * from h_v_Gy_SteppedPriceCoefficientBillWithSub";
 
                // 调试:记录接收到的参数
                Console.WriteLine($"API 接收参数 - sWhere: '{sWhere}', user: '{user}'");
 
                // 处理查询条件(约定:前端只发送条件表达式,可能以 AND 开头)
                string whereClause = ProcessWhereClause(sWhere);
                string orderByClause = "order by hmainid";
 
                // 构建完整SQL
                string sql;
                if (string.IsNullOrWhiteSpace(whereClause))
                {
                    // 没有条件时,不需要WHERE关键字
                    sql = $"{baseSql} {orderByClause}";
                }
                else
                {
                    // 有条件时,添加WHERE关键字
                    sql = $"{baseSql} WHERE {whereClause} {orderByClause}";
                }
 
                // 调试:输出最终SQL
                Console.WriteLine($"最终执行的SQL: {sql}");
 
                // 执行查询
                ds = oCN.RunProcReturn(sql, "h_v_Gy_SteppedPriceCoefficientBillWithSub");
 
                // 添加列名
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        Type dataType = col.DataType;
                        string colmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                        columnNameList.Add(JsonConvert.DeserializeObject(colmString));
                    }
                }
 
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    objJsonResult.code = "1";
                    objJsonResult.count = ds.Tables[0].Rows.Count;
                    objJsonResult.Message = "Success!";
                    objJsonResult.data = ds.Tables[0];
                    objJsonResult.list = columnNameList;
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "没有查询到数据,请联系系统管理员进行核对";
                    objJsonResult.data = ds?.Tables[0] ?? new DataTable();
                    objJsonResult.list = columnNameList;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "查询失败!错误:" + e.Message;
                objJsonResult.data = null;
 
                // 记录完整异常信息
                Console.WriteLine($"API 异常: {e.ToString()}");
 
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 处理WHERE条件子句
        /// 约定:前端只发送条件表达式,可能以 AND 开头
        /// 返回:不带 WHERE 和开头 AND 的条件字符串
        /// </summary>
        private string ProcessWhereClause(string sWhere)
        {
            if (string.IsNullOrWhiteSpace(sWhere))
                return string.Empty;
 
            string condition = sWhere.Trim();
 
            Console.WriteLine($"ProcessWhereClause 输入: '{sWhere}'");
 
            // 如果前端意外发送了 WHERE 开头,移除它
            if (condition.StartsWith("WHERE ", StringComparison.OrdinalIgnoreCase))
            {
                condition = condition.Substring(6).Trim();
                Console.WriteLine($"移除了 WHERE 关键字,处理后: '{condition}'");
            }
 
            // 移除开头的 AND
            if (condition.StartsWith("AND ", StringComparison.OrdinalIgnoreCase))
            {
                condition = condition.Substring(4).Trim();
                Console.WriteLine($"移除了 AND 关键字,处理后: '{condition}'");
            }
 
            // 额外检查:确保开头没有 WHERE 或 AND
            condition = condition.Trim();
 
            Console.WriteLine($"ProcessWhereClause 最终输出: '{condition}'");
 
            return condition;
        }
        #endregion
 
        #region 阶梯工价系数 编辑-页面赋值
        [Route("Gy_SteppedPriceCoefficientBill/editInit")]
        [HttpGet]
        public object getSteppedPriceCoefficientEditInit(string HInterID, string user)
        {
            try
            {
                Console.WriteLine($"=== 编辑页面初始化开始 ===");
                Console.WriteLine($"参数 - HInterID: {HInterID}, User: {user}");
 
 
 
                if (string.IsNullOrEmpty(HInterID) || HInterID == "0")
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "HInterID不能为空!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 查询主表数据
                string mainSql = $@"
                    SELECT 
                        m.HInterID,
                        m.HItemMainID,
                        m.HBillNo,
                        m.HDate,
                        m.HRemark,
                        m.HProcID,
                        m.HEmpID,
                        m.HDeptID,
                        m.HStockOrgID,
                        m.HMaker,
                        m.HUpDater,
                        m.HChecker,
                        m.HCloseMan,
                        m.HDeleteMan,
                        m.HBacker,
                        m.HMakeDate,
                        m.HUpDateDate,
                        m.HCheckDate,
                        m.HCloseDate,
                        m.HDeleteDate,
                        m.HBackDate,
                        m.HBackRemark
                    FROM Gy_SteppedPriceCoefficientBillMain m
                    WHERE m.HInterID = {HInterID}";
 
                ds = oCN.RunProcReturn(mainSql, "MainData");
 
                Console.WriteLine($"主表查询结果行数: {ds?.Tables[0]?.Rows?.Count ?? 0}");
 
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "未查询到记录!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 检查单据状态
                string checker = ds.Tables[0].Rows[0]["HChecker"]?.ToString() ?? "";
                if (!string.IsNullOrEmpty(checker))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "该单据已审核,不可编辑!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 获取子表数据
                string subSql = $@"
                    SELECT 
                        HEntryID,
                        HSeq,
                        HMinQty,
                        HMaxQty,
                        HPriceCoefficient,
                        HMaxPrice,
                        HRemark,
                        HStockOrgID
                    FROM Gy_SteppedPriceCoefficientBillSub 
                    WHERE HInterID = {HInterID} 
                    ORDER BY HSeq";
 
                DataSet subDs = oCN.RunProcReturn(subSql, "SubData");
 
                Console.WriteLine($"子表查询结果行数: {subDs?.Tables[0]?.Rows?.Count ?? 0}");
 
                // 转换数据为对象列表
                List<Dictionary<string, object>> mainList = new List<Dictionary<string, object>>();
                List<Dictionary<string, object>> subList = new List<Dictionary<string, object>>();
 
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        Dictionary<string, object> rowDict = new Dictionary<string, object>();
                        foreach (DataColumn col in ds.Tables[0].Columns)
                        {
                            rowDict[col.ColumnName] = row[col] == DBNull.Value ? null : row[col];
                        }
                        mainList.Add(rowDict);
                    }
                }
 
                if (subDs != null && subDs.Tables.Count > 0 && subDs.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in subDs.Tables[0].Rows)
                    {
                        Dictionary<string, object> rowDict = new Dictionary<string, object>();
                        foreach (DataColumn col in subDs.Tables[0].Columns)
                        {
                            rowDict[col.ColumnName] = row[col] == DBNull.Value ? null : row[col];
                        }
                        subList.Add(rowDict);
                    }
                }
 
                // 构建返回结果
                var result = new
                {
                    Main = mainList,
                    Sub = subList
                };
 
                Console.WriteLine("编辑页面初始化成功完成");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Success!";
                objJsonResult.data = result;
                return objJsonResult;
            }
            catch (Exception e)
            {
                Console.WriteLine($"=== 编辑页面初始化异常 ===");
                Console.WriteLine($"错误信息: {e.Message}");
                Console.WriteLine($"堆栈跟踪: {e.StackTrace}");
 
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "查询失败!" + e.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 阶梯工价系数 删除
        [Route("Gy_SteppedPriceCoefficientBill/delete")]
        [HttpGet]
        public object deleteSteppedPriceCoefficient(string HInterID, string user)
        {
            try
            {
                if (string.IsNullOrEmpty(HInterID))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "HInterID不能为空!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                // 查看权限检查
                if (!DBUtility.ClsPub.Security_Log("Gy_SteppedPriceCoefficient_Drop", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无删除权限";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //检查单据状态
                string sql = "SELECT HBillStatus, HChecker FROM Gy_SteppedPriceCoefficientBillMain WHERE HInterID = " + HInterID;
                ds = oCN.RunProcReturn(sql, "CheckStatus");
 
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                string checker = ds.Tables[0].Rows[0]["HChecker"].ToString();
                if (!string.IsNullOrEmpty(checker))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "该单据已审核,不可删除!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                oCN.BeginTran();
 
                //删除子表数据
                string deleteSubSql = "DELETE FROM Gy_SteppedPriceCoefficientBillSub WHERE HInterID = " + HInterID;
                oCN.RunProc(deleteSubSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                //删除主表数据
                string deleteMainSql = "DELETE FROM Gy_SteppedPriceCoefficientBillMain WHERE HInterID = " + HInterID;
                oCN.RunProc(deleteMainSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                oCN.Commit();
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "删除成功!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                oCN.RollBack();
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "删除失败!" + e.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 阶梯工价系数 审核/反审核
        [Route("Gy_SteppedPriceCoefficientBill/Audit")]
        [HttpGet]
        public object AuditSteppedPriceCoefficient(int HInterID, int IsAudit, string CurUserName)
        {
            try
            {
 
                // 查看权限检查
                if (!DBUtility.ClsPub.Security_Log("Gy_SteppedPriceCoefficient_Check", 1, false, CurUserName))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无审核权限";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
 
                //检查单据状态
                string checkSql = "SELECT HBillStatus, HChecker FROM Gy_SteppedPriceCoefficientBillMain WHERE HInterID = " + HInterID;
                ds = oCN.RunProcReturn(checkSql, "CheckStatus");
 
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                string checker = ds.Tables[0].Rows[0]["HChecker"].ToString();
                int billStatus = Convert.ToInt32(ds.Tables[0].Rows[0]["HBillStatus"]);
 
                oCN.BeginTran();
 
                if (IsAudit == 0)  //审核
                {
                    if (!string.IsNullOrEmpty(checker))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已审核,不能重复审核!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    string auditSql = "UPDATE Gy_SteppedPriceCoefficientBillMain SET " +
                        "HBillStatus = 2, " +
                        "HChecker = '" + CurUserName + "', " +
                        "HCheckDate = GETDATE() " +
                        "WHERE HInterID = " + HInterID;
 
                    oCN.RunProc(auditSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "审核成功!";
                }
                else if (IsAudit == 1) //反审核
                {
                    if (string.IsNullOrEmpty(checker))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据未审核,不能反审核!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    string unauditSql = "UPDATE Gy_SteppedPriceCoefficientBillMain SET " +
                        "HBillStatus = 1, " +
                        "HChecker = '', " +
                        "HCheckDate = NULL " +
                        "WHERE HInterID = " + HInterID;
 
                    oCN.RunProc(unauditSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "反审核成功!";
                }
 
                oCN.Commit();
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                oCN.RollBack();
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "操作失败!" + e.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 阶梯工价系数 关闭/反关闭功能
        /// <summary>
        /// 关闭/反关闭阶梯工价系数单据
        /// </summary>
        /// <param name="HInterID">单据ID</param>
        /// <param name="IsAudit">关闭(0),反关闭(1)</param>
        /// <param name="user">操作人</param>
        /// <returns></returns>
        [Route("Gy_SteppedPriceCoefficientBill/CloseGy_SteppedPriceCoefficientBill")]
        [HttpGet]
        public object CloseGy_SteppedPriceCoefficientBill(string HInterID, int IsAudit, string user)
        {
            json objJsonResult = new json(); // 使用您现有的json对象
            try
            {
                Console.WriteLine($"=== 关闭/反关闭开始 ===");
                Console.WriteLine($"参数: HInterID={HInterID}, IsAudit={IsAudit}, user={user}");
 
                // 1. 权限检查
                //string ModRightNameCheck = "Gy_SteppedPriceCoefficientBill_Close";
                //if (!DBUtility.ClsPub.Security_Log(ModRightNameCheck, 1, false, user))
                //{
                //    Console.WriteLine($"权限检查失败: {ModRightNameCheck}");
                //    objJsonResult.code = "0";
                //    objJsonResult.count = 0;
                //    objJsonResult.Message = "无关闭权限!";
                //    objJsonResult.data = null;
                //    return objJsonResult;
                //}
 
                // 2. 参数验证
                if (string.IsNullOrEmpty(HInterID) || HInterID == "0")
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据ID不能为空!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 3. 单据状态检查
                string checkSql = $@"
            SELECT 
                HInterID,
                HBillNo,
                HCloseMan,
                HChecker,
                HCheckDate,
                HDeleteMan,
                HBillStatus,
                HBacker
            FROM Gy_SteppedPriceCoefficientBillMain 
            WHERE HInterID = {HInterID}";
 
                Console.WriteLine($"查询SQL: {checkSql}");
                ds = oCN.RunProcReturn(checkSql, "CheckBillStatus");
 
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                DataRow row = ds.Tables[0].Rows[0];
                string billNo = row["HBillNo"]?.ToString() ?? "";
                string closeMan = row["HCloseMan"]?.ToString() ?? "";
                string checker = row["HChecker"]?.ToString() ?? "";
                string deleteMan = row["HDeleteMan"]?.ToString() ?? "";
                string backer = row["HBacker"]?.ToString() ?? "";
                int billStatus = Convert.ToInt32(row["HBillStatus"]);
 
                Console.WriteLine($"单据状态: BillNo={billNo}, BillStatus={billStatus}, CloseMan={closeMan}, Checker={checker}, DeleteMan={deleteMan}");
 
                // 4. 业务规则检查
                if (IsAudit == 0)  // 关闭判断
                {
                    // 检查是否已关闭
                    if (billStatus == 3 || !string.IsNullOrEmpty(closeMan))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已关闭!不能再次关闭!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查是否已审核通过(状态2)
                    if (billStatus != 2)
                    {
                        string statusMsg = GetStatusMessage(billStatus);
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = $"单据当前状态为{statusMsg},只有已审核通过的单据才能关闭!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查是否已作废
                    if (billStatus == 4 || !string.IsNullOrEmpty(deleteMan))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已作废!不能关闭!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查是否已退回
                    if (billStatus == 5 || !string.IsNullOrEmpty(backer))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已审核退回!不能关闭!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                }
 
                if (IsAudit == 1) // 反关闭判断
                {
                    // 检查是否已关闭
                    if (billStatus != 3 || string.IsNullOrEmpty(closeMan))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据未关闭!不需要反关闭!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                }
 
                // 5. 开始事务处理
                oCN.BeginTran();
 
                try
                {
                    if (IsAudit == 0)  // 关闭操作
                    {
                        // 关闭前控制 - 调用存储过程进行业务验证
                        string beforeCloseSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_BeforeCloseCtrl {HInterID}, '{billNo}', '{user}'";
                        Console.WriteLine($"关闭前控制SQL: {beforeCloseSql}");
 
                        DataSet beforeDs = oCN.RunProcReturn(beforeCloseSql, "BeforeCloseCtrl");
 
                        if (beforeDs == null || beforeDs.Tables.Count == 0 || beforeDs.Tables[0].Rows.Count == 0)
                        {
                            throw new Exception("关闭前判断失败,请与网络管理人员联系");
                        }
 
                        if (beforeDs.Tables[0].Rows[0]["HBack"]?.ToString() != "0")
                        {
                            string errorMsg = beforeDs.Tables[0].Rows[0]["HRemark"]?.ToString() ?? "关闭前验证失败";
                            throw new Exception(errorMsg);
                        }
 
                        // 执行关闭
                        string closeSql = $@"
                    UPDATE Gy_SteppedPriceCoefficientBillMain 
                    SET 
                        HCloseMan = '{user.Replace("'", "''")}',
                        HCloseDate = GETDATE(),
                        HBillStatus = 3  -- 已关闭状态
                    WHERE HInterID = {HInterID}";
 
                        Console.WriteLine($"关闭SQL: {closeSql}");
                        oCN.RunProc(closeSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 关闭后控制
                        string afterCloseSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_AfterCloseCtrl {HInterID}, '{billNo}', '{user}'";
                        oCN.RunProc(afterCloseSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        oCN.Commit();
 
                        Console.WriteLine("关闭成功完成");
 
                        objJsonResult.code = "1";
                        objJsonResult.count = 1;
                        objJsonResult.Message = "关闭成功!";
                        objJsonResult.data = new { HInterID = HInterID, HBillNo = billNo };
                        return objJsonResult;
                    }
 
                    if (IsAudit == 1) // 反关闭操作
                    {
                        // 反关闭前控制
                        string beforeUnCloseSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_BeforeUnCloseCtrl {HInterID}, '{billNo}', '{user}'";
                        Console.WriteLine($"反关闭前控制SQL: {beforeUnCloseSql}");
 
                        DataSet beforeUnCloseDs = oCN.RunProcReturn(beforeUnCloseSql, "BeforeUnCloseCtrl");
 
                        if (beforeUnCloseDs == null || beforeUnCloseDs.Tables.Count == 0 || beforeUnCloseDs.Tables[0].Rows.Count == 0)
                        {
                            throw new Exception("反关闭前判断失败,请与网络管理人员联系");
                        }
 
                        if (beforeUnCloseDs.Tables[0].Rows[0]["HBack"]?.ToString() != "0")
                        {
                            string errorMsg = beforeUnCloseDs.Tables[0].Rows[0]["HRemark"]?.ToString() ?? "反关闭前验证失败";
                            throw new Exception(errorMsg);
                        }
 
                        // 执行反关闭 - 返回审核通过状态(2)
                        string unCloseSql = $@"
                    UPDATE Gy_SteppedPriceCoefficientBillMain 
                    SET 
                        HCloseMan = '',
                        HCloseDate = NULL,
                        HBillStatus = 2  -- 返回审核通过状态
                    WHERE HInterID = {HInterID}";
 
                        Console.WriteLine($"反关闭SQL: {unCloseSql}");
                        oCN.RunProc(unCloseSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 反关闭后控制
                        string afterUnCloseSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_AfterUnCloseCtrl {HInterID}, '{billNo}', '{user}'";
                        oCN.RunProc(afterUnCloseSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        oCN.Commit();
 
                        Console.WriteLine("反关闭成功完成");
 
                        objJsonResult.code = "1";
                        objJsonResult.count = 1;
                        objJsonResult.Message = "反关闭成功!";
                        objJsonResult.data = new { HInterID = HInterID, HBillNo = billNo };
                        return objJsonResult;
                    }
 
                    // 参数错误
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无效的操作类型!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                catch (Exception ex)
                {
                    oCN.RollBack();
                    Console.WriteLine($"操作失败: {ex.Message}");
                    throw new Exception("操作失败:" + ex.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"执行失败: {e.Message}");
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "执行失败!" + e.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 阶梯工价系数 作废/反作废
        /// <summary>
        /// 作废/反作废阶梯工价系数单据
        /// </summary>
        /// <param name="HInterID">单据ID</param>
        /// <param name="IsAudit">作废(0),反作废(1)</param>
        /// <param name="CurUserName">操作人</param>
        /// <returns></returns>
        [Route("Gy_SteppedPriceCoefficientBill/DropGy_SteppedPriceCoefficientBill")]
        [HttpGet]
        public object DropGy_SteppedPriceCoefficientBill(int HInterID, int IsAudit, string CurUserName)
        {
            json objJsonResult = new json(); // 使用您现有的json对象
            try
            {
                Console.WriteLine($"=== 作废/反作废开始 ===");
                Console.WriteLine($"参数: HInterID={HInterID}, IsAudit={IsAudit}, CurUserName={CurUserName}");
 
                // 1. 权限检查
                string ModRightNameCheck = "Gy_SteppedPriceCoefficientBill_Delete";
                //if (!DBUtility.ClsPub.Security_Log(ModRightNameCheck, 1, false, CurUserName))
                //{
                //    Console.WriteLine($"权限检查失败: {ModRightNameCheck}");
                //    objJsonResult.code = "0";
                //    objJsonResult.count = 0;
                //    objJsonResult.Message = "作废失败!无权限!";
                //    objJsonResult.data = null;
                //    return objJsonResult;
                //}
 
                // 2. 参数验证
                if (HInterID <= 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据ID无效!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                // 3. 获取单据信息
                string checkSql = $@"
            SELECT 
                HInterID,
                HBillNo,
                HChecker,
                HCheckDate,
                HCloseMan,
                HDeleteMan,
                HBillStatus,
                HBacker,
                HBackDate
            FROM Gy_SteppedPriceCoefficientBillMain 
            WHERE HInterID = {HInterID}";
 
                Console.WriteLine($"查询SQL: {checkSql}");
                ds = oCN.RunProcReturn(checkSql, "GetBillInfo");
 
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "单据不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                DataRow row = ds.Tables[0].Rows[0];
                string billNo = row["HBillNo"]?.ToString() ?? "";
                string checker = row["HChecker"]?.ToString() ?? "";
                string closeMan = row["HCloseMan"]?.ToString() ?? "";
                string deleteMan = row["HDeleteMan"]?.ToString() ?? "";
                string backer = row["HBacker"]?.ToString() ?? "";
                int billStatus = Convert.ToInt32(row["HBillStatus"]);
 
                Console.WriteLine($"单据状态: BillNo={billNo}, BillStatus={billStatus}, Checker={checker}, CloseMan={closeMan}, DeleteMan={deleteMan}, Backer={backer}");
 
                // 4. 业务规则检查
                if (IsAudit == 0)  // 作废判断
                {
                    // 检查是否已作废
                    if (billStatus == 4 || !string.IsNullOrEmpty(deleteMan))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已作废!不能再次作废!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查是否已审核通过(状态2)
                    if (billStatus == 2)
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已审核通过!请先反审核后再作废!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查是否已关闭(状态3)
                    if (billStatus == 3)
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据已关闭!请先反关闭后再作废!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查特殊状态(不允许作废的状态)
                    int[] notAllowedStatus = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17 };
                    if (notAllowedStatus.Contains(billStatus))
                    {
                        string statusMsg = GetStatusMessage(billStatus);
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = $"单据当前状态为{statusMsg},不允许作废!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                }
 
                if (IsAudit == 1) // 反作废判断
                {
                    // 检查是否已作废
                    if (billStatus != 4 || string.IsNullOrEmpty(deleteMan))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "单据未作废!不需要反作废!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                    // 检查作废后是否已被其他操作影响
                    object checkDateObj = row["HCheckDate"];
                    if (!string.IsNullOrEmpty(checker) && checkDateObj != DBNull.Value && checkDateObj != null)
                    {
                        DateTime checkDate = Convert.ToDateTime(checkDateObj);
                        object deleteDateObj = row["HDeleteDate"];
                        if (deleteDateObj != DBNull.Value && deleteDateObj != null)
                        {
                            DateTime deleteDate = Convert.ToDateTime(deleteDateObj);
                            if (checkDate > deleteDate)
                            {
                                objJsonResult.code = "0";
                                objJsonResult.count = 0;
                                objJsonResult.Message = "单据作废后有审核记录,不能反作废!";
                                objJsonResult.data = null;
                                return objJsonResult;
                            }
                        }
                    }
                }
 
                // 5. 开始事务处理
                oCN.BeginTran();
 
                try
                {
                    if (IsAudit == 0) // 作废操作
                    {
                        // 作废前控制
                        string beforeDropSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_BeforeDropCtrl {HInterID}, '{billNo}', '{CurUserName}'";
                        Console.WriteLine($"作废前控制SQL: {beforeDropSql}");
 
                        DataSet beforeDropDs = oCN.RunProcReturn(beforeDropSql, "BeforeDropCtrl");
 
                        if (beforeDropDs == null || beforeDropDs.Tables.Count == 0 || beforeDropDs.Tables[0].Rows.Count == 0)
                        {
                            throw new Exception("作废前判断失败,请与网络管理人员联系");
                        }
 
                        if (beforeDropDs.Tables[0].Rows[0]["HBack"]?.ToString() != "0")
                        {
                            string errorMsg = beforeDropDs.Tables[0].Rows[0]["HRemark"]?.ToString() ?? "作废前验证失败";
                            throw new Exception(errorMsg);
                        }
 
                        // 获取当前状态,用于记录日志
                        string originalStatus = GetStatusMessage(billStatus);
 
                        // 执行作废
                        string dropSql = $@"
                    UPDATE Gy_SteppedPriceCoefficientBillMain 
                    SET 
                        HDeleteMan = '{CurUserName.Replace("'", "''")}',
                        HDeleteDate = GETDATE(),
                        HBillStatus = 4  -- 已作废状态
                    WHERE HInterID = {HInterID}";
 
                        Console.WriteLine($"作废SQL: {dropSql}");
                        oCN.RunProc(dropSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 记录作废日志
                        string logSql = $@"
                    INSERT INTO Gy_SteppedPriceCoefficientBillLog (
                        HInterID, HBillNo, HOperation, HOperator,
                        HOperationDate, HOriginalStatus, HNewStatus,
                        HRemark
                    ) VALUES (
                        {HInterID}, '{billNo}', '作废', '{CurUserName.Replace("'", "''")}',
                        GETDATE(), '{originalStatus}', '已作废',
                        '单据从{originalStatus}状态作废'
                    )";
                        oCN.RunProc(logSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 作废后控制
                        string afterDropSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_AfterDropCtrl {HInterID}, '{billNo}', '{CurUserName}'";
                        oCN.RunProc(afterDropSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        oCN.Commit();
 
                        Console.WriteLine("作废成功完成");
 
                        objJsonResult.code = "1";
                        objJsonResult.count = 1;
                        objJsonResult.Message = "作废成功!";
                        objJsonResult.data = new { HInterID = HInterID, HBillNo = billNo };
                        return objJsonResult;
                    }
 
                    if (IsAudit == 1) // 反作废操作
                    {
                        // 反作废前控制
                        string beforeUnDropSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_BeforeUnDropCtrl {HInterID}, '{billNo}', '{CurUserName}'";
                        Console.WriteLine($"反作废前控制SQL: {beforeUnDropSql}");
 
                        DataSet beforeUnDropDs = oCN.RunProcReturn(beforeUnDropSql, "BeforeUnDropCtrl");
 
                        if (beforeUnDropDs == null || beforeUnDropDs.Tables.Count == 0 || beforeUnDropDs.Tables[0].Rows.Count == 0)
                        {
                            throw new Exception("反作废前判断失败,请与网络管理人员联系");
                        }
 
                        if (beforeUnDropDs.Tables[0].Rows[0]["HBack"]?.ToString() != "0")
                        {
                            string errorMsg = beforeUnDropDs.Tables[0].Rows[0]["HRemark"]?.ToString() ?? "反作废前验证失败";
                            throw new Exception(errorMsg);
                        }
 
                        // 获取原状态(从日志中获取或根据情况判断)
                        int originalStatus = 1; // 默认返回未审核状态
 
                        // 尝试从日志中获取作废前的状态
                        string getOriginalStatusSql = $@"
                    SELECT TOP 1 HOriginalStatus 
                    FROM Gy_SteppedPriceCoefficientBillLog 
                    WHERE HInterID = {HInterID} AND HOperation = '作废' 
                    ORDER BY HOperationDate DESC";
 
                        DataSet statusDs = oCN.RunProcReturn(getOriginalStatusSql, "GetOriginalStatus");
                        if (statusDs != null && statusDs.Tables[0].Rows.Count > 0)
                        {
                            string originalStatusStr = statusDs.Tables[0].Rows[0]["HOriginalStatus"]?.ToString() ?? "";
                            originalStatus = GetStatusFromMessage(originalStatusStr);
                        }
 
                        // 执行反作废
                        string unDropSql = $@"
                    UPDATE Gy_SteppedPriceCoefficientBillMain 
                    SET 
                        HDeleteMan = '',
                        HDeleteDate = NULL,
                        HBillStatus = {originalStatus}  -- 返回作废前的状态
                    WHERE HInterID = {HInterID}";
 
                        Console.WriteLine($"反作废SQL: {unDropSql}");
                        oCN.RunProc(unDropSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 记录反作废日志
                        string newStatusMsg = GetStatusMessage(originalStatus);
                        string logSql = $@"
                    INSERT INTO Gy_SteppedPriceCoefficientBillLog (
                        HInterID, HBillNo, HOperation, HOperator,
                        HOperationDate, HOriginalStatus, HNewStatus,
                        HRemark
                    ) VALUES (
                        {HInterID}, '{billNo}', '反作废', '{CurUserName.Replace("'", "''")}',
                        GETDATE(), '已作废', '{newStatusMsg}',
                        '单据反作废,恢复为{newStatusMsg}状态'
                    )";
                        oCN.RunProc(logSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        // 反作废后控制
                        string afterUnDropSql = $"exec h_p_Gy_SteppedPriceCoefficientBill_AfterUnDropCtrl {HInterID}, '{billNo}', '{CurUserName}'";
                        oCN.RunProc(afterUnDropSql, ref DBUtility.ClsPub.sExeReturnInfo);
 
                        oCN.Commit();
 
                        Console.WriteLine("反作废成功完成");
 
                        objJsonResult.code = "1";
                        objJsonResult.count = 1;
                        objJsonResult.Message = "反作废成功!";
                        objJsonResult.data = new { HInterID = HInterID, HBillNo = billNo };
                        return objJsonResult;
                    }
 
                    // 参数错误
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无效的操作类型!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                catch (Exception ex)
                {
                    oCN.RollBack();
                    Console.WriteLine($"操作失败: {ex.Message}");
                    throw new Exception("操作失败:" + ex.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"执行失败: {e.Message}");
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "执行失败!" + e.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 辅助方法 - 状态转换(放在类级别)
        /// <summary>
        /// 获取状态对应的文字描述
        /// </summary>
        private string GetStatusMessage(int status)
        {
            switch (status)
            {
                case 1: return "未审";
                case 2: return "审核通过";
                case 3: return "关闭";
                case 4: return "作废";
                case 5: return "审核退回";
                case 6: return "审核中";
                case 7: return "已阅";
                case 8: return "已回复";
                case 9: return "结案";
                case 10: return "验证";
                case 11: return "下达";
                case 12: return "开工";
                case 13: return "申请审批";
                case 15: return "申请检验";
                case 16: return "判定合格";
                case 17: return "判定不合格";
                default: return "未知状态";
            }
        }
 
        /// <summary>
        /// 根据状态描述获取状态值
        /// </summary>
        private int GetStatusFromMessage(string statusMessage)
        {
            switch (statusMessage)
            {
                case "未审": return 1;
                case "审核通过": return 2;
                case "关闭": return 3;
                case "作废": return 4;
                case "审核退回": return 5;
                case "审核中": return 6;
                case "已阅": return 7;
                case "已回复": return 8;
                case "结案": return 9;
                case "验证": return 10;
                case "下达": return 11;
                case "开工": return 12;
                case "申请审批": return 13;
                case "申请检验": return 15;
                case "判定合格": return 16;
                case "判定不合格": return 17;
                default: return 1; // 默认返回未审
            }
        }
 
        /// <summary>
        /// 检查是否可以作废
        /// </summary>
        private bool CanDropBill(int billStatus)
        {
            // 允许作废的状态
            int[] allowedStatus = { 1, 5, 6, 7, 8 }; // 未审、审核退回、审核中、已阅、已回复
            return allowedStatus.Contains(billStatus);
        }
        #endregion
 
        #region 数据模型类
        public class Gy_SteppedPriceCoefficient
        {
            //主表字段
            public long HInterID { get; set; }
            public int HYear { get; set; }
            public int HPeriod { get; set; }
            public string HBillType { get; set; }
            public string HBillSubType { get; set; }
            public DateTime HDate { get; set; }
            public string HBillNo { get; set; }
            public int HBillStatus { get; set; }
            public string HRemark { get; set; }
            public int HProcID { get; set; }
            public int HEmpID { get; set; }
            public int HDeptID { get; set; }
            public int HStockOrgID { get; set; }
 
            //子表集合
            public List<Gy_SteppedPriceCoefficientSub> SubItems { get; set; }
        }
 
        public class Gy_SteppedPriceCoefficientSub
        {
            public long HEntryID { get; set; }
            public int HSeq { get; set; }
            public int HMinQty { get; set; }
            public int HMaxQty { get; set; }
            public decimal HPriceCoefficient { get; set; }
            public decimal HMaxPrice { get; set; }
            public string HRemark { get; set; }
        }
        #endregion
    }
}