UpstreamSendCalendar.cs 69.4 KB
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
using AutoMapper;
using Hh.Mes.Common.Json;
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.ApiEntity;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.ViewModel;
using Hh.Mes.POJO.WebEntity;
using Hh.Mes.POJO.WebEntity.api;
using Hh.Mes.Service.Material;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Ubiety.Dns.Core;
using static Microsoft.AspNetCore.Hosting.Internal.HostingApplication;

namespace Hh.Mes.Service.ApiService
{
    public partial class UpstreamService
    {
        public dynamic SendCalendar(CalendarEntity entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new ResponseUpstream<string>(entity.plmeid);
                var calendar = new base_calendar
                {
                    keys = Guid.NewGuid(),
                    plmeId = entity.plmeid,
                    workShopCode = entity.work_code,
                    currentDate = entity.current_date,
                    shift = entity.shift,
                    startTime = entity.start_time,
                    endTime = entity.end_time,
                    timeFlag = entity.time,

                    isDelete = AddOrUpdateFlag
                };
                int resultCount = 0;
                if (entity.type == EnumAction.I.ToString())
                {
                    if (Context.Queryable<base_calendar>().Any(t => t.plmeId == calendar.plmeId && t.isDelete == AddOrUpdateFlag))
                    {
                        return response.ResponseError($"【MOM】【plmeid】日历信息[{entity.plmeid}]已经存在,请勿重复添加!");
                    }
                    calendar.createTime = DateTime.Now;
                    resultCount = Context.Insertable(calendar).ExecuteCommand();
                }
                else if (entity.type == EnumAction.U.ToString())
                {
                    calendar.updateTime = DateTime.Now;
                    resultCount = Context.Updateable(calendar).IgnoreColumns(it => new { it.keys, it.createBy, it.createTime })
                    .Where(x => x.plmeId == entity.plmeid && x.isDelete == AddOrUpdateFlag)
                    .ExecuteCommand();
                }
                else if (entity.type == EnumAction.D.ToString())
                {
                    calendar.updateTime = DateTime.Now;
                    resultCount = Context.Updateable<base_calendar>()
                                              .SetColumns(t => t.isDelete == DeleteFlag)
                                              .Where(x => x.plmeId.Equals(entity.plmeid) && x.isDelete == AddOrUpdateFlag)
                                              .ExecuteCommand();
                }
                return resultCount > 0 ? response.ResponseSuccess() : response.ResponseError();
            });
        }

        /// <summary>
        /// ep3d订单推送接收
        /// </summary>
        /// <returns></returns>
        public dynamic ep3dDataPush(productionOrderList list)
        {
            var response = new POJO.Response.Response();
            try
            {
                var importbachnumber = DateTime.Now.ToString("yyyyMMddhhmmss");

                //重复数据去除
                var dBList = Context.Queryable<base_productionOrder_EP3D>().ToList();
                if (dBList.Count > 0)
                {
                    list.details = list.details.Where(x => !dBList.Exists(y => y.pipelineNo == x.pipelineNo && y.pipeSectionNo == x.pipeSectionNo)).ToList();
                }

                foreach (var model in list.details)
                {
                    model.keys = Guid.NewGuid();
                    model.state = 0;
                    model.createTime = DateTime.Now;
                    model.updateTime = DateTime.Now;
                    model.batchNo = importbachnumber;
                }

                int inI = Context.Insertable(list.details).ExecuteCommand();
                if (inI > 0)
                {
                    return response;
                }
                else
                {
                    return response.ResponseError($"数据接收失败,新增数据数量为0!");
                }

            }
            catch (Exception ex)
            {
                return response.ResponseError($"{ex.Message}");
            }
        }



        public dynamic SendWorkOrderByYZJ(List<base_work_order> work_orders)
        {
            var response = new POJO.Response.Response();
            if (work_orders.Count < 1)
            {
                return response.ResponseError("数据为空!");
            }

            List<sys_dict_data> lineCodes = base.Context.Queryable<sys_dict_data>().Where(x => x.dictType == "LineCode").ToList();
            foreach (var work_order in work_orders)
            {
                string errMsg = "";
                if (string.IsNullOrEmpty(work_order.workOrderCode))
                {
                    errMsg += "生产订单号不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.lineCode))
                {
                    errMsg += "生产线不能为空;";
                }
                else
                {
                    if (lineCodes.Where(x => x.dictLabel == work_order.lineCode).ToList().Count < 1)
                    {
                        errMsg += "生产线编号不正确;";
                    }
                }

                if (string.IsNullOrEmpty(work_order.workPieceNo))
                {
                    errMsg += "工件编码不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.pipePartsCode))
                {
                    errMsg += "管件9位码不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.paintCode))
                {
                    errMsg += "涂装代码不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.assemblageInfo))
                {
                    errMsg += "组立信息不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.range))
                {
                    errMsg += "系列不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.turningAngle))
                {
                    errMsg += "扭转角度不能为空;";
                }
                if (string.IsNullOrEmpty(work_order.cutLength.ToString()))
                {
                    errMsg += "切断长不能为空;";
                }
                //if (work_order.bends == null)
                //{
                //    errMsg += "弯管信息不能为空;";
                //}
                //if (work_order.Cuts == null)
                //{
                //    errMsg += "切割信息不能为空;";
                //}

                //var orderList = Context.Queryable<base_work_order_head>().First(x => x.workOrderCode == work_order.workOrderCode && x.processStatus != "3");
                //if (orderList != null)
                //{
                //    errMsg += $"工单{work_order.workOrderCode}已存在;";
                //} 
                if (errMsg.Length > 0)
                {
                    errMsg = work_order.workOrderCode + errMsg;
                    // Log4NetHelper.Instance.Info($"数据校验未通过:{errMsg}");
                    return response.ResponseError(errMsg);
                }
                //上游系统给的数据可能为空
                if (work_order.Cuts != null)
                {
                    work_order.Cuts.RemoveAll(x => x.lenth == null);
                }

            }

            //物料校验 增加物料和组队法兰 校验
            List<string> matList = work_orders.Select(x => x.materielCode).Distinct().ToList();
            List<string> attachment1s = work_orders.Where(x => !string.IsNullOrEmpty(x.attachment1)).Select(x => x.attachment1).Distinct().ToList();
            List<string> attachment2s = work_orders.Where(x => !string.IsNullOrEmpty(x.attachment2)).Select(x => x.attachment1).Distinct().ToList();
            if (attachment1s.Count > 0)
            {
                matList.AddRange(attachment1s);
            }
            if (attachment2s.Count > 0)
            {
                matList.AddRange(attachment2s);
            }
            matList = matList.Distinct().ToList();

            List<string> baseMateriel = Context.Queryable<base_material>().Select(x => x.materialCode).Distinct().ToList();
            string matErr = "";
            foreach (string item in matList)
            {
                if (!baseMateriel.Contains(item) && !string.IsNullOrEmpty(item))
                {
                    matErr += $"{item};"; 
                }
            }
            if (matErr.Length > 0)
            {
                return response.ResponseError($"物料不存在[{matErr}] ");
            }

            //校验重复
            foreach (var item in work_orders)
            {
                var orderList = Context.Queryable<base_work_order_head>().Where(x => x.workOrderCode == item.workOrderCode && x.pipePartsNo == item.pipePartsNo && x.workPieceNo == item.workPieceNo && x.processStatus != "3").ToList();
                if (orderList.Count > 0) //判断重复
                {
                    return response.ResponseError($"管件[{item.pipePartsNo}] 和工单[{item.workOrderCode}] 已存在。");
                }
            }

            string createUser = "Api";
            if (!string.IsNullOrEmpty(sysUserApi?.Account))
            {
                createUser = sysUserApi?.Account;
            }





            Context.Ado.BeginTran();
            try
            {
                string plan_code = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                int plan_index = 1;
                foreach (var work_order in work_orders)
                {
                    Guid keys = Guid.NewGuid();
                    base_work_order_head order_head = GetWorkOrderModel(work_order);
                    order_head.keys = keys;
                    order_head.planCode = $"{plan_code}-{plan_index.ToString("000000")}";
                    //生成工艺路线和工单任务
                    // CreateProjectAndWorkOrder(order_head, work_order);
                    if (string.IsNullOrEmpty(order_head.bevels1))
                    {
                        order_head.bevels1 = "0";
                    }
                    if (string.IsNullOrEmpty(order_head.bevels2))
                    {
                        order_head.bevels2 = "0";
                    }
                    int inI = Context.Insertable(order_head).ExecuteCommand();

                    //弯管信息
                    base_work_order_bends bends = work_order.bends;
                    if (bends != null)
                    {

                        bends.headKeys = keys;
                        bends.createBy = createUser;
                        bends.createTime = DateTime.Now;
                        Context.Insertable(bends).ExecuteCommand();
                    }

                    if (work_order.Cuts != null)
                    {
                        //切割数据
                        List<Work_Order_FlameCut> flameCuts = work_order.Cuts;
                        List<base_work_order_flameCut_d> flameCut_d = new List<base_work_order_flameCut_d>();
                        List<base_work_order_endinfo> endinfos = new List<base_work_order_endinfo>();
                        List<base_work_order_holes> holes = new List<base_work_order_holes>();
                        if (flameCuts != null && flameCuts.Count > 0)
                        {
                            foreach (var item in flameCuts)
                            {
                                Guid guid = Guid.NewGuid();
                                item.headKeys = keys;
                                item.createBy = createUser;
                                item.createTime = DateTime.Now;
                                item.headKeys = keys;
                                item.Keys = guid;
                                if (item.Cut_D !=null && item.Cut_D.Count > 0)
                                {
                                    foreach (var FlameCut_D_Item in item.Cut_D)
                                    {
                                        base_work_order_flameCut_d flameCut_d1 = FlameCut_D_Item;
                                        flameCut_d1.headKeys = guid;
                                        flameCut_d1.createBy = createUser;
                                        flameCut_d1.createTime = DateTime.Now;
                                        flameCut_d.Add(flameCut_d1);
                                    }
                                }
                                if (item.EndInfos != null && item.EndInfos.Count>0)
                                {
                                    foreach (var endinfo in endinfos)
                                    {

                                        endinfo.headKeys = guid;
                                        endinfo.createBy = createUser;
                                        endinfo.createTime = DateTime.Now;
                                        endinfos.Add(endinfo);
                                    }
                                }
                                if (item.Holes !=null && item.Holes.Count >0 )
                                {
                                    foreach (var hole in item.Holes)
                                    { 
                                        hole.headKeys = guid;
                                        hole.createBy = createUser;
                                        hole.createTime = DateTime.Now;
                                        holes.Add(hole);
                                    }
                                } 
                            }


                            //  Mapper.Initialize(x => x.CreateMap<Work_Order_FlameCut, base_work_order_flameCut>());
                            List<base_work_order_flameCut> flameCuts2 = new List<base_work_order_flameCut>();
                            foreach (Work_Order_FlameCut item in flameCuts)
                            {
                                base_work_order_flameCut f = new base_work_order_flameCut(); //   Mapper.Map<base_work_order_flameCut>(item);
                                CopyModel(f, item);
                                flameCuts2.Add(f);
                            }

                            Context.Insertable(flameCuts2).ExecuteCommand();
                            Context.Insertable(flameCut_d).ExecuteCommand();
                            if (holes!= null&& holes.Count>0)
                            {
                                Context.Insertable(holes).ExecuteCommand();
                            }
                            if (endinfos != null && endinfos.Count > 0)
                            {
                                Context.Insertable(endinfos).ExecuteCommand();
                            }

                        }
                    }
                    if (work_order.mounting != null)
                    {
                        //装配信息
                        List<base_work_order_mounting> mounting = work_order.mounting;
                        foreach (var item in mounting)
                        {
                            item.headKeys = keys;
                            item.createBy = createUser;
                            item.createTime = DateTime.Now;
                        }
                        Context.Insertable(mounting).ExecuteCommand();
                    }
                    plan_index++;
                }
                Context.Ado.CommitTran();
                return response.ResponseSuccess();
            }
            catch (Exception ex)
            {
                Log4NetHelper.Instance.Error($"数据处理失败,错误信息:{ex.Message}");
                Context.Ado.RollbackTran();
                return response.ResponseError($"{ex.Message}");
            }

        }
        /// <summary>
        /// 模型赋值
        /// </summary>
        /// <param name="target">目标</param>
        /// <param name="source">数据源</param>
        public static void CopyModel<T, M>(T target, M source)
        {
            Type targetType = target.GetType();
            Type sourceType = source.GetType();
            foreach (var mi in sourceType.GetProperties())
            {
                var des = targetType.GetProperty(mi.Name);
                if (des != null)
                {
                    des.SetValue(target, mi.GetValue(source));
                }
            }
        }

        /// <summary>
        /// 通过列比对是否一致
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static bool ArePropertiesEqual<T>(List<T> obj1, List<T> obj2, string propertyName)
        {
            if (obj1.Count != obj2.Count) return false;
            PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
            if (propertyInfo == null)
            {
                throw new ArgumentException("Property not found");
            }

            //object value1 = propertyInfo.GetValue(obj1);
            //object value2 = propertyInfo.GetValue(obj2);
            List<string> value1 = new List<string>();
            List<string> value2 = new List<string>();
            foreach (var item in obj1)
            {
                value1.Add(propertyInfo.GetValue(item).ToString());
            }
            foreach (var item in obj2)
            {
                value2.Add(propertyInfo.GetValue(item).ToString());
            }
            value1.Sort();
            value2.Sort();
            return value1.Except(value2).ToList().Count < 1;

            //return Equals(value1, value2);
        }

        public base_work_order_head GetWorkOrderModel(base_work_order work_order)
        {
            base_work_order_head head = new base_work_order_head();
            head.assemblageInfo = work_order.assemblageInfo;
            head.attachment1 = work_order.attachment1;
            head.attachment2 = work_order.attachment2;
            head.bevels1 = work_order.bevels1;
            head.bevels2 = work_order.bevels2;
            head.cutLength = work_order.cutLength;
            head.diameter = work_order.diameter;
            head.extend1 = work_order.extend1;
            head.extend2 = work_order.extend2;
            head.extend3 = work_order.extend3;
            head.extend4 = work_order.extend4;
            head.flowOrientation1 = work_order.flowOrientation1;
            head.flowOrientation2 = work_order.flowOrientation2;
            head.instructions1 = work_order.instructions1;
            head.instructions2 = work_order.instructions2;
            head.level = work_order.level;
            head.lineCode = work_order.lineCode;
            head.materielCode = work_order.materielCode;
            head.paintCode = work_order.paintCode;
            head.pipePartsCode = work_order.pipePartsCode;
            head.pipePartsNo = work_order.pipePartsNo;
            head.projectNo = work_order.projectNo;
            head.range = work_order.range;
            head.startWorkDate = work_order.startWorkDate;
            head.thickness = work_order.thickness;
            head.turningAngle = work_order.turningAngle;
            head.workOrderCode = work_order.workOrderCode;
            head.workPieceNo = work_order.workPieceNo;
            head.attachment1PrintInfo = work_order.attachment1PrintInfo;
            head.attachment2PrintInfo = work_order.attachment2PrintInfo;
            if (!string.IsNullOrEmpty(sysUserApi?.Account))
            {
                head.createBy = sysUserApi?.Account;
                head.updateby = sysUserApi?.Account;
            }
            else
            {
                head.createBy = "Api";
                head.updateby = "Api";
            }
            head.createTime = DateTime.Now;
            head.processStatus = "0";
            return head;
        }

        /// <summary>
        /// 创建工单任务
        /// </summary>
        /// <param name="work_order"></param>
        /// <param name="b_order"></param>
        /// <returns></returns>
        public bool CreateProjectAndWorkOrder(base_work_order_head work_order, base_work_order b_order)
        {
            #region 现在不需要项目相关信息了
            /*  base_project entity =   Context.Queryable<base_project>().Where(x => x.projectNo.Equals(work_order.projectNo)).First();
             // 如果项目不存在创建项目及工艺路线
             if (entity == null)
             {
                 entity = new base_project();
                 Guid projectKeys = Guid.NewGuid();
                 entity.projectNo = work_order.projectNo;
                 entity.projectName = work_order.projectNo;
                 //  entity.createBy = sysWebUser.Account;
                 entity.createTime = DateTime.Now;
                 entity.keys = projectKeys;
                 entity.state = 0;//默认 未开始状态
                 entity.scheduledStartTime = work_order.startWorkDate;
                 entity.scheduledEntTime = work_order.startWorkDate;
                 // entity.processKeys = work_order.keys;
                 Context.Insertable(entity).ExecuteCommand();
                 List<base_work_center> work_Centers = Context.Queryable<base_work_center>().Where(x => x.isDelete.Equals("1")).ToList();
             }

             base_project_production_order base_Project_Production_Order = new base_project_production_order();
             base_Project_Production_Order.projectKeys = entity.keys;
             base_Project_Production_Order.productionOrderKey = work_order.keys;
             base_Project_Production_Order.createTime = DateTime.Now;
             base_Project_Production_Order.updateTime = DateTime.Now;
             base_Project_Production_Order.keys = Guid.NewGuid();
             Context.Insertable(base_Project_Production_Order).ExecuteCommand();
            */
            #endregion

            //生成工单信息
            base_productionOrder_EP3D order = new base_productionOrder_EP3D();
            CopyModel(order, work_order);
            order.pipeSectionNo = work_order.pipePartsNo;
            order.pipelineGrade = work_order.level;
            order.weldingMaterial1 = work_order.instructions1;
            order.weldingPointNo1 = !string.IsNullOrEmpty(work_order.instructions1) ? "HK01" : "";
            order.weldingMaterial2 = work_order.instructions2;
            order.weldingPointNo2 = !string.IsNullOrEmpty(work_order.instructions2) ? "HK02" : "";
            order.keys = work_order.keys;
            order.state = 0;
            order.pipeLength = work_order.cutLength;
            order.pipeMaterialCode = work_order.materielCode;
            order.curvedAngle = string.IsNullOrEmpty(work_order.turningAngle) ? 0 : decimal.Parse(work_order.turningAngle);
            Context.Insertable(order).ExecuteCommand();

            //获取工艺路线
            Guid guid = InitRoute(b_order);

            bus_workOrder_head bus_WorkOrder_Head = new bus_workOrder_head();
            CopyModel(bus_WorkOrder_Head, work_order);
            bus_WorkOrder_Head.isDelete = 0;
            bus_WorkOrder_Head.isScrap = false;
            bus_WorkOrder_Head.processHeadKeys = guid;
            bus_WorkOrder_Head.projectCode = work_order.projectNo;
            bus_WorkOrder_Head.projectName = work_order.projectNo;
            bus_WorkOrder_Head.planCode = DateTime.Now.ToString("yyyyMMddHHmmss");
            bus_WorkOrder_Head.workOrderName = work_order.workOrderCode;
            bus_WorkOrder_Head.orderType = "1";
            bus_WorkOrder_Head.state = 0;
            bus_WorkOrder_Head.productName = "YZJ工单";
            bus_WorkOrder_Head.planStartTime = work_order.startWorkDate;
            bus_WorkOrder_Head.planEndTime = work_order.startWorkDate;
            bus_WorkOrder_Head.nowOprSequenceCode = "LoadMaterial";
            bus_WorkOrder_Head.productHeaderCode = "YZJ";
            Context.Insertable(bus_WorkOrder_Head).ExecuteCommand();

            bool b = CreateRouteTaskInfo(guid, bus_WorkOrder_Head, order);

            return true;
        }



        private bool CreateRouteTaskInfo(Guid guid, bus_workOrder_head busWorkOrderHead, base_productionOrder_EP3D order)
        {
            var processDetail = Context.Queryable<base_process_route_detail>()
                    .Where(x => x.headkeys == guid).OrderBy(x => x.oprSequence, OrderByType.Asc).ToList();
            foreach (var item in processDetail)
            {
                var qualityDetail = new List<base_qualityStencil_detail>();


                #region  生成工序任务明细 busWorkOrderDetailList
                var busWorkOrderDetailList = new List<bus_workOrder_detail>();
                var nowWorkDetail = new bus_workOrder_detail
                {
                    headKeys = busWorkOrderHead.keys,
                    productHeaderCode = busWorkOrderHead.productHeaderCode,
                    workOrderCode = busWorkOrderHead.workOrderCode,

                    cutMaterCode = order.pipeMaterialCode,
                    cuttingLength = order.pipeLength,

                    lineCode = busWorkOrderHead.lineCode,
                    // designNo = order.pagination,
                    // designUrl = order.pipelineNo + ".pdf", 扬子江没有该信息

                    barCode = order.workPieceNo,
                    partCode = order.workPieceNo,  // order.pipelineNo.Trim(),

                    serialNumber = item.oprSequence,
                    oprSequenceCode = item.oprSequenceCode,
                    oprSequenceName = item.oprSequenceName,
                    workCenterCode = item.workCenterCode,
                    planStartTime = busWorkOrderHead.planStartTime,
                    planEndTime = busWorkOrderHead.planEndTime,

                    isEndProduct = 1,
                    isDelete = 1,
                    state = (int)EnumOrderBodyStatus.初始化,
                    workReportStatus = (int)EnumWorkReportStatus.未报工,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                nowWorkDetail.bodyKeys = Guid.NewGuid();
                nowWorkDetail.serialNumberName = nowWorkDetail.serialNumber + "_1";

                //如果是组对或焊接需要补充焊口信息
                if (item.workCenterCode == WorkCenterCode.组对 || item.workCenterCode == WorkCenterCode.焊接 || item.workCenterCode == WorkCenterCode.组焊)
                {
                    nowWorkDetail.weldNo = order.weldingPointNo1;
                    nowWorkDetail.weldMaterCode = order.weldingMaterial1;
                    busWorkOrderDetailList.Add(nowWorkDetail);

                    if (!string.IsNullOrEmpty(order.weldingPointNo2))
                    {
                        var nowWorkDetai2 = new bus_workOrder_detail
                        {
                            headKeys = busWorkOrderHead.keys,
                            productHeaderCode = busWorkOrderHead.productHeaderCode,
                            workOrderCode = busWorkOrderHead.workOrderCode,

                            cutMaterCode = order.pipeMaterialCode,
                            cuttingLength = order.pipeLength,

                            lineCode = busWorkOrderHead.lineCode,
                            //扬子江没有
                            //  designNo = order.pagination,
                            //  designUrl = order.pipelineNo + ".pdf",

                            barCode = order.workPieceNo,
                            partCode = order.workPieceNo,  // order.pipelineNo.Trim(),

                            serialNumber = item.oprSequence,
                            oprSequenceCode = item.oprSequenceCode,
                            oprSequenceName = item.oprSequenceName,
                            workCenterCode = item.workCenterCode,
                            planStartTime = busWorkOrderHead.planStartTime,
                            planEndTime = busWorkOrderHead.planEndTime,

                            isEndProduct = 1,
                            isDelete = 1,
                            state = (int)EnumOrderBodyStatus.初始化,
                            workReportStatus = (int)EnumWorkReportStatus.未报工,
                            createTime = DateTime.Now,
                            createBy = SystemVariable.DefaultCreated
                        };

                        nowWorkDetai2.bodyKeys = Guid.NewGuid();
                        nowWorkDetai2.serialNumberName = nowWorkDetail.serialNumber + "_2";
                        nowWorkDetai2.weldNo = order.weldingPointNo2;
                        nowWorkDetai2.weldMaterCode = order.weldingMaterial2;
                        busWorkOrderDetailList.Add(nowWorkDetai2);
                    }
                }
                else
                {
                    busWorkOrderDetailList.Add(nowWorkDetail);
                }

                Context.Insertable(busWorkOrderDetailList).ExecuteCommand();//   .AddQueue();
                #endregion

                #region  生成质检任务
                if (item.inspectionFlag == (int)EnumQualityisExecute.)
                {
                    foreach (var detail in qualityDetail)
                    {
                        var bqualityExecute = new base_qualityStencil_Execute
                        {
                            keys = Guid.NewGuid(),
                            projectKey = guid,
                            workOrderDetailKey = nowWorkDetail.bodyKeys,
                            qualityDetailKey = detail.keys,
                            isExecute = (int)EnumQualityisExecute.,//目前直接设置为是,正式项目需要改为否,需要上一工序完成后修改
                            executeResult = (int)EnumQualityExecute.未执行,
                            state = (int)EnumQuality.启用,
                            createTime = DateTime.Now,
                            updateTime = DateTime.Now
                        };

                        Context.Insertable(bqualityExecute).ExecuteCommand();// AddQueue();
                    }
                }
                #endregion
            }

            return true;
        }


        /// <summary>
        /// 获取工艺路线,没有就新增
        /// </summary>
        /// <param name="work_order"></param>
        /// <returns></returns>
        public Guid InitRoute(base_work_order work_order)
        {
            Guid processKeys = Guid.NewGuid();
            int orderNo = 1;
            List<base_process_route_detail> detailList = new List<base_process_route_detail>();
            base_process_route_detail d1 = new base_process_route_detail();
            d1.LineCode = work_order.lineCode;
            d1.oprSequenceCode = "LoadMaterial";
            d1.oprSequenceName = "上料";
            d1.oprSequence = orderNo;
            d1.isDelete = 1;
            d1.workCenterCode = "LoadMaterial";
            d1.remarks = work_order.projectNo;
            d1.createBy = "System";
            d1.createTime = DateTime.Now;
            detailList.Add(d1);

            orderNo += 1;
            base_process_route_detail d2 = new base_process_route_detail();
            //  d2.LineCode = work_order.lineCode;
            d2.oprSequenceCode = "Nesting";
            d2.oprSequenceName = "套料";
            d2.oprSequence = orderNo;
            d2.isDelete = 1;
            d2.workCenterCode = "Nesting";
            d2.createBy = "System";
            d2.createTime = DateTime.Now;
            detailList.Add(d2);

            if (work_order.Cuts.Count > 0)
            {
                orderNo += 1;
                base_process_route_detail dl = new base_process_route_detail();
                //  d2.LineCode = work_order.lineCode;
                dl.oprSequenceCode = "Cut";
                dl.oprSequenceName = "切割";
                dl.oprSequence = orderNo;
                dl.isDelete = 1;
                dl.workCenterCode = "Cut";
                dl.createBy = "System";
                dl.createTime = DateTime.Now;
                detailList.Add(dl);
            }

            // 组队,焊接
            if (!string.IsNullOrEmpty(work_order.bevels1))
            {
                orderNo += 1;
                base_process_route_detail dl = new base_process_route_detail();
                //  d2.LineCode = work_order.lineCode;
                dl.oprSequenceCode = "Bevel";
                dl.oprSequenceName = "坡口";
                dl.oprSequence = orderNo;
                dl.isDelete = 1;
                dl.workCenterCode = "Bevel";
                dl.createBy = "System";
                dl.createTime = DateTime.Now;
                detailList.Add(dl);
            }
            // 组队,焊接
            if (!string.IsNullOrEmpty(work_order.attachment1))
            {
                orderNo += 1;
                base_process_route_detail dl = new base_process_route_detail();
                //  d2.LineCode = work_order.lineCode;
                dl.oprSequenceCode = "FitUp";
                dl.oprSequenceName = "组队";
                dl.oprSequence = orderNo;
                dl.isDelete = 1;
                dl.workCenterCode = "FitUp";
                dl.createBy = "System";
                dl.createTime = DateTime.Now;
                detailList.Add(dl);

                orderNo += 1;
                base_process_route_detail d = new base_process_route_detail();
                //  d2.LineCode = work_order.lineCode;
                d.oprSequenceCode = "Weld";
                d.oprSequenceName = "焊接";
                d.oprSequence = orderNo;
                d.isDelete = 1;
                d.workCenterCode = "Weld";
                d.createBy = "System";
                d.createTime = DateTime.Now;
                detailList.Add(d);
            }

            //弯管
            if (work_order.flowOrientation1 == "W")
            {
                orderNo += 1;
                base_process_route_detail d = new base_process_route_detail();
                //  d2.LineCode = work_order.lineCode;
                d.oprSequenceCode = "bentPipe";
                d.oprSequenceName = "弯管";
                d.oprSequence = orderNo;
                d.isDelete = 1;
                d.workCenterCode = "bentPipe";
                d.createBy = "System";
                d.createTime = DateTime.Now;
                detailList.Add(d);
            }
            GetProcessKeys(detailList, ref processKeys, work_order);
            return processKeys;
        }

        //比对是否已经存在工艺路线,没有就创建
        private void GetProcessKeys(List<base_process_route_detail> detailList, ref Guid processKeys, base_work_order work_order)
        {

            var route_head = Context.Queryable<base_process_route_head>().Where(x => x.lineCode == work_order.lineCode).OrderBy(x => x.edition, SqlSugar.OrderByType.Desc).ToList();
            var route_detail = Context.Queryable<base_process_route_detail>().ToList();
            foreach (var item in route_head)
            {
                List<base_process_route_detail> curList = route_detail.Where(t => t.headkeys == item.keys).ToList();

                if (ArePropertiesEqual(detailList, curList, "oprSequenceCode"))
                {
                    processKeys = item.keys;
                    return;
                }
            }
            CreateRoutInfo(detailList, processKeys, work_order);
            return;
        }

        private void CreateRoutInfo(List<base_process_route_detail> detailList, Guid processKeys, base_work_order work_order)
        {
            base_process_route_head head = new base_process_route_head();
            head.edition = 1;
            head.keys = processKeys;
            head.processName = work_order.projectNo + "-" + work_order.workOrderCode;
            head.isDelete = 1;
            head.lineCode = work_order.lineCode;
            head.processCode = work_order.workOrderCode;
            head.productHeaderCode = "YZJ" + work_order.projectNo;
            head.createBy = "System";

            head.createTime = DateTime.Now;

            foreach (var item in detailList)
            {
                item.createBy = "System";
                item.createTime = DateTime.Now;
                item.headkeys = processKeys;
                item.inspectionFlag = 0;
                item.LineCode = work_order.lineCode;
            }
            Context.Insertable(detailList).ExecuteCommand();
            Context.Insertable(head).ExecuteCommand();
        }

        public  string lineCode { get; set; } = "line1";
        /// <summary>
        /// 获取字典的废料长度
        /// </summary>
        public decimal CutPlanLength
        {
            get
            {
                var CutPlan = "70";

                if (lineCode.ToUpper() == "Line1")
                {
                    CutPlan= GetDictionaryDictValue("CuttingWasteLength", "CutConfig");
                }
                else
                {
                    CutPlan = GetDictionaryDictValue($"CuttingWasteLength_{lineCode.ToUpper()}", "CutConfig");
                }
                if (CutPlan == null)
                    CutPlan = "250";

                return decimal.Parse(CutPlan);
            }
        }

        /// <summary>
        /// ecs反馈测长数据
        /// </summary>
        /// <param name="zx"></param>
        /// <returns></returns>
        public dynamic taskMeasuring(Measuring measuring)
        {
            var response = new POJO.Response.Response();
            string errMsg = "";
            if (measuring.taskLength <= 0)
            {
                errMsg += "测长长度错误;";
            }
            if (measuring.taskOrder <= 0)
            {
                errMsg += "测长顺序错误;";
            }

            var task = Context.Queryable<base_loader_task>().Where(x => x.taskCode == measuring.taskCode).First();

            if (task == null)
            {
                errMsg += "任务号错误,未查询到任务数据;";
            }

            if (errMsg.Length > 0)
            {
                return response.ResponseError(errMsg);
            }

            Context.Ado.BeginTran();
            try
            {
                //1.修改任务已测长数量
                task.feedbackNum += 1;
                task.updateTime = DateTime.Now;
                Context.Updateable(task).ExecuteCommand();

                var equipment = Context.Queryable<base_work_station>().First(x => x.workStationCode == task.equipmentCode);
                if (equipment == null)
                {
                    return response.ResponseError($"未查询到工位码【{task.equipmentCode}】信息,请核对!");
                }
                lineCode = equipment.lineCode;
                var pipeSN = measuring.taskCode;
                if (task.extend1 == ((int)EnumLoaderTaskType.原料上架).ToString())
                {
                    //2.将测长数据存入库存表
                    pipeSN = task.taskCode + "-" + measuring.taskOrder;
                    var inventory = new base_inventory();
                    inventory.lineCode = equipment.lineCode;
                    inventory.locationCode = task.equipmentCode;
                    inventory.materialCode = task.materialCode;
                    inventory.lot = measuring.taskOrder.ToString();
                    inventory.batchNo = task.taskCode;
                    inventory.pipeSN = pipeSN;
                    inventory.status = InventoryStatus.good.ToString();
                    inventory.pipeLength = measuring.taskLength;
                    inventory.useState = 0;
                    inventory.qty = 1;
                    inventory.createTime = DateTime.Now;

                    Context.Insertable(inventory).ExecuteCommand();
                }
                else
                {
                    var inventory = Context.Queryable<base_inventory>().First(x => x.pipeSN == measuring.taskCode);
                    if (inventory == null)
                    {
                        return response.ResponseError($"未查询到余料码【{measuring.taskCode}】信息,请核对!");
                    }

                    inventory.pipeLength = measuring.taskLength;
                    inventory.locationCode = task.equipmentCode;
                    inventory.status = InventoryStatus.good.ToString();
                    inventory.createTime = DateTime.Now;
                    inventory.updateTime = DateTime.Now;

                    Context.Updateable(inventory).ExecuteCommand();
                }

                Context.Ado.CommitTran();

                //3.测长完成后进行套料,小经线,中1线才自动套料 
                //自动套料禁用2025-9-24
                //if (equipment.lineCode.ToUpper() == EnumLine.小经线.ToUpper() || equipment.lineCode.ToUpper() == EnumLine.中1线.ToUpper() || equipment.lineCode.ToUpper() == EnumLine.三井小经线.ToUpper()  || equipment.lineCode.ToUpper() == EnumLine.三井中1线.ToUpper())
                //{
                    
                //    //var CutPlan = GetDictionaryDictValue("CuttingWasteLength", "CutConfig");
                //    //if (equipment.lineCode.ToUpper() == EnumLine.中1线.ToUpper())
                //    //{
                //    //    CutPlan = GetDictionaryDictValue($"CuttingWasteLength_{equipment.lineCode.ToUpper()}", "CutConfig");
                //    //}
                    
                //    //可套料库存
                //    var inventory = Context.Queryable<base_inventory>().Where(x =>
                //                                    x.pipeLength > CutPlanLength
                //                                    && x.useState == (int)InventoryUseState.未套料
                //                                    && x.status == InventoryStatus.good.ToString()
                //                                    && x.lineCode.ToUpper() == equipment.lineCode.ToUpper()
                //                                    ).OrderBy(x => x.createTime).First();

                //    if (inventory.pipeSN != pipeSN)
                //    {
                //        return response.ResponseError($"查询到测长管材前有未套料管材,需要在库存管理中核对,或手动进行套料,本次测长未进行自动套料!");
                //    }

                //    CutPlanCalculateService cutPlanCalculateService = new CutPlanCalculateService();
                //    cutPlanCalculateService.lineCode = equipment.lineCode;
                //    POJO.Response.Response response1 = cutPlanCalculateService.GetCutterInfo(equipment.lineCode);
                //    var cutList = response1.Result;
                //    if (cutList.Count == 0)
                //    {
                //        return response.ResponseError($"未查询到可以【套料】的工单!");

                //    }

                //    var workOrderList = (List<bus_workOrder_detail>)cutList;

                //    var cutIDs = string.Join(",", workOrderList.Where(x => x.parentTypeId == Guid.Parse("00000000-0000-0000-0000-000000000000")).ToList().Select(x => x.id));

                //    var cutPlan = cutPlanCalculateService.SaveCutPlan(cutIDs, equipment.lineCode);

                //    return cutPlan;
                //}

                return response.ResponseSuccess();
            }
            catch (Exception ex)
            {
                Context.Ado.RollbackTran();
                return response.ResponseError($"{ex.Message}");
            }

        }

        public dynamic OrderCamcel(List<base_work_order_cancel> work_orders)
        {
            var response = new POJO.Response.Response();
            if (work_orders.Count < 1)
            {
                return response.ResponseError($"请求数据为空");
            }
            //记录数据方便调试
            // Log4NetHelper.Instance.Info($"接收数据:{work_orders.to()}");
            //空数据校验
            string errMsg = string.Empty;
            foreach (var item in work_orders)
            {
                if (string.IsNullOrEmpty(item.workOrderCode))
                {
                    errMsg += "工单号不能为空";
                }
                if (string.IsNullOrEmpty(item.cancelTime.ToString()))
                {
                    errMsg += "取消时间不能为空";
                }
                if (errMsg.Length > 0)
                {
                    return response.ResponseError($"{errMsg}");
                }
                var orderList = Context.Queryable<base_work_order_head>().Where(x => x.workOrderCode == item.workOrderCode && x.processStatus != "3").First();
                if (orderList == null)
                {
                    errMsg += $"工单{item.workOrderCode}不存在,或者已取消";
                }

                //是否已经开始执行
                var busList = Context.Queryable<bus_workOrder_detail>().Where(x => x.workOrderCode == item.workOrderCode && x.state != 0 && x.oprSequenceCode != "BentPipe").OrderBy(x => x.createBy, OrderByType.Desc).First();
                if (busList != null)
                {
                    errMsg += $"工单{item.workOrderCode} 已经开始生产无法取消";
                }
                if (errMsg.Length > 0)
                {
                    return response.ResponseError($"{errMsg}");
                }
            }

            //数据处理
            foreach (var item in work_orders)
            {
                item.createBy = "Api";
                item.createTime = DateTime.Now;
                item.processStatus = "1";
                item.processMsg = "处理成功";
                try
                {
                    List<string> barCodes = Context.Queryable<base_work_order_head>().Where(x => x.workOrderCode == item.workOrderCode).ToList().Select(x => x.workPieceNo).ToList();
                    Context.Deleteable<base_imprint_task>().In(x => x.barCode ,barCodes).ExecuteCommand();
                    // 取消工单表
                    Context.Deleteable<base_work_order_head>().Where(x => x.workOrderCode == item.workOrderCode && x.processStatus != "3")
                        .ExecuteCommand();
                    //取消工单任务表
                    Context.Deleteable<bus_workOrder_head>().Where(x => x.workOrderCode == item.workOrderCode)
                        .ExecuteCommand();
                    Context.Deleteable<bus_workOrder_detail>().Where(x => x.workOrderCode == item.workOrderCode)
                        .ExecuteCommand();
                    // Context.Insertable<base_work_order_cancel>(item).ExecuteCommand();

                }
                catch (Exception ex)
                {
                    item.processStatus = "2";
                    item.processMsg = ex.Message;
                    Log4NetHelper.Instance.Error($"工单[{item.workOrderCode}]数据处理失败,错误信息:{ex.Message}");
                    return response.ResponseError($"数据处理失败");
                }
                Context.Insertable(item).ExecuteCommand();

            }

            return response;
        }

        public dynamic SendMaterialInfo(MaterialCodeInfos materialCodeInfos)
        {
            MaterialResult result = new MaterialResult();
            result.status = 1;

            if (materialCodeInfos.materialCodeInfos == null)
            {
                result.status = 0;
                result.errorcode = 500;
                result.error = "数据为空";
                return result;
            }
            if (materialCodeInfos.materialCodeInfos.Count < 1)
            {
                result.status = 0;
                result.errorcode = 500;
                result.error = "数据为空";
                return result;
            }
            string errMsg = "";
            foreach (api_Material_CodeInfos_YZJ item in materialCodeInfos.materialCodeInfos)
            {
                if (string.IsNullOrEmpty(item.ThirdPartyID))
                {
                    errMsg += "物料系统编码ID(内码)不能为空;";
                }
                if (string.IsNullOrEmpty(item.Code))
                {
                    errMsg += "物料编码不能为空;";
                }
                if (string.IsNullOrEmpty(item.MaterialDesc))
                {
                    errMsg += "物料描述不能为空;";
                }
                if (string.IsNullOrEmpty(item.MaterialUnit))
                {
                    errMsg += "物资单位不能为空;";
                }
                if (string.IsNullOrEmpty(item.Type))
                {
                    errMsg += "物料类型不能为空;";
                }
                //if (string.IsNullOrEmpty(item.internalCode))
                //{
                //    errMsg += "内码不能为空;";
                //}
                if (errMsg.Length > 0)
                {
                    result.status = 0;
                    result.errorcode = 500;
                    result.error = errMsg;
                    return result;
                }
            }

            foreach (api_Material_CodeInfos_YZJ item in materialCodeInfos.materialCodeInfos)
            {
                //内码就是物料ID
                //item.internalCode = item.ThirdPartyID;
                item.CreateBy = "api";
                item.CreateTime = DateTime.Now;
                //写入接口表
                Context.Insertable(item).ExecuteCommand();
                base_material material = Context.Queryable<base_material>().First(x => x.ThirdPartyID == item.ThirdPartyID);
                //有就更新没有就新增
                if (material == null)
                {
                    material = new base_material();
                    material = GetMaterial(item, false, ref material);
                    Context.Insertable(material).ExecuteCommand();
                }
                else
                {
                    if (item.Mark != "D")
                    {
                        material = GetMaterial(item, true, ref material);
                        Context.Updateable(material).ExecuteCommand();
                    }
                    else
                    {
                        //删除
                        //material = GetMaterial(item, true, ref material);
                        Context.Deleteable<base_material>().Where(x => x.keys == material.keys).ExecuteCommand();
                    }

                }
            }

            return result;

        }


        public base_material GetMaterial(api_Material_CodeInfos_YZJ model, bool isUpdate, ref base_material material)
        {
            // base_material material = new base_material();
            if (isUpdate)
            {
                material.updateBy = "Api";
                material.updateTime = DateTime.Now;

            }
            else
            {
                material.keys = Guid.NewGuid();
                material.createBy = "Api";
                material.createTime = DateTime.Now;
            }

            material.factoryCode = "YZJ";
            material.flag = 0;
            material.mtTypeCode = "material";
            material.materialCode = model.Code;
            material.materialName = model.MaterialDesc;
            material.types = model.Quality;
            material.specifications = model.Spec;
            material.unitCode = model.MaterialUnit;
            material.mtClassify = "pipe";//model.Type; 固定管子
            material.isDelete = model.Usable == "1" ? 1 : 0;
            material.ThirdPartyID = model.ThirdPartyID;
            material.ProductLevel1 = model.ProductLevel1;
            material.ProductLevel2 = model.ProductLevel2;
            material.ProductLevel3 = model.ProductLevel3;
            material.MaterialCategory = model.MaterialCategory;
            material.internalCode = model.internalCode;
            material.Usable = model.Usable;
            return material;
        }

        /// <summary>
        /// 余料记录
        /// </summary>
        /// <param name="headID">套料任务ID</param>
        /// <returns></returns>
        public dynamic SurplusRecord(string headID)
        {
            var response = new POJO.Response.Response();
            if (string.IsNullOrEmpty(headID))
            {
                return response.ResponseError($"套料任务ID为空!");
            }

            // 套料任务头表
            var cutplanHead = Context.Queryable<bus_cutplan_head>().First(x => x.id.ToString() == headID);
            if (cutplanHead == null)
            {
                return response.ResponseError($"未查询到套料任务!");
            }

            CutWeldService service = new CutWeldService();

            //2.将余料数据存入库存表 大于3000mm的余料才记录
            var oddLength = GetDictionaryDictValue("oddLength", "CutConfig");
            if (string.IsNullOrEmpty(oddLength))
            {
                oddLength = "3000";
            }

            if (cutplanHead.oddmentsLength >= decimal.Parse(oddLength))
            {
                var inventory = new base_inventory();
                inventory.lineCode = cutplanHead.lineCode;
                inventory.materialCode = cutplanHead.materialCode;
                inventory.lot = "1";
                inventory.batchNo = headID;
                inventory.pipeSN = cutplanHead.oddmentsCode;
                inventory.status = InventoryStatus.discussed.ToString();
                inventory.pipeLength = cutplanHead.oddmentsLength;
                inventory.useState = 0;
                inventory.qty = 1;
                inventory.createTime = DateTime.Now;

                Context.Insertable(inventory).ExecuteCommand();

                //3.反馈上游余料-新增
                OddFeelBackModel oddFeelBackModel = new OddFeelBackModel();
                oddFeelBackModel.OddCode = cutplanHead.oddmentsCode;
                oddFeelBackModel.MaterialCode = cutplanHead.materialCode;
                oddFeelBackModel.Length = cutplanHead.oddmentsLength.ToString();
                oddFeelBackModel.CreateDate = DateTime.Now.ToString();
                oddFeelBackModel.State = "0";
                if (string.IsNullOrEmpty(cutplanHead.lotNo))
                {
                    oddFeelBackModel.OddCode = cutplanHead.lotNo;
                    oddFeelBackModel.State = "1";
                    oddFeelBackModel.OddCode2 = cutplanHead.oddmentsCode;
                }

                service.OddFeedBack(oddFeelBackModel);
            }
            //3.反馈上游余料-使用
            else if (string.IsNullOrEmpty(cutplanHead.lotNo))
            {
                OddFeelBackModel oddFeelBackModel = new OddFeelBackModel();
                oddFeelBackModel.OddCode = cutplanHead.lotNo;
                oddFeelBackModel.MaterialCode = cutplanHead.materialCode;
                oddFeelBackModel.Length = cutplanHead.oddmentsLength.ToString();
                oddFeelBackModel.CreateDate = DateTime.Now.ToString();
                oddFeelBackModel.State = "1";

                service.OddFeedBack(oddFeelBackModel);
            }

            //4.反馈切割工序完工


            return response;
        }

        public dynamic strReplace(string workOrderCOde)
        {
            var response = new POJO.Response.Response();
            List<base_work_order_head> heads = Context.Queryable<base_work_order_head>().Where(x => x.workOrderCode == workOrderCOde).ToList();
            foreach (var item in heads)
            {
                Context.Updateable<base_work_order_head>().SetColumns(x => x.paintPrintCode == item.paintPrintCode.Replace("Ø", "?"))
                    .Where(x => x.keys == item.keys).ExecuteCommand();
            }
            return response;
        }

        public dynamic DeleteOrder(string workOrderCOde)
        {
            var response = new POJO.Response.Response();
            try
            {
                List<string>  barCodes = Context.Queryable<base_work_order_head>().Where(x => x.workOrderCode == workOrderCOde).ToList().Select(x=> x.workPieceNo).ToList(); 
                Context.Deleteable<base_imprint_task>().In(x => x.barCode, barCodes).ExecuteCommand();
                Context.Deleteable<bus_workOrder_detail>().Where(x => x.workOrderCode == workOrderCOde).ExecuteCommand();
                Context.Deleteable<bus_workOrder_head>().Where(x => x.workOrderCode == workOrderCOde).ExecuteCommand();
                Context.Deleteable<base_work_order_head>().Where(x => x.workOrderCode == workOrderCOde).ExecuteCommand();
            }
            catch (Exception)
            {

            }
            return response;
        }

        public dynamic CreateOrder(List<OrderInfo> orders)
        {
            var response = new POJO.Response.Response();

            string workOrderNo = DateTime.Now.ToString("yyyyMMddhhMMssff");
            List<base_work_order_head> heads = new List<base_work_order_head>();
            int index = 1;
            foreach (OrderInfo order in orders)
            {
                base_work_order_head head = new base_work_order_head();
                head.keys = Guid.NewGuid();
                head.lineCode = order.LineCode;
                // head.
                head.workOrderCode = workOrderNo;
                head.workPieceNo = workOrderNo.Substring(workOrderNo.Length - 9, 9) + "_" + index;
                head.projectNo = "ZC-X1547";

                head.pipePartsNo = workOrderNo + "_" + index;
                head.pipePartsCode = head.pipePartsNo.Substring(head.pipePartsNo.Length - 9, 9); //九位码
                head.paintCode = "GNB";
                head.startWorkDate = DateTime.Now;
                head.assemblageInfo = "A20-1";
                head.range = "2";
                head.diameter = order.Diameter;
                head.thickness = order.Thickness;
                head.level = "III";

                head.materielCode = Context.Queryable<base_material>().First(x => x.thickness == order.Thickness && x.diameter == order.Diameter && x.isDelete == 1).materialCode;
                head.cutLength = order.CutLength;
                head.flowOrientation1 = "L";
                head.flowOrientation2 = "D";
                head.attachment1 = "SQA7A130BF0500";
                head.instructions1 = "";
                head.bevels1 = "0";
                head.attachment2 = "SQA7A130BF0500";
                head.instructions2 = "";
                head.bevels2 = "0";
                head.turningAngle = "0";
                head.extend1 = "1";
                head.extend2 = "";
                head.extend3 = "";
                head.extend4 = "";
                head.attachment1PrintInfo = $"Q235-A III RF 16040 ({order.Diameter})";
                //head.attachment2PrintInfo = $"Q235-A III RF 16040 ({order.Diameter})";
                head.createBy = "Api";
                head.createTime = DateTime.Now;
                head.updateby = "Api";
                head.updateTime = DateTime.Now;
                head.planCode = Guid.NewGuid().ToString();
                heads.Add(head);
                index++;
            }
            Context.Insertable(heads).ExecuteCommand();
            return response;
        }

        /// <summary>
        /// 切断下料生成打标任务
        /// </summary>
        /// <param name="barCode">管段码</param>
        /// <param name="equipmentNo">设备PLC编号</param>
        /// <returns></returns>
        public dynamic LayingOff(string barCode, string equipmentNo)
        {
            var response = new POJO.Response.Response();
            if (string.IsNullOrEmpty(equipmentNo))
            {
                return response.ResponseError($"设备PLC编号为空!");
            }
            //增加产线,不然都是line1
            string lineCode = "line1";
            base_work_order_head order = Context.Queryable<base_work_order_head>().First(x=>x.workPieceNo == barCode);
            if (order != null)
            {
                lineCode = order.lineCode;
            }
            var equipment = Context.Queryable<base_work_station>().First(x => (x.workStationCode == equipmentNo || x.otherCode == equipmentNo) && x.lineCode.ToUpper()== lineCode.ToUpper());

            if (equipment == null)
            {
                return response.ResponseError($"工位编码未查询到设备,请配置!");
            }

            var workOrderDetailList = Context.Queryable<bus_workOrder_detail>()
                .Where(x => x.barCode == barCode && x.oprSequenceCode == EnumoprSequenceCode.组对).ToList();

            if (workOrderDetailList.Count == 0)
            {
                return response.ResponseError($"管段码【{barCode}】未查询到组对工序任务!");
            }

            //查询是否已经生成
            var imptaskList = Context.Queryable<base_imprint_task>().Where(x => x.barCode == barCode).ToList();

            if (imptaskList.Count == 0)
            {

                var code = DateTime.Now.ToString("yyyyMMddHHmmss");
                var i = 1;

                foreach (var item in workOrderDetailList)
                {
                    bus_workOrder_head ls = Context.Queryable<bus_workOrder_head>().Where(x => x.keys == item.headKeys).First();

                    var newcode = $"{code}-{i}";
                    var task = new base_imprint_task();
                    task.equipmentCode = equipment.workStationCode;
                    task.equipmentNo = equipmentNo;
                    task.taskCode = newcode;
                    task.content = item.extendComp1;
                    task.status = (int)EnumImprintTaskType.初始;
                    task.createTime = DateTime.Now;
                    task.updateTime = DateTime.Now;
                    task.barCode = barCode;
                    task.procedureID = item.id;
                    if (ls != null)
                    {
                        task.extend1 = ls.diameter;
                        task.extend2 = ls.thickness;
                    }
                    else
                    {
                        task.extend1 = "0";
                        task.extend2 = "0";
                    }

                    Context.Insertable(task).AddQueue();
                    i++;
                }
            }
            else
            {
                foreach (var item in imptaskList)
                {
                    if (string.IsNullOrEmpty(item.equipmentCode))
                    {
                        item.equipmentCode = equipment.workStationCode;
                        item.equipmentNo = equipmentNo;
                        Context.Updateable(item).AddQueue();
                    }
                }
            }

            var resultCount = Context.SaveQueues();
            return resultCount > 0 ? response.ResponseSuccess() : response.ResponseError();
        }

        /// <summary>
        /// 弯管机反馈完工
        /// </summary>
        /// <param name="batchCode">批次码</param>
        /// <returns></returns>
        public dynamic synBendLine(string batchCode)
        {
            var response = new POJO.Response.Response();
            return ExceptionsHelp.Instance.ExecuteT<dynamic>(() =>
            {
                if (string.IsNullOrEmpty(batchCode))
                {
                    return response.ResponseError($"批次码不能为空!");
                }

                var orderDetail = Context.Queryable<bus_workOrder_detail>().Where(x => x.id.ToString() == batchCode).First();

                if (orderDetail == null)
                {
                    return response.ResponseError($"批次码【{batchCode}】未查询到弯管工序信息!");
                }

                orderDetail.actualEndTime = DateTime.Now;
                orderDetail.updateTime = DateTime.Now;
                orderDetail.state = (int)EnumOrderBodyStatus.已完成;
                orderDetail.updateBy = sysUserApi?.Account;

                Context.Updateable(orderDetail).ExecuteCommand();

                //工序完工反馈
                CutWeldService cutWeldService = new CutWeldService();
                cutWeldService.SendIWPTechnologylineProcess(orderDetail.barCode, (int)EnumCutHeadState.弯管完成);

                return response;
            });
        }

        /// <summary>
        /// 工单取消,根据工件编码取消
        /// </summary>
        /// <param name="pipeParts"></param>
        /// <returns></returns>
        public dynamic PipePartsCamcel(List<pipePartsCancel> pipeParts)
        {
            var response = new POJO.Response.Response();
            if (pipeParts == null ||pipeParts.Count < 1)
            {
                return response.ResponseError($"请求数据为空");
            } 
            string errMsg = string.Empty;
            foreach (var item in pipeParts)
            {
                if (string.IsNullOrEmpty(item.workPieceNo))
                {
                    errMsg += "工件编码不能为空";
                }
                if (string.IsNullOrEmpty(item.cancelTime.ToString()))
                {
                    errMsg += "取消时间不能为空";
                }
                if (errMsg.Length > 0)
                {
                    return response.ResponseError($"{errMsg}");
                }
                var orderList = Context.Queryable<base_work_order_head>().Where(x => x.workPieceNo == item.workPieceNo && x.processStatus != "3").First();
                if (orderList == null)
                {
                    errMsg += $"工件编号{item.workPieceNo}不存在,或者已取消;";
                }

                //是否已经开始执行
                var busList = Context.Queryable<bus_workOrder_detail>().Where(x => x.barCode == item.workPieceNo && x.state != 0 && x.oprSequenceCode != "BentPipe").OrderBy(x => x.createBy, OrderByType.Desc).ToList();
                if (busList != null && busList.Count>0)
                {
                    //errMsg += $"工单{item.workOrderCode} 已经开始生产无法取消";
                    if (busList.Select(x=>x.oprSequenceCode).ToList().Contains("Cut"))
                    {
                        errMsg += $"工件编号{item.workPieceNo},已切割无法进行取消 ;";
                    }
                    else
                    {
                        if (busList.Select(x => x.oprSequenceCode).ToList().Contains("Nesting"))
                        {
                            errMsg += $"工件编号{item.workPieceNo},已套料无法进行取消 ;";
                        }
                    }
                } 
            }
            if (errMsg.Length > 0)
            {
                return response.ResponseError($"{errMsg}");
            }
            Context.Ado.BeginTran();
            //数据处理
            foreach (var item in pipeParts)
            {
                base_work_order_cancel cancelInfo = new base_work_order_cancel();
                cancelInfo.createBy = "Api";
                cancelInfo.createTime = DateTime.Now;
                cancelInfo.processStatus = "1";
                cancelInfo.processMsg = "处理成功";
                try
                {
                    base_work_order_head  workOrder = Context.Queryable<base_work_order_head>().Where(x => x.workPieceNo == item.workPieceNo).First();
                    Context.Deleteable<base_imprint_task>().Where(x => x.barCode == item.workPieceNo).ExecuteCommand();
                     
                    cancelInfo.workOrderCode = item.workPieceNo;

                    //删除明细表
                    Context.Deleteable<base_work_order_bends>().Where(x => x.headKeys == workOrder.keys).ExecuteCommand();
                    Context.Deleteable<base_work_order_mounting>().Where(x => x.headKeys == workOrder.keys).ExecuteCommand();
                    Context.Deleteable<base_work_order_flameCut_d>().Where(x => SqlFunc.Subqueryable<base_work_order_flameCut>().Where(s => s.Keys == x.headKeys  && s.headKeys == workOrder.keys).Any()).ExecuteCommand();
                    Context.Deleteable<base_work_order_flameCut>().Where(x => x.headKeys == workOrder.keys).ExecuteCommand();
                    // 取消工单表
                    Context.Deleteable<base_work_order_head>().Where(x => x.workPieceNo == item.workPieceNo && x.processStatus != "3")
                        .ExecuteCommand();
                    //取消工单任务表
                    Context.Deleteable<bus_workOrder_head>().Where(x => x.workPieceNo == item.workPieceNo)
                        .ExecuteCommand();
                    Context.Deleteable<bus_workOrder_detail>().Where(x => x.barCode == item.workPieceNo)
                        .ExecuteCommand();
                      
                }
                catch (Exception ex)
                {
                    Context.Ado.RollbackTran();
                    cancelInfo.processStatus = "2";
                    cancelInfo.processMsg = ex.Message;
                    Log4NetHelper.Instance.Error($"工单[{item.workPieceNo}]数据处理失败,错误信息:{ex.Message}");
                    return response.ResponseError($"数据处理失败");
                }
                Context.Insertable(cancelInfo).ExecuteCommand();
                Context.Ado.CommitTran();
            }

            return response;
        }

    }
}