UpstreamSendCalendar.cs 48.3 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
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.WebEntity;
using Hh.Mes.Service.Material;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
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 (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.cut_Type == null);
                }

            }



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

            Context.Ado.BeginTran();
            try
            {
                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 = Guid.NewGuid().ToString(); //DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //生成工艺路线和工单任务
                    // CreateProjectAndWorkOrder(order_head, work_order);
                    int inI = Context.Insertable(order_head).ExecuteCommand();

                    //弯管信息
                    List<base_work_order_bends> bends = work_order.bends;
                    if (bends != null)
                    {
                        foreach (var item in bends)
                        {
                            item.headKeys = keys;
                            item.createBy = createUser;
                            item.createTime = DateTime.Now;
                        }
                        Context.Insertable(bends).ExecuteCommand();
                    }


                    //切割数据
                    List<Work_Order_FlameCut> flameCuts = work_order.Cuts;
                    List<base_work_order_flameCut_d> flameCut_d = new List<base_work_order_flameCut_d>();

                    if (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.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);
                                }
                            }
                        }

                        //  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 (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();
                    }

                }
                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.bends.Count > 0)
            {
                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();
        }


        /// <summary>
        /// 获取字典的废料长度
        /// </summary>
        public decimal CutPlanLength
        {
            get
            {
                var CutPlan = GetDictionaryDictValue("CuttingWasteLength", "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}】信息,请核对!");
                }

                var pipeSN = measuring.taskCode;
                if (task.equipmentCode == ((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(equipment).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.createTime = DateTime.Now;
                    inventory.updateTime = DateTime.Now;

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

                Context.Ado.CommitTran();

                //3.测长完成后进行套料,小经线,中1线才自动套料
                if (equipment.lineCode.ToUpper() == EnumLine.小经线 || equipment.lineCode.ToUpper() == EnumLine.1线)
                {
                    var CutPlan = GetDictionaryDictValue("CuttingWasteLength", "CutConfig");
                    //可套料库存
                    var inventory = Context.Queryable<base_inventory>().Where(x =>
                                                    x.pipeLength > CutPlanLength
                                                    && x.useState == (int)InventoryUseState.未套料
                                                    && x.lineCode.ToUpper() == equipment.lineCode.ToUpper()
                                                    ).OrderBy(x => x.createTime).First();

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

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

                    var workOrderList = (List<bus_workOrder_detail>)cutList.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 += "取消时间不能为空";
                }
                var orderList = Context.Queryable<base_work_order_head>().First(x => x.workOrderCode == item.workOrderCode && x.processStatus != "3");
                if (orderList == null)
                {
                    errMsg += $"工单{item.workOrderCode}不存在,或者已取消";
                }

                //是否已经开始执行
                var busList = Context.Queryable<bus_workOrder_head>().Where(x => x.workOrderCode == item.workOrderCode && x.isDelete == 0).OrderBy(x => x.createBy, OrderByType.Desc).First(/*&& x.nowOprSequenceCode != "LoadMaterial" && x.isDelete == 0*/ );
                if (busList != null && busList.nextOprSequenceCode != "LoadMaterial")
                {
                    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
                {
                    // 取消工单表
                    Context.Updateable<base_work_order_head>().SetColumns(x => x.processStatus == ((int)EnumWorkOrderProessStatus.已取消).ToString())
                        .SetColumns(x => x.cancelTime == item.cancelTime)
                        .SetColumns(x => x.updateby == "Api")
                        .SetColumns(x => x.updateTime == DateTime.Now)
                        .Where(x => x.workOrderCode == item.workOrderCode && x.processStatus != "3")
                        .ExecuteCommand();
                    //取消工单任务表
                    Context.Updateable<bus_workOrder_head>().SetColumns(x => x.isDelete == 1)
                        .SetColumns(x => x.updateBy == "Api")
                        .SetColumns(x => x.updateTime == DateTime.Now)
                        .Where(x => x.workOrderCode == item.workOrderCode && x.isDelete == 0)
                        .ExecuteCommand();
                    //取消原有订单表
                    //Context.Updateable<base_productionOrder_EP3D>().SetColumns(x => x.state == 30)
                    //    //.SetColumns(x => x.updateBy == "Api")
                    //    .SetColumns(x => x.updateTime == DateTime.Now)
                    //    .Where(x => x.workOrderCode == item.workOrderCode &&  x.state ==0)
                    //    .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($"未查询到套料任务!");
            }

            //2.将余料数据存入库存表
            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.good.ToString();
            inventory.pipeLength = 0;
            inventory.useState = 0;
            inventory.qty = 1;
            inventory.createTime = DateTime.Now;

            Context.Insertable(inventory).ExecuteCommand();


            return response;
        }
    }
}