MaterialDistributeLoadDataService.cs 53.7 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
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.ViewModel;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hh.Mes.POJO.Response;

namespace Hh.Mes.Service.Distribution
{
    /// <summary>
    /// 装料数据
    /// </summary>
    public class MaterialDistributeLoadDataService : RepositorySqlSugar<bus_material_distribute_load_head>
    {
        #region 
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response Load(PageReq pageReq, bus_material_distribute_load_head model)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc" : $"{pageReq.field} {pageReq.order} ";
                string sqlWhere = SqlWhere(model);
                var stringBuilder = new StringBuilder();
                //页码,页数
                //Exel ture 不分页
                if (!model.Exel && pageReq != null)
                {
                    stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                    stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
                }

                stringBuilder.AppendLine($@" select  * 
                                         from bus_material_distribute_load_head  with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

                //Exel ture 不分页
                if (!model.Exel)
                {
                    stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                    stringBuilder.Append($" select rowTotal= count(*) from bus_material_distribute_load_head    with(nolock) where {sqlWhere}");
                }
                var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                                                        new SugarParameter("@productCode",model.productCode),
                                                        new SugarParameter("@status", model.status)});
                result.Result = ds.Tables[0];
                result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
                return result;
            });
        }

        public string SqlWhere(bus_material_distribute_load_head model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.productCode)) stringBuilder.Append(" and  t1.productCode like @productCode ");
            if (model.status != null) stringBuilder.Append(" and  t1.status = @status ");

            return stringBuilder.ToString();
        }

        /// <summary>
        /// 新增
        /// </summary>
        public dynamic Ins(bus_material_distribute_load_head model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region 校验数据
                if (string.IsNullOrWhiteSpace(model.endPosition))
                {
                    if (SystemVariable.noneGoodsLocationCodes.Item2.Count == 0)
                    {
                        return response.ResponseError($"组队上料点是空,暂无可上料料点,请确认PLC料点信号是否正常!");
                    }
                    var resultLocation = GetLoadMaterialLocation(model.productCode, model.containerCode, model.startPosition);
                    model.endPosition = resultLocation.Result[0].locationCode;
                }


                var container = base.Context.Queryable<base_container>().First(x => x.containerCode == model.containerCode);
                if (container == null) return response.ResponseError($"料框条码(容器编码)【{model.containerCode}】不存在【容器管理】基础数据中!");

                var zhuangLiao = (int)EnumLocationZoneCode.装料点;
                var shangLiao = (int)EnumLocationZoneCode.上料点;
                var locationList = base.Context.Queryable<base_location>()
                                               .Where(x => x.locationCode == model.startPosition || x.locationCode == model.endPosition)
                                               .ToList();
                var startLocation = locationList.FirstOrDefault(t => t.zoneCode == zhuangLiao && t.locationCode == model.startPosition);
                if (startLocation == null)
                {
                    return response.ResponseError($"【库位管理】中【人工装料区】不存在库位【{model.startPosition}】!");
                }
                if (string.IsNullOrEmpty(startLocation.containerCode))
                {
                    return response.ResponseError($"【库位管理】中库位【{startLocation.locationCode}】不存在容器【{startLocation.containerCode}】不能装料!");
                }
                if (startLocation.locationType != container.containerType)
                {
                    return response.ResponseError($"库位【{startLocation.locationCode}】的类型是【{startLocation.locationType}】,托盘【{container.containerCode}】的类型是【{container.containerType}】,不能装料!");
                }
                if (startLocation.locationStatus == (int)EnumLocationStatus.锁定)
                {
                    return response.ResponseError($"【库位管理】中库位【{startLocation.locationCode}】有任务锁定,不能装料!");
                }
                var endLocation = locationList.FirstOrDefault(t => t.zoneCode == shangLiao && t.locationCode == model.endPosition);
                if (endLocation == null)
                {
                    return response.ResponseError($"【库位管理】中【组队上料区】不存在库位【{model.endPosition}】!");
                }
                if (!string.IsNullOrEmpty(endLocation.containerCode))
                {
                    return response.ResponseError($"【库位管理】中库位【{endLocation.locationCode}】存在容器【{endLocation.containerCode}】不能装料!");
                }
                if (endLocation.locationType != container.containerType)
                {
                    return response.ResponseError($"库位【{endLocation.locationCode}】的类型是【{endLocation.locationType}】,托盘【{container.containerCode}】的类型是【{container.containerType}】,不能上料!");
                }
                if (endLocation.locationStatus == (int)EnumLocationStatus.锁定)
                {
                    return response.ResponseError($"【库位管理】中库位【{endLocation.locationCode}】有任务锁定,不能装料!");
                }

                //检查同一组装料区域的配送,是否都是往同一个组队上料区域,(例如装料点A1去了组队1的区域1,装料点B1只能去组队1的区域1,否则机器人无法抓料)
                var otherDistributeHead = base.Context.Queryable<bus_material_distribute_load_head>()
                                                      .First(x => x.startStationCode == startLocation.stationCode && x.startArea == startLocation.fitupArea && x.status < (int)EnumLoadData.配送完成);
                if (otherDistributeHead != null)
                {
                    if (otherDistributeHead.productCode != model.productCode)
                    {
                        return response.ResponseError($"本组装料中已经有一个框料装的产品【{otherDistributeHead.productCode}】,本料框也只能装相同产品的物料!");
                    }
                    if (otherDistributeHead.loadQty != model.loadQty)
                    {
                        return response.ResponseError($"本组装料中已经有一个框料装了【{otherDistributeHead.loadQty}】套产品的物料,本料框也只能装相同套数!");
                    }
                    if (otherDistributeHead.endStationCode != endLocation.stationCode || otherDistributeHead.endArea != endLocation.fitupArea)
                    {
                        return response.ResponseError($"本组装料中已经有一个框料去工位【{otherDistributeHead.endStationCode}】上料区域【{otherDistributeHead.endArea}】,本料框也只能去相同工位和上料区域,请重新设置!");
                    }
                }

                #endregion

                #region 生成实体

                //生成【装料配送头】实体
                model.keys = Guid.NewGuid();
                model.containerType = container.containerType;
                model.startStationCode = startLocation.stationCode;
                model.startArea = startLocation.fitupArea;
                model.endStationCode = endLocation.stationCode;
                model.endArea = endLocation.fitupArea;
                model.status = (int)EnumLoadData.已装料;
                model.createBy = base.sysWebUser.Account;
                model.createTime = DateTime.Now;

                //生成【配送任务】明细实体
                var distributeDetail = new List<bus_material_distribute_load_detail>();
                for (int i = 0; i < model.table.Count; i++)
                {
                    if (model.table[i].sequence > 0 && model.table[i].row >= 0 && model.table[i].line >= 0 && model.table[i].layer >= 0)
                    {
                        distributeDetail.Add(new bus_material_distribute_load_detail()
                        {
                            headKeys = model.keys,
                            bodyKeys = Guid.NewGuid(),

                            loadDataBodyKeys = model.table[i].bodyKeys,
                            sequence = model.table[i].sequence.Value,

                            row = model.table[i].row.Value,
                            line = model.table[i].line.Value,
                            qty = model.table[i].qty.Value,
                            layer = model.table[i].layer.Value,

                            createBy = sysWebUser.Account,
                            createTime = DateTime.Now
                        });
                    }
                }
                if (distributeDetail.Count == 0)
                {
                    response.ResponseError("没有装料明细,无法保存!");
                }


                //生成【AGV任务】实体
                var busAgvTask = new bus_agv_task()
                {
                    keys = Guid.NewGuid(),
                    taskCode = Guid.NewGuid().ToString(),
                    agvCode = "",
                    agvTaskType = (int)EnumAgvTaskType.上料配送,

                    materialFrameCode = model.containerCode,
                    materialDistributeLoadCode = model.keys.ToString(),
                    workOrderCode = "",
                    productHeaderCode = model.productCode,

                    startPosition = model.startPosition,
                    endPosition = model.endPosition,
                    state = (int)EnumAGVState.任务创建,
                    createTime = DateTime.Now,
                    createBy = sysWebUser.Account,
                };
                //修改【库位】实体
                startLocation.locationStatus = (int)EnumLocationStatus.锁定;
                endLocation.locationStatus = (int)EnumLocationStatus.锁定;

                #endregion

                #region 执行数据库操作
                //添加实体到执行队列
                base.Context.Insertable(model).AddQueue();
                base.Context.Insertable(distributeDetail).AddQueue();
                base.Context.Insertable(busAgvTask).AddQueue();
                base.Context.Updateable(startLocation).UpdateColumns(t => t.locationStatus).AddQueue();
                base.Context.Updateable(endLocation).UpdateColumns(t => t.locationStatus).AddQueue();
                //保存数据
                var result = base.Context.SaveQueues() > 0;
                if (!result)
                {
                    response.ResponseError("更新数据库失败!");
                }
                return response;
                #endregion
            });
        }


        /// <summary>
        /// 更新
        /// </summary>
        public dynamic Upd(bus_material_distribute_load_head model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region before

                //if (string.IsNullOrEmpty(model.endPosition))
                //    return response.ResponseError($"组队上料点是空,请输入!");

                //var container = base.Context.Queryable<base_container>().First(x => x.containerCode == model.containerCode);
                //if (container == null) return response.ResponseError($"料框条码(容器编码)【{model.containerCode}】不存在【容器管理】基础数据中!");
                if (model.table.Count == 0)
                {
                    response.ResponseError("没有装料明细,无法保存!");
                }

                var yizhuangliao = (int)EnumLoadData.使用中;
                var distributeHead = base.Context.Queryable<bus_material_distribute_load_head>().First(x => x.id == model.id);
                if (distributeHead.status < yizhuangliao) return response.ResponseError("装料数据状态是小于【使用中】才能编辑!");

                //model.containerType = container.containerType;
                model.updateBy = base.sysWebUser.Account;
                model.updateTime = DateTime.Now;

                #endregion

                #region detail
                for (int i = 0; i < model.table.Count; i++)
                {
                    if (model.table[i].sequence > 0 && model.table[i].row >= 0 && model.table[i].line >= 0 && model.table[i].layer >= 0)
                    {
                        var key = model.table[i].bodyKeys;
                        var detail = new bus_material_distribute_load_detail()
                        {
                            row = model.table[i].row.Value,
                            line = model.table[i].line.Value,
                            qty = model.table[i].qty.Value,
                            layer = model.table[i].layer.Value,

                            updateBy = sysWebUser.Account,
                            updateTime = DateTime.Now
                        };
                        base.Context.Updateable(detail).Where(x => x.bodyKeys == key).UpdateColumns(x => new
                        {
                            x.row,
                            x.line,
                            x.qty,
                            x.layer,
                            x.updateBy,
                            x.updateTime
                        }).AddQueue();
                    }
                }

                #endregion

                #region head
                base.Context.Updateable(model).UpdateColumns(x => new
                {
                    //x.containerCode,
                    //x.productCode,
                    x.loadQty,
                    //x.startPosition,
                    //x.endPosition,
                    //x.containerType,

                    x.updateBy,
                    x.updateTime
                }).Where(x => x.id == model.id).AddQueue();
                #endregion

                var result = base.Context.SaveQueues() > 0;
                if (!result) response.ResponseError("更新数据库失败!");
                return response;
            });

        }

        /// <summary>
        /// 删除
        /// </summary>
        public dynamic DelByIds(Guid[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                Context.Deleteable<bus_material_distribute_load_head>().In(x => x.keys, ids).AddQueue();
                foreach (var id in ids)
                {
                    Context.Deleteable<bus_material_distribute_load_detail>().Where(it => it.headKeys == id).AddQueue();
                }
                var result = Context.SaveQueues();
                if (result < 0) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <returns></returns>
        public Task<dynamic> Export(bus_material_distribute_load_head entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var dataTable = Load(null, entity);
                if (dataTable.Count == 0)
                {
                    result.Result = null;
                    result.Message = "没有查询到数据!";
                    result.Code = -1;
                    return result;
                }
                var guids = new List<Guid>();
                foreach (var item in dataTable.Result)
                {
                    guids.Add((Guid)item.keys);
                }
                var data = LoadDesc(null, new bus_material_distribute_load_detail { headKeyList = guids });
                result.Result = new
                {
                    head = dataTable.Result,
                    body = data.Result
                };
                return result;
            });
        }

        /// <summary>
        /// 产品代码查询装料模板数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Response GetLoadDataTemplateByProductCode(bus_material_distribute_load_head entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                //新增第一个无法清空数据,只能默认发送一次数据请求
                if (entity.productCode == "-1") return response.ResponseError("先扫人工装料点、料框条码(容器编码、在选产品编码!");

                //通过容器编码(料框编码)和产品编码过滤 装料数据模板类型【A、或者B】
                var container = base.Context.Queryable<base_container>().First(x => x.containerCode == entity.containerCode);
                if (container == null) return response.ResponseError($"料框条码(容器编码)【{entity.containerCode}】不存在【容器管理】基础数据中!");

                var heardTemplate = base.Context.Queryable<bus_material_distribute_load_template_head>().First(x => x.productCode == entity.productCode);
                if (heardTemplate == null) return response.ResponseError($"产品【{entity.productCode}】没有配置装料模板头表数据!");

                dynamic data = null;
                if (entity.flag != "edit")
                {
                    data = base.Context.Queryable<bus_material_distribute_load_template_detail>().Where(x => x.headKeys == heardTemplate.keys && x.containerType == container.containerType).ToList();
                    if (data.Count == 0) return response.ResponseError($"产品【{entity.productCode}】没有配置装料模板明细数据!");
                    response.Count = data.Count;
                }
                else
                {
                    var sql = $@" select t1.*, t2.materialCode,t2.containerType 
                                  from bus_material_distribute_load_detail t1
                                  left join  bus_material_distribute_load_template_detail t2 on t1.loadDataBodyKeys = t2.bodyKeys
                                  where t1.headKeys='{entity.keys}' ";
                    data = base.Context.Ado.GetDataTable(sql);
                    if (data.Rows.Count == 0) return response.ResponseError($"产品{entity.productCode}没有配置装料模板明细数据!");
                    response.Count = data.Rows.Count;
                }
                response.Result = data;
                return response;
            });
        }

        /// <summary>
        /// 获取PLC无货的组队上料点
        /// </summary>
        /// <param name="productCode">产品编码</param>
        /// <param name="containerCode">托盘编码</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Response GetLoadMaterialLocation(string productCode, string containerCode, string startPosition = "")
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();

                if (SystemVariable.noneGoodsLocationCodes.Item1.AddSeconds(30) < DateTime.Now)
                    return response.ResponseError($"ECS已经超过30秒没向中控接口【distribution/MaterialDistributeLoadData/SetLoadMaterialLocation】发送可去的料点信息,请先检查ECS!");
                var locationCodes = SystemVariable.noneGoodsLocationCodes.Item2;

                //通过容器编码(料框编码)和产品编码过滤 装料数据模板类型【A、或者B】
                var container = base.Context.Queryable<base_container>().First(x => x.containerCode == containerCode);
                if (container == null) return response.ResponseError($"料框条码(容器编码)【{containerCode}】不存在【容器管理】基础数据中,请配置!");

                //查询产品的工艺路线
                var processRouteHead = base.Context.Queryable<base_process_route_head>().First(x => x.productHeaderCode == productCode);
                if (processRouteHead == null) return response.ResponseError($"产品编码【{productCode}】不存在【工艺路线头表】基础数据中,请配置!");

                //查询产品的工艺路线明细(暂时简单认为第一道工艺路线就是组队,后续要加上工序类型)
                var ProcessRouteDetail = base.Context.Queryable<base_process_route_detail>().First(x => x.headkeys == processRouteHead.keys && x.oprSequence == 1);
                if (ProcessRouteDetail == null) return response.ResponseError($"产品编码【{productCode}】不存在工序顺序为1的【工艺路线明细表】基础数据中,请配置!");

                //查询产品的工序工位,获取产品组队能去的所有工位
                var ProcessRouteStationList = base.Context.Queryable<base_process_route_station>().Where(x => x.bodyKeys == ProcessRouteDetail.bodyKeys).ToList();
                if (ProcessRouteStationList == null) return response.ResponseError($"产品编码【{productCode}】的工序【{ProcessRouteDetail.oprSequenceName}】不存在【工序工位表】基础数据中,请配置!");
                //产品组队能去的所有工位
                var workStationCodeList = ProcessRouteStationList.Select(x => x.workStationCode).ToList();

                var fitup = (int)EnumLocationZoneCode.上料点;
                //能去的料点的条件:1.料点类型和料框类型一致、2.产品能去的组队工位、3.料点无料框、4.ECS确认无货
                var locationList = base.Context.Queryable<base_location>()
                                               .Where(x => x.locationType == container.containerType && x.zoneCode == fitup && string.IsNullOrEmpty(x.containerCode)).ToList();
                locationList = locationList.Where(x => workStationCodeList.Contains(x.stationCode) && locationCodes.Contains(x.locationCode)).ToList();
                if (startPosition != "")
                {
                    var location = base.Context.Queryable<base_location>()
                                                      .First(u => u.locationCode == startPosition);
                    var otherDistributeHead = base.Context.Queryable<bus_material_distribute_load_head>()
                                                      .Where(x => x.startStationCode == location.stationCode && x.startArea == location.fitupArea.ToString() && x.status < (int)EnumLoadData.配送完成).ToList();
                    if (otherDistributeHead.Count() == 1)
                    {
                        var shangLiao = (int)EnumLocationZoneCode.上料点;
                        locationList = base.Context.Queryable<base_location>()
                                                      .Where(u => u.zoneCode == shangLiao && u.fitupArea.ToString() == otherDistributeHead[0].endArea && u.stationCode == otherDistributeHead[0].endStationCode && u.locationCode != otherDistributeHead[0].endPosition).ToList();
                    }
                }
                if (locationList.Count == 0) return response.ResponseError("根据产品编码、产品编码查询无组队上料点数据!");
                response.Result = locationList;
                return response;
            });
        }

        /// <summary>
        /// 强制完成装料数据
        /// </summary>
        public Response HandlerMaterialDistributeLoadEnd(Guid keys)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region before
                var material_Distribute_Load_Head = Context.Queryable<bus_material_distribute_load_head>().First(x => x.keys == keys);
                if (material_Distribute_Load_Head == null) return response.ResponseError("找不到对应的装料数据任务信息");
                if (material_Distribute_Load_Head.status == (int)EnumLoadData.完成) return response.ResponseError("装料任务已经完成,不能重复操作");


                #endregion

                #region save
                var kongXian = (int)EnumLocationStatus.空闲;
                var end = (int)EnumLoadData.完成;
                //更新配送任务状态
                Context.Updateable<bus_material_distribute_load_head>()
                       .SetColumns(x => x.status == end)
                       .Where(x => x.keys == keys)
                       .AddQueue();

                var firstLocation = Context.Queryable<base_location>().First(x => x.locationCode == material_Distribute_Load_Head.endPosition);
                var lastLocation = Context.Queryable<base_location>().First(x => x.stationCode == firstLocation.stationCode && x.fitupArea == firstLocation.fitupArea && x.locationType != firstLocation.locationType);
                if (lastLocation != null)
                {
                    var lastMaterialDistributeLoad = Context.Queryable<bus_material_distribute_load_head>().First(x => x.endPosition == lastLocation.locationCode && x.productCode == material_Distribute_Load_Head.productCode && x.status < (int)EnumLoadData.完成);
                    if (lastMaterialDistributeLoad != null)
                    {
                        Context.Updateable<bus_material_distribute_load_head>()
                       .SetColumns(x => x.status == end)
                       .Where(x => x.keys == lastMaterialDistributeLoad.keys)
                       .AddQueue();
                    }
                    var lastagvTask = Context.Queryable<bus_agv_task>().First(x => x.materialDistributeLoadCode == lastMaterialDistributeLoad.keys.ToString());
                    if (lastagvTask != null && lastagvTask.state != (int)EnumAGVState.任务完成)
                    {

                        lastagvTask.state = (int)EnumAGVState.任务完成;
                        Context.Updateable(lastagvTask).UpdateColumns(x => new { x.state }).AddQueue();
                        Context.Updateable<base_location>()
                           .SetColumns(x => x.containerCode == "")
                           .SetColumns(x => x.locationStatus == kongXian)
                           .Where(x => x.locationCode == lastagvTask.startPosition)
                           .AddQueue();
                        Context.Updateable<base_location>()
                               .SetColumns(x => x.containerCode == lastagvTask.materialFrameCode)
                               .SetColumns(x => x.locationStatus == kongXian)
                               .Where(x => x.locationCode == lastagvTask.endPosition)
                               .AddQueue();
                    }
                }
                //设置任务状态为完成
                var agvTask = Context.Queryable<bus_agv_task>().First(x => x.materialDistributeLoadCode == keys.ToString());
                if (agvTask != null && agvTask.state != (int)EnumAGVState.任务完成)
                {
                    agvTask.state = (int)EnumAGVState.任务完成;
                    Context.Updateable(agvTask).UpdateColumns(x => new { x.state }).AddQueue();
                    Context.Updateable<base_location>()
                          .SetColumns(x => x.containerCode == "")
                          .SetColumns(x => x.locationStatus == kongXian)
                          .Where(x => x.locationCode == agvTask.startPosition)
                          .AddQueue();
                    Context.Updateable<base_location>()
                           .SetColumns(x => x.containerCode == agvTask.materialFrameCode)
                           .SetColumns(x => x.locationStatus == kongXian)
                           .Where(x => x.locationCode == agvTask.endPosition)
                           .AddQueue();
                }



                if (ExecuteQueues(base.Context) > 0)
                {
                    #region 通知agv结束任务
                    // 
                    #endregion
                }
                else
                {
                    response.Message = "结束装料任务,更新数据库失败!";
                }
                #endregion

                return response;
            });
        }

        #endregion

        #region 明细

        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadDesc(PageReq pageReq, bus_material_distribute_load_detail model)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var sql = $@" select t1.*, t2.materialCode,t2.containerType 
                              from bus_material_distribute_load_detail t1
                              left join  bus_material_distribute_load_template_detail t2 on t1.loadDataBodyKeys = t2.bodyKeys
                              where t1.headKeys='{model.headKeys}'";
                var data = base.Context.Ado.GetDataTable(sql);

                var result = new Response
                {
                    Code = 200,
                    Result = data,
                    Count = data.Rows.Count
                };
                return result;
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        public dynamic InsDesc(bus_material_distribute_load_detail model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.createBy = base.sysWebUser.Account;
                model.createTime = DateTime.Now;
                response.Status = Context.Insertable(model).ExecuteCommand() > 0;
                if (!response.Status)
                {
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        public dynamic UpdDesc(bus_material_distribute_load_detail model)
        {

            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                Context.Updateable(model).IgnoreColumns(x => new { x.createTime, x.createBy }).AddQueue();
                var result = Context.SaveQueues();
                if (result <= 0) return response.ResponseError();
                return response;

            });

        }



        /// <summary>
        /// 删除
        /// </summary>
        public dynamic DelByIdsDesc(int[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                response.Status = Context.Deleteable<bus_material_distribute_load_detail>().In(ids).ExecuteCommand() > 0;
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }
        #endregion

        #region 料点相关

        #region 全局静态变量相关

        private static readonly object lockObj = new object();

        /// <summary>
        /// 初始化叫料点状态全局静态变量
        /// </summary>
        /// <param name="isIni">是否初始化</param>
        public void IniLocationVm(bool isIni = false)
        {
           ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
           {
               //这里必须加锁,不然并发后,库位信息就会重叠
               lock (lockObj)
               {
                   #region ini

                   ////是否已经初始化
                   //if (SystemVariable.locationList.Count > 0 && !isIni)
                   //    return;

                   ////装料数据
                   List<bus_material_distribute_load> materialDistributeList = null;

                   //叫料点位
                   var locationList = base.Context.Queryable<base_location>().ToList();

                   //删除料点表没有的料点
                   for (var i = SystemVariable.locationList.Count - 1; i >= 0; i--)
                   {
                       if (!locationList.Exists(t => t.locationCode == SystemVariable.locationList[i].locationCode))
                       {
                           SystemVariable.locationList.RemoveAt(i);
                       }
                   }
                   //找出静态变量中没有的料点信息
                   var tempList = locationList.Where(t => !SystemVariable.locationList.Exists(x => x.locationCode == t.locationCode)).ToList();
                   if (tempList.Count > 0)
                   {
                       materialDistributeList = base.Context.Queryable<bus_material_distribute_load>().Where(x => x.status < (int)EnumLoadData.配送完成).ToList();
                   }
                   //增加静态缓存中没有的料点
                   foreach (var locationItem in tempList)
                   {
                       locationItem.askingStatus = (int)EnumLocationAskingStatus.未叫料;
                       //判断是否有装料数据
                       if (materialDistributeList.Exists(x => x.endPosition == locationItem.locationCode))
                       {
                           locationItem.askingStatus = (int)EnumLocationAskingStatus.已装料;
                       }
                       SystemVariable.locationList.Add(locationItem);
                   }

                   ////装料数据
                   //var materialDistributeList = base.Context.Queryable<bus_material_distribute_load>().Where(x => x.status < (int)EnumLoadData.配送到达).ToList();

                   ////全局变量赋值
                   //foreach (var item in locationList)
                   //{
                   //item.locationStatus = (int)EnumLocationAskingStatus.未叫料;
                   ////判断是否有装料数据
                   //if (materialDistributeList.Exists(x => x.endPosition == item.locationCode))
                   //{
                   //    item.locationStatus = (int)EnumLocationAskingStatus.已装料;
                   //}

                   //Tuple<string, base_location> locationTuple = new Tuple<string, base_location>(item.locationCode, item);
                   //SystemVariable.locationDict.Add(locationTuple);
                   //}

                   #endregion
               }
           });
        }

        /// <summary>
        /// 更新叫料点状态全局静态变量
        /// </summary>
        /// <param name="locationCode">料点编码</param>
        /// <param name="locationStatus">叫料状态</param>
        public void UpLocationVm(string locationCode, EnumLocationAskingStatus locationStatus)
        {
            ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
            {
                #region update

                if (string.IsNullOrEmpty(locationCode))
                    return;

                var locationItem = SystemVariable.locationList.Where(x => x.locationCode == locationCode).FirstOrDefault();
                //找到对应料点 更新状态与时间
                if (locationItem != null)                
                {
                    locationItem.askingStatus = (int)locationStatus;
                    locationItem.updateTime = DateTime.Now;
                }

                #endregion
            });
        }


        #endregion

        /// <summary>
        /// 上料装料区域查询
        /// </summary>
        /// <param name="groupType">分组类型</param>
        /// <returns></returns>
        public Response GteChargeAreaData(string groupType)
        {
            var response = new Response();
            //初始化字典
            IniLocationVm();

            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region select

                //上料装料区域
                var dictData = base.Context.Queryable<sys_dict_data>().Where(x => x.dictType == groupType).ToList();

                var loadingAreaTypeList = dictData.Select(x => new LoadingAreaTypeVm
                {
                    key = x.dictValue,
                    value = x.dictLabel
                }).ToList();

                if (loadingAreaTypeList.Count == 0) return response.ResponseError("无装料区域数据!");
                response.Result = loadingAreaTypeList;
                return response;

                #endregion
            });
        }

        /// <summary>
        /// 叫料点查询(叫料页面)
        /// </summary>
        /// <param name="loadingAreaType">上料点区域类型</param>
        /// <returns></returns>
        public Response GteLoadingData(string feedGroupCode)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region select
                //叫料点位
                var locationList = SystemVariable.locationList.Where(x => x.feedGroupCode == feedGroupCode && x.zoneCode == (int)EnumLocationZoneCode.上料点).ToList();
                if (locationList.Count == 0)    return response.ResponseError("无叫料点数据!");

                response.Result = locationList;
                return response;

                #endregion
            });
        }

        /// <summary>
        /// 叫料操作
        /// </summary>
        /// <param name="locationCode">料点编码</param>
        /// <param name="iScheck">是否验证时间(1分钟)</param>
        /// <returns></returns>
        public Response LoadingAsking(string locationCode, bool iScheck)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region 叫料点数据
                var locationModel = SystemVariable.locationList.Where(x => x.locationCode == locationCode).First();
                if (locationModel == null) return response.ResponseError("未查询到料点信息!");

                if (locationModel.updateTime.AddSeconds(60) < DateTime.Now && iScheck)
                    return response.ResponseError("1分钟之前已经叫料过了,是否确认用完?");
                
                if (locationModel.isWorkClothes == (int)EnumtIsWorkClothes. && string.IsNullOrEmpty(locationModel.containerCode))
                    return response.ResponseError("工装叫料必须要有料框,请检查!");
                
                #endregion

                #region 如果存在【使用中】的装料配送,就把状态改为【使用完】
                //找出所有小于等于【未使用】的配送,等于【使用中】的配送修改为【使用完】,小于【使用中】的配送在下面用于是否还要叫料的判断
                var distributeLoadHeadList = base.Context.Queryable<bus_material_distribute_load>()
                                                         .Where(t => t.endPosition == locationCode && t.status <= (int)EnumLoadData.使用中).ToList();

                if (distributeLoadHeadList.Any(t => t.status == (int)EnumLoadData.使用中))
                {
                    var distributeLoadTemp = distributeLoadHeadList.Where(t => t.status == (int)EnumLoadData.使用中).ToList();
                    foreach (var item in distributeLoadTemp)
                    {
                        item.status = (int)EnumLoadData.完成;
                    }
                    base.Context.Updateable(distributeLoadHeadList).AddQueue();
                }
                #endregion

                #region 如果有料框 并且不是工装,就生成回收料框的AGV任务
                if (!string.IsNullOrEmpty(locationModel.containerCode) && locationModel.isWorkClothes == (int)EnumtIsWorkClothes.)
                {
                    //料点还有未使用的配送
                    if (distributeLoadHeadList.Any(t => t.status < (int)EnumLoadData.使用中))
                        return response.ResponseError("料点还有未使用的配送,是否确认用完?");
                    

                    //是否存在agv回收料框任务,如果有就不再生成回收空料框任务
                    var agvTaskExist = base.Context.Queryable<bus_agv_task>()
                                                   .Where(t => t.startPosition == locationCode && t.state < (int)EnumAGVState.任务完成 && t.agvTaskType == (int)EnumAgvTaskType.料框回收)
                                                   .Any();

                    //有就生成agv回收料框任务
                    if (!agvTaskExist)
                    {

                        //找到当前上料点对应的多个装料点
                        var endLocation = base.Context.Queryable<base_location_rel>()
                                                      .Where(t => t.endPositionCode == locationCode).ToList()
                                                      .Select(x => x.startPositionCode).ToList();

                        //从多个装料点中选择一个能去的料点
                        var manualLoadLocation = base.Context.Queryable<base_location>()
                                                             .Where(t => t.locationType == locationModel.locationType &&
                                                                         t.zoneCode == (int)EnumLocationZoneCode.装料点 &&
                                                                         t.locationStatus == (int)EnumLocationStatus.空闲 &&
                                                                         string.IsNullOrEmpty(t.containerCode) &&
                                                                         endLocation.Contains(t.locationCode))
                                                             .First();

                        if (manualLoadLocation == null)
                            return response.ResponseError("找不到空闲、无货的【人工装料点】!");


                        //agv任务新增
                        bus_agv_task agvTask = new bus_agv_task();

                        agvTask.keys = Guid.NewGuid();
                        agvTask.taskCode = Guid.NewGuid().ToString();
                        agvTask.agvCode = "";
                        agvTask.agvTaskType = (int)EnumAgvTaskType.料框回收;
                        agvTask.materialFrameCode = locationModel.containerCode;
                        //任务起点编号
                        agvTask.startPosition = locationCode;
                        // 任务终点编号
                        agvTask.endPosition = manualLoadLocation.locationCode;
                        agvTask.state = (int)EnumAGVState.任务创建;
                        agvTask.workOrderCode = "";
                        agvTask.productHeaderCode = "";
                        agvTask.createTime = DateTime.Now;
                        agvTask.createBy = base.sysWebUser.Account;

                        //新增agv回收料框任务
                        base.Context.Insertable(agvTask).AddQueue();

                        //更新上料点的状态为锁定
                        locationModel.locationStatus = (int)EnumLocationStatus.锁定;
                        base.Context.Updateable(locationModel).UpdateColumns(t => t.locationStatus).AddQueue();

                        //更新装料点的状态为锁定
                        manualLoadLocation.locationStatus = (int)EnumLocationStatus.锁定;
                        base.Context.Updateable(manualLoadLocation).UpdateColumns(t => t.locationStatus).AddQueue();
                    }
                }
                #endregion

                #region 执行数据库操作
                base.Context.SaveQueues();
                #endregion

                UpLocationVm(locationCode, EnumLocationAskingStatus.已叫料);
                return response;
            });
        }

        /// <summary>
        /// 取消叫料
        /// </summary>
        /// <returns></returns>
        public Response EscLoadingAsking(string locationCode)
        {
            var response = new Response();

            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                // 叫料点数据
                var locationModel = SystemVariable.locationList.Where(x => x.locationCode == locationCode).FirstOrDefault();
                if (locationModel == null)      return response.ResponseError("未查询到料点信息!");
                if (locationModel.askingStatus >= (int)EnumLocationAskingStatus.已装料)      return response.ResponseError("已装料不能取消!");

                UpLocationVm(locationCode, EnumLocationAskingStatus.未叫料);
                return response;
            });
        }

        /// <summary>
        /// 叫料点查询(装料页面)
        /// </summary>
        /// <param name="loadingAreaType">区域类型</param>
        /// <returns></returns>
        public Response GetChargeData(string loadGroupCode)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region get

                //上料点
                var locationList = SystemVariable.locationList.Where(x => x.loadGroupCode == loadGroupCode && x.zoneCode == (int)EnumLocationZoneCode.上料点).ToList();
                if (locationList.Count == 0)    return response.ResponseError("无叫料点数据!");

                response.Result = locationList;
                return response;

                #endregion
            });
        }

        /// <summary>
        /// 叫料点对应装料点查询
        /// </summary>
        /// <param name="locationCode">料点编码</param>
        /// <returns></returns>
        public Response GetLocationRelData(string locationCode)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region get

                if (string.IsNullOrEmpty(locationCode))
                    return response;

                //查询有料框的装料点
                var locationList = base.Context.Queryable<base_location_rel, base_location>((x, y) =>
                                                       new JoinQueryInfos(JoinType.Right, x.startPositionCode == y.locationCode))
                                                .Where((x, y) => x.endPositionCode == locationCode && !string.IsNullOrEmpty(y.containerCode))
                                                .Select((x, y) => new LoadingAreaTypeVm
                                                {
                                                    value = y.locationCode,
                                                    key = y.locationName
                                                }).ToList();

                if (locationList.Count == 0) return response.ResponseError("无装料点数据或装料点无料框!");

                response.Result = locationList;
                return response;

                #endregion
            });
        }

        /// <summary>
        /// 装料操作
        /// </summary>
        /// <returns></returns>
        public Response LoadingCharge(bus_material_distribute_load model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region 判断

                if (string.IsNullOrEmpty(model.startPosition))  return response.ResponseError("请选择装料点!");

                var locationItem = SystemVariable.locationList.Where(x => x.locationCode == model.endPosition).FirstOrDefault();
                if (locationItem != null && locationItem.askingStatus != (int)EnumLocationAskingStatus.已叫料)     return response.ResponseError("料点已经取消叫料!");

                //当前装料点
                var startLocationModel = base.Context.Queryable<base_location>()
                                                     .Where(x => x.locationCode == model.startPosition && x.locationStatus == (int)EnumLocationStatus.空闲)
                                                     .First();

                if (startLocationModel == null)     return response.ResponseError("装料点被锁定!");
                if (string.IsNullOrEmpty(startLocationModel.containerCode))     return response.ResponseError("装料点无料框!");

                //要去的叫料点
                var endLocationModel = base.Context.Queryable<base_location>()
                                                   .Where(x => x.locationCode == model.endPosition && x.locationStatus == (int)EnumLocationStatus.空闲)
                                                   .First();

                if (endLocationModel == null)   return response.ResponseError("叫料点被锁定!");

                if (string.IsNullOrEmpty(endLocationModel.containerCode) && endLocationModel.isWorkClothes == (int)EnumtIsWorkClothes.)
                {
                    return response.ResponseError("工装装料 叫料点需要有料框,请检查!");
                }

                var agvTaskType = (int)EnumAgvTaskType.上料配送;
                //如果是工装装料就改配送类型
                if (endLocationModel.isWorkClothes == (int)EnumtIsWorkClothes.)
                    agvTaskType = (int)EnumAgvTaskType.置换料框;

                //是否存在agv上料配送任务,如果有就报错
                var agvTaskExist = base.Context.Queryable<bus_agv_task>()
                                               .Where(t => t.state < (int)EnumAGVState.任务完成 && t.agvTaskType == agvTaskType &&
                                                           t.startPosition == model.startPosition && t.endPosition == model.endPosition)
                                               .Any();
                if (agvTaskExist)
                {
                    return response.ResponseError($"起始【{model.startPosition}】和终点【{model.endPosition}】还有未完成的AGV任务,不能装料!");
                }

                #endregion

                #region 记录装料数据

                var Code = Guid.NewGuid();
                model.keys = Code;
                model.needStation = endLocationModel.stationCode;
                model.containerCode = startLocationModel.containerCode;

                model.createBy = base.sysWebUser.Account;
                model.createTime = DateTime.Now;
                model.status = (int)EnumLoadData.已装料;

                base.Context.Insertable(model).AddQueue();

                #endregion

                #region 生成AGV任务

                bus_agv_task agvTask = new bus_agv_task();
                agvTask.keys = Guid.NewGuid();
                agvTask.taskCode = Guid.NewGuid().ToString();
                agvTask.agvCode = "";
                agvTask.agvTaskType = agvTaskType;
                agvTask.materialFrameCode = startLocationModel.containerCode;
                agvTask.materialDistributeLoadCode = Code.ToString();
                agvTask.workOrderCode = model.workOrderCode;
                agvTask.productHeaderCode = model.productCode;
                agvTask.startPosition = model.startPosition;
                agvTask.endPosition = model.endPosition;
                agvTask.state = (int)EnumAGVState.任务创建;
                agvTask.createTime = DateTime.Now;
                agvTask.createBy = base.sysWebUser.Account;

                //添加agv上料配送任务
                base.Context.Insertable(agvTask).AddQueue();

                //更新上料点的状态为锁定
                endLocationModel.locationStatus = (int)EnumLocationStatus.锁定;
                base.Context.Updateable(endLocationModel).UpdateColumns(t => t.locationStatus).AddQueue();

                //更新装料点的状态为锁定
                startLocationModel.locationStatus = (int)EnumLocationStatus.锁定;
                base.Context.Updateable(startLocationModel).UpdateColumns(t => t.locationStatus).AddQueue();

                #endregion

                #region 执行数据库操作
                
                //保存数据
                base.Context.SaveQueues();
               
                #endregion

                UpLocationVm(model.endPosition, EnumLocationAskingStatus.已装料);
                return response;
            });
        }

        #endregion
    }
}