MapController.cs 49.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
using Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Castle.Core.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using WebApp;
using WebRepository;

using System.ComponentModel.DataAnnotations.Schema;
using System.Drawing;
using Castle.Components.DictionaryAdapter;
using log4net;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;
using System.Reflection;
using Microsoft.AspNetCore.Authentication;
using RCS.Model.Comm;
using static RCS.Model.Comm.EnumMsg;
using Microsoft.VisualBasic;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebMvc
{
    /// <summary>
	/// 工作流模板信息表
	/// </summary>
    [Area("map")]
    public class MapController : BaseController
    {
        private readonly MapApp _app;
        private readonly IUnitWork _unitWork;
        //private readonly TBaseStationApp _tBaseStationApp;
        private readonly Map_content _Content;
        private readonly Mappoint _mappoint;
        private readonly Mapstations _mapstation;
        private readonly MapRegions _setinfo;
        private readonly BaseDbContext _baseContext;
        private readonly ACSDbContext _acsContext;
        //public MapController(IAuth authUtil, MapApp app, Map_content mpc, Mappoint mpp, Mapstations mpst, MapRegions mprs, IUnitWork unitWork, TBaseStationApp tBaseStationApp) : base(authUtil)
        public MapController(IAuth authUtil, MapApp app, Map_content mpc, Mappoint mpp, Mapstations mpst, MapRegions mprs, IUnitWork unitWork, ACSDbContext acsContext, BaseDbContext baseContext) : base(authUtil)
        {
            _app = app.SetLoginInfo(_loginInfo);
            _Content = mpc.SetLoginInfo(_loginInfo);
            _mappoint = mpp.SetLoginInfo(_loginInfo);
            _mapstation = mpst.SetLoginInfo(_loginInfo);
            _setinfo = mprs.SetLoginInfo(_loginInfo);
            _unitWork = unitWork;
            //_tBaseStationApp = tBaseStationApp;
            _baseContext = baseContext;
            _acsContext = acsContext;
        }

        #region 视图功能
        /// <summary>
        /// 默认视图Action
        /// </summary>
        /// <returns></returns>
        [Authenticate]
        [ServiceFilter(typeof(OperLogFilter))]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Design()
        {
            return View();
        }

        public ActionResult Preview()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 加载及分页查询
        /// 加载地图界面
        /// </summary>
        /// <param name="pageRequest">表单请求信息</param>
        /// <param name="entity">请求条件实例</param>
        /// <returns></returns>
        [HttpPost]
        public string Load(PageReq pageRequest, Map entity)
        {
            return JsonHelper.Instance.Serialize(_app.Load(pageRequest, entity));
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="Table_entity">新增实例</param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string Ins(Map Table_entity)
        {
            try
            {
                Map map = _baseContext.Maps.Where(u => u.Name == Table_entity.Name).FirstOrDefault();
                if (map != null)
                {
                    throw new Exception("地图名称重复!");
                }
                Upd(Table_entity);
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }



        private EnumMsg.StationType GetStationType(Area setInfo)
        {

            EnumMsg.StationType stationType = 0;
            if (setInfo.Color == "user_quliaoqu" || setInfo.Color == "user_fangliaoqu")
            {
                stationType = EnumMsg.StationType.工位;
                if (setInfo.SetInfo.StationType != null)
                {
                    stationType = (StationType)setInfo.SetInfo.StationType;
                }
            }
            else if (setInfo.Color == "user_tingchequ")
            {
                stationType = EnumMsg.StationType.回家位;
            }
            else if (setInfo.Color.Contains("user_diantiqu_", StringComparison.CurrentCulture))
            {
                stationType = EnumMsg.StationType.电梯区;
            }
            else if (setInfo.Color.Contains("user_tishengjiqu_", StringComparison.CurrentCulture))
            {
                stationType = EnumMsg.StationType.提升机区;
            }
            else if (setInfo.Color.Contains("user_chongdianzhuang", StringComparison.CurrentCulture))
            {
                stationType = EnumMsg.StationType.充电桩;
            }
            return stationType;
        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="Table_entity">修改实例</param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string Upd(Map Table_entity)
        {
            try
            {
                //List<ChangePointModel> changePointModels = GetChangedPoint(Table_entity);
                //Map map = _app.FindSingle(u => u.Name == Table_entity.Name && u.Id != Table_entity.Id);
                if (_unitWork.IsExist<Map>(u => u.Name == Table_entity.Name && u.Id != Table_entity.Id))
                {
                    throw new Exception("地图名称重复!");
                }
                Map map1 = _acsContext.Maps.Find(Table_entity.Id);

                map1 ??= Table_entity;
                //Map map1 = _app.FindSingle(u => u.Id == Table_entity.Id);


                List<TTaskDesign> taskDesign = _unitWork.Find<TTaskDesign>(u => ("," + u.Taskmap + ",").Contains("," + map1.Name + ",")).MapToList<TTaskDesign>();
                if (taskDesign.Count > 0)
                {
                    #region 检查该地图上有无未完成的任务
                    List<string> taskids = new List<string>();
                    foreach (var item in taskDesign)
                    {
                        taskids.Add(item.Taskid);
                    }
                    if (_unitWork.IsExist<TTaskAssign>(u => new List<int> { 0, 1 }.Contains(u.Status.Value) && taskids.Contains(u.Taskid)))
                    {
                        throw new Exception("不能变更地图,该地图:【" + map1.Name + "】 有尚未完成的任务!请等待任务完成后再操作。");
                    }
                    #endregion


                    foreach (var item in taskDesign)
                    {
                        List<TaskSplit> Taskcontent = JsonConvert.DeserializeObject<List<TaskSplit>>(item.Taskcontent);
                        #region 检查所有任务的关键点的RFID是否还存在
                        foreach (TaskSplit item1 in Taskcontent)
                        {
                            if (item1.Map.Equals(map1.Name))
                            {
                                string rfid = item1.RFID;
                                bool hasPoint = false;
                                foreach (var item2 in JsonConvert.DeserializeObject<MapContent>(Table_entity.MapContent).Areas)
                                {
                                    if (item2.Color.IndexOf("user_rfid") >= 0)
                                    {
                                        if (item2.SetInfo.RFID == rfid)
                                        {
                                            hasPoint = true;
                                            break;
                                        }
                                    }
                                }
                                if (!hasPoint)
                                {
                                    throw new Exception("不能变更地图,该地图:【" + map1.Name + "】 上的RFID:【" + rfid + "】 作为任务ID:【" + item.Taskid + "】 的关键点,不能删除!");
                                }
                            }
                        }
                        #endregion

                        #region 检查所有任务对应的路径是否OK
                        string keyPoints = JsonConvert.SerializeObject(Taskcontent);
                        string taskPaths = GetDemoTaskPath(keyPoints, Table_entity.Name);
                        TableData tableData = JsonConvert.DeserializeObject<TableData>(taskPaths);
                        if (tableData.code != 0)
                        {
                            throw new Exception("不能变更地图,变更后,模拟任务:【" + item.Taskid + "】 的路径失败, 错误信息:【" + tableData.msg + "】!");
                        }
                        else
                        {
                            List<TaskPathModel> taskPathModel = JsonConvert.DeserializeObject<List<TaskPathModel>>(tableData.data);
                            if (taskPathModel == null || taskPathModel.Count == 0)
                            {
                                throw new Exception("不能变更地图,变更后,模拟任务:【" + item.Taskid + "】 的路径失败!");
                            }
                            if (taskPathModel[taskPathModel.Count - 1].pathDriection != 0)
                            {
                                throw new Exception("不能变更地图,变更后,模拟任务:【" + item.Taskid + "】 的路径失败, 无法模拟到终点,只能模拟到点:【" + taskPathModel[taskPathModel.Count - 1].strBarcode + "】!");
                            }
                        }
                        #endregion
                    }
                }

                MapContent mapContent = JsonConvert.DeserializeObject<MapContent>(Table_entity.MapContent);
                Table_entity.Emptymap = true;

                #region 定义4个表的List
                List<MapPageContent> contents = new List<MapPageContent>();//头主表
                List<MapRegion> regions = new List<MapRegion>();//管制区域表
                List<MapPoint> points = new List<MapPoint>();//点位表
                List<MapStation> stations = new List<MapStation>();//站台表
                #endregion

                #region 新增修改地图方法       
                #region 修改管制区域
                if (mapContent.Regions != null)
                {
                    for (int i = 0; i < mapContent.Regions.Count(); i++)
                    {
                        MapRegion region = new MapRegion();
                        region.AreaName = Table_entity.Name;
                        region.RegionId = mapContent.Regions[i].RegionId;
                        region.RegionName = mapContent.Regions[i].RegionName;
                        region.RegionPoint1 = mapContent.Regions[i].RegionPoint1;
                        region.RegionPoint2 = mapContent.Regions[i].RegionPoint2;
                        region.RegionPoint3 = mapContent.Regions[i].RegionPoint3;
                        region.RegionPoint1_Id = mapContent.Regions[i].RegionPoint1_Id;
                        region.RegionPoint2_Id = mapContent.Regions[i].RegionPoint2_Id;
                        region.RegionPoint3_Id = mapContent.Regions[i].RegionPoint3_Id;
                        region.LAY_TABLE_INDEX = mapContent.Regions[i].LAY_TABLE_INDEX;
                        regions.Add(region);
                        //_setinfo.mpcIns(region);
                        MapPageContent map_Content = new MapPageContent();
                        map_Content.Color = "user_group";
                        map_Content.MapName = Table_entity.Name;
                        map_Content.Name = region.RegionId;
                        map_Content.Left = mapContent.Regions[i].Left;
                        map_Content.Top = mapContent.Regions[i].Top;
                        map_Content.Width = mapContent.Regions[i].Width;
                        map_Content.Height = mapContent.Regions[i].Height;
                        map_Content.aid = region.RegionId;
                        map_Content.Alt = true;
                        contents.Add(map_Content);
                        //_Content.mpcIns(map_Content);
                    }
                }
                #endregion

                //再插入修改后的数据
                foreach (Area item in mapContent.Areas)
                {
                    MapPageContent map_Content = new MapPageContent();
                    map_Content.MapName = Table_entity.Name;//全区域名
                    map_Content.Name = item.Name;//"运行区",
                    map_Content.Left = item.Left;//地图方位
                    map_Content.Top = item.Top;//地图方位
                    map_Content.Color = item.Color;
                    map_Content.Width = item.Width;
                    map_Content.Height = item.Height;
                    map_Content.aid = item.Id;
                    map_Content.Alt = true;
                    contents.Add(map_Content);

                    if (item.Color.IndexOf("user_rfid") >= 0)
                    {

                        Table_entity.Emptymap = false;

                        if (item.SetInfo == null)
                        {
                            throw new Exception($"区域{item.Name}中的点的属性未填写!");
                        }

                        var pointType = string.IsNullOrEmpty(item.SetInfo.Point_type)
                            ? PointType.整体旋转点
                            : (PointType)int.Parse(item.SetInfo.Point_type);
                        //: (PointType)Enum.Parse(typeof(PointType), item.SetInfo.Point_type);

                        if (item.SetInfo.Point_area == "user_quliaoqu" || item.SetInfo.Point_area == "user_fangliaoqu")
                        {
                            //取放料区的运行点给站台点的属性
                            pointType = PointType.站台点;
                        }

                        #region 插入新增point
                        MapPoint mapPoint = new MapPoint();
                        if (item.SetInfo != null)
                        {
                            mapPoint.AID = item.SetInfo.Id ?? "";//AID当加载地图时需要将字段名换成Id
                            mapPoint.Name = item.Name ?? "";
                            mapPoint.Left = item.Left.ToString() ?? "";
                            mapPoint.Top = item.Top.ToString() ?? "";
                            mapPoint.RegionName = string.IsNullOrEmpty(item.SetInfo.RegionName) ? "" : item.SetInfo.RegionName;
                            mapPoint.Point_turn = item.SetInfo.Point_turn ?? 0;
                            mapPoint.Point_area = item.SetInfo.Point_area ?? "";
                            mapPoint.RFID = item.SetInfo.RFID ?? "";
                            mapPoint.PauseTime = item.SetInfo.PauseTime ?? "";
                            mapPoint.IsStop = item.SetInfo.IsStop ?? 0;
                            mapPoint.IntStopLevel = item.SetInfo.IntStopLevel ?? 0;
                            mapPoint.IntAgvAngle = item.SetInfo.IntAgvAngle ?? 0;
                            //以下是ACS调度用到的字段
                            mapPoint.AreaType = Table_entity.Name;
                            mapPoint.Barcode = item.SetInfo.RFID ?? "";
                            mapPoint.BarcodeValue = "";
                            mapPoint.PreBarcode = "";
                            mapPoint.PointType = pointType;
                            if (mapPoint.Left != "" && mapPoint.Left != null)
                            {
                                mapPoint.IntX = int.Parse(mapPoint.Left) / 30 + 1;
                            }
                            else
                            {
                                mapPoint.IntX = null;
                            }
                            if (mapPoint.Top != "" && mapPoint.Top != null)
                            {
                                mapPoint.IntY = 1000 - (int.Parse(mapPoint.Top) / 30 + 1);
                            }
                            else
                            {
                                mapPoint.IntY = null;
                            }
                            mapPoint.IsEnable = mapPoint.Is_enable ?? true;
                            mapPoint.IsOccupy = false;
                            mapPoint.OccupyAgvNo = "";
                            mapPoint.IsXpos = item.SetInfo.Chk_right ?? false;
                            mapPoint.IsXNeg = item.SetInfo.Chk_left ?? false;
                            mapPoint.IsYPos = item.SetInfo.Chk_up ?? false;
                            mapPoint.IsYNeg = item.SetInfo.Chk_down ?? false;
                            mapPoint.XLength = item.SetInfo.IntXC ?? 0;
                            mapPoint.YLength = item.SetInfo.IntYC ?? 0;
                            mapPoint.AgvAngle = 0;
                            mapPoint.AgvAngle = (int)(item.SetInfo.IntAgvAngle * 10 ?? 0);
                            if (mapPoint.PauseTime == "" || mapPoint.PauseTime == null)
                            {
                                mapPoint.StopTime = 0;
                            }
                            else
                            {
                                var tm = int.Parse(mapPoint.PauseTime);
                                mapPoint.StopTime = tm;
                            }
                            mapPoint.StopLevel = mapPoint.IntStopLevel;
                            mapPoint.AgvDirectionXPos = item.SetInfo.AgvDirectionXPos;
                            mapPoint.AgvDirectionXNeg = item.SetInfo.AgvDirectionXNeg;
                            mapPoint.AgvDirectionYPos = item.SetInfo.AgvDirectionYPos;
                            mapPoint.AgvDirectionYNeg = item.SetInfo.AgvDirectionYNeg;
                            mapPoint.DialDirectionXPos = item.SetInfo.DialDirectionXPos;
                            mapPoint.DialDirectionXNeg = item.SetInfo.DialDirectionXNeg;
                            mapPoint.DialDirectionYPos = item.SetInfo.DialDirectionYPos;
                            mapPoint.DialDirectionYNeg = item.SetInfo.DialDirectionYNeg;
                            mapPoint.AdjustIn = item.SetInfo.AdjustIn;
                            mapPoint.AdjustOut = item.SetInfo.AdjustOut;
                            mapPoint.SpeedXPos = item.SetInfo.SpeedXPos;
                            mapPoint.SpeedXNeg = item.SetInfo.SpeedXNeg;
                            mapPoint.SpeedYPos = item.SetInfo.SpeedYPos;
                            mapPoint.SpeedYNeg = item.SetInfo.SpeedYNeg;
                            mapPoint.RadarXPos = item.SetInfo.RadarXPos;
                            mapPoint.RadarXNeg = item.SetInfo.RadarXNeg;
                            mapPoint.RadarYPos = item.SetInfo.RadarYPos;
                            mapPoint.RadarYNeg = item.SetInfo.RadarYNeg;
                            mapPoint.ArcingLevel = item.SetInfo.ArcingLevel;
                            mapPoint.IntAgvAngle = item.SetInfo.IntAgvAngle ?? 0;
                            mapPoint.XPosGValue = item.SetInfo.XPosGValue ?? 0;
                            mapPoint.XNegGValue = item.SetInfo.XNegGValue ?? 0;
                            mapPoint.YNegGValue = item.SetInfo.YNegGValue ?? 0;
                            mapPoint.YPosGValue = item.SetInfo.YPosGValue ?? 0;
                            //_mappoint.mpcIns(mapp);
                            points.Add(mapPoint);
                        }
                        #endregion
                    }

                    else if (item.Color == "user_quliaoqu"
                        || item.Color == "user_fangliaoqu"
                        || item.Color == "user_tingchequ"
                        || item.Color.Contains("user_diantiqu_", StringComparison.CurrentCulture)
                        || item.Color.Contains("user_tishengjiqu_", StringComparison.CurrentCulture)
                        || item.Color.Contains("user_chongdianzhuang", StringComparison.CurrentCulture))
                    {

                        var stationType = GetStationType(item);
                        var strBarcode = item.SetInfo.RFID;
                        if (item.SetInfo == null)
                        {
                            throw new Exception($"站台{item.Name}的属性未填写!");
                        }


                        if (item.Color.Contains("user_chongdianzhuang", StringComparison.CurrentCulture))
                        {
                            strBarcode = item.SetInfo.ChargeRFID;
                        }
                        else if (item.Color == "user_quliaoqu"
                        || item.Color == "user_fangliaoqu"
                        || item.Color == "user_tingchequ"
                        || item.Color.Contains("user_diantiqu_", StringComparison.CurrentCulture)
                        || item.Color.Contains("user_tishengjiqu_", StringComparison.CurrentCulture))
                        {


                            //获取当前站台的附属点,如果有判断是否在点内
                            if (item.SetInfo.ListRFID != null)
                            {
                                var barcode = item.SetInfo.ListRFID.Split('#')[0];
                                if (!mapContent.Areas.Any(u => u.SetInfo != null && u.SetInfo.RFID == barcode))
                                {
                                    throw new Exception($"站台{item.SetInfo.RFID}的附属点错误!");
                                }
                            }

                        }



                        MapStation mapStation = new MapStation();
                        if (item.SetInfo != null)
                        {
                            mapStation.AID = item.SetInfo.Id ?? "";//AID当加载地图时需要将字段名换成Id
                            mapStation.Name = item.Name ?? "";
                            mapStation.Left = item.Left.ToString() ?? "";
                            mapStation.Top = item.Top.ToString() ?? "";
                            mapStation.Width = item.Width.ToString() ?? "";
                            mapStation.Height = item.Height.ToString() ?? "";
                            mapStation.ChargeRFID = item.SetInfo.ChargeRFID ?? "";
                            mapStation.ChargeDirection = item.SetInfo.ChargeDirection ?? "";
                            mapStation.ChargeLength = item.SetInfo.ChargeLength ?? "";
                            mapStation.RFID = item.SetInfo.RFID ?? "";
                            mapStation.ListRFID = item.SetInfo.ListRFID ?? "";
                            mapStation.Txt_up = item.SetInfo.Txt_up ?? "";
                            mapStation.Txt_down = item.SetInfo.Txt_down ?? "";
                            mapStation.Txt_left = item.SetInfo.Txt_left ?? "";
                            mapStation.Txt_right = item.SetInfo.Txt_right ?? "";
                            mapStation.Code = item.SetInfo.Code ?? "";
                            mapStation.StationType = stationType;
                            mapStation.Area = Table_entity.Name;
                            mapStation.Group = "";
                            mapStation.StationDirection = item.SetInfo.StationDirection;
                            mapStation.LowHeight = item.SetInfo.LowHeight;
                            mapStation.HighHeight = item.SetInfo.HighHeight;
                            mapStation.IsEnable = item.SetInfo.IsEnable ?? false;
                            mapStation.IsLocked = item.SetInfo.IsLocked ?? false;//false;
                            mapStation.Barcode = strBarcode;
                            mapStation.PreBarcode = item.SetInfo.ListRFID ?? "";
                            mapStation.Tim = 0;
                            mapStation.StationState = 0;
                            stations.Add(mapStation);
                        }
                    }

                }

                if (Table_entity.IsDefault == 1)
                {
                    var Maps = _unitWork.Find<Map>(u => u.Id != Table_entity.Id).ToList();
                    foreach (var item in Maps)
                    {
                        item.IsDefault = 0;
                        _unitWork.Update(item);
                    }
                }
                //先删除子表原数据

                var context = _acsContext;

                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var res = context.Database.ExecuteSql($"delete from t_base_map_content where mapname={map1.Name} and ifnull( areasID,'')!=''");
                        res = context.Database.ExecuteSql($"delete from t_base_map_point where areaType={map1.Name} and ifnull( AID,'')!=''");
                        res = context.Database.ExecuteSql($"delete from t_base_map_station where area={map1.Name} and ifnull( AID,'')!=''");
                        res = context.Database.ExecuteSql($"delete from t_base_map_region where areaName={map1.Name}");


                        context.AddRange(contents);
                        context.AddRange(regions);
                        context.AddRange(stations);
                        context.AddRange(points);

                        if ((map1.Id ?? 0) == 0)
                        {
                            context.Add(map1);
                        }
                        else
                        {
                            map1.Name = Table_entity.Name;
                            map1.MapContent = Table_entity.MapContent;
                            map1.IsDefault = Table_entity.IsDefault;
                            map1.Description = Table_entity.Description;
                            map1.Emptymap = Table_entity.Emptymap;
                            map1.UpdateBy = _loginInfo.Account;
                            map1.UpdateTime = DateTime.Now;
                            context.Update(map1);
                        }
                        context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;

                AfterDemo(Table_entity);
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string DelByIds(int[] ids)
        {
            try
            {
                foreach (var id in ids)
                {
                    Map map = _app.FindSingle(u => u.Id == id);

                    TTaskDesign taskDesign = _unitWork.FindSingle<TTaskDesign>(u => ("," + u.Taskmap + ",").Contains("," + map.Name + ","));
                    if (taskDesign != null)
                    {
                        throw new Exception("不能变更地图,该地图:【" + map.Name + "】已应用于任务类型:" + taskDesign.Taskname + "!请删除任务类型后再操作。");
                    }


                    var context = this._baseContext;

                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            var res = context.Database.ExecuteSql($"delete from t_base_map_content where mapname={map.Name} and ifnull( areasID,'')!=''");
                            res = context.Database.ExecuteSql($"delete from t_base_map_point where areaType={map.Name} and ifnull( AID,'')!=''");
                            res = context.Database.ExecuteSql($"delete from t_base_map_station where area={map.Name} and ifnull( AID,'')!=''");
                            res = context.Database.ExecuteSql($"delete from t_base_map_region where areaName={map.Name}");
                            res = context.Database.ExecuteSql($"delete from map where id={map.Id}");

                            //_app.DelByIds(new int[] { id });

                            context.SaveChanges();
                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                        }
                    }




                }
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }
        #endregion

        #region 导出数据
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="entity">请求条件实例</param>
        /// <returns></returns>
        [HttpPost]
        public string Export(Map entity)
        {
            return JsonHelper.Instance.Serialize(_app.ExportData(entity));
        }
        #endregion

        #region 导出模板
        /// <summary>
        /// 导出模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetTemplate()
        {
            var result = new TableData();
            List<Map> listFlowScheme = new List<Map>();
            Map entity = _app.FindSingle(u => u.Id > 0);
            if (entity != null)
            {
                listFlowScheme.Add(entity);
            }
            else
            {
                listFlowScheme.Add(new Map());
            }

            result.data = listFlowScheme;
            result.count = listFlowScheme.Count;

            return JsonHelper.Instance.Serialize(result);
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="excelfile">表单提交的文件信息</param>
        /// <returns></returns>
        [HttpPost]
        public string Import(IFormFile excelfile)
        {
            try
            {
                Response result = _app.ImportIn(excelfile);
                if (!result.Status)
                {
                    Result.Status = false;
                    Result.Message = result.Message;
                }
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }
        #endregion

        #region 自定义方法
        /// <summary>
        /// 进入地图信息界面-20240428
        /// </summary>
        public string Get(string id)
        {
            try
            {
                var result = new Response<Map> { Result = _app.Get(id) };
                return JsonHelper.Instance.Serialize(result);
            }
            catch (Exception ex)
            {
                Result.Code = 500;
                Result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        public string GetMaps()
        {
            return JsonHelper.Instance.Serialize(_app.GetMaps());
        }

        public string CheckDefault()
        {
            return JsonHelper.Instance.Serialize(_app.CheckDefault());
        }

        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string MapBkp(int id)
        {
            try
            {
                _app.MapBkp(id);
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string MapRestore(int id)
        {
            try
            {
                _app.MapRestore(id);
                Map map = _app.FindSingle(u => u.Id.Equals(id));
                Upd(map);
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string GetMapIdByName(string mapName)
        {
            try
            {
                Map map1 = _app.FindSingle(u => u.Name.Equals(mapName));
                if (map1 != null)
                {
                    Result.Message = map1.Id.ToString();
                }
                else
                {
                    throw new Exception("获取地图Id失败!");
                }
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="Table_entity">修改实例</param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(OperLogFilter))]
        public string UpdBaseInfo(Map Table_entity)
        {
            try
            {
                if (Table_entity.IsDefault == 1)
                {
                    var Maps = _unitWork.Find<Map>(u => u.Id != Table_entity.Id).ToList();
                    foreach (var item in Maps)
                    {
                        item.IsDefault = 0;
                        _unitWork.Update(item);
                    }
                }

                var context = _unitWork.GetDbContext();
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        Map map2 = context.Maps.FirstOrDefault(x => x.Id.Equals(Table_entity.Id));
                        var res = context.Database.ExecuteSql($"update t_base_map_content set mapname={Table_entity.Name}  where mapname={map2.Name} and ifnull( areasID,'')!=''");
                        res = context.Database.ExecuteSql($"update t_base_map_point set areaType={Table_entity.Name} where areaType={map2.Name} and ifnull( AID,'')!=''");
                        res = context.Database.ExecuteSql($"update t_base_map_station set  area={Table_entity.Name} where area={map2.Name} and ifnull( AID,'')!=''");
                        res = context.Database.ExecuteSql($"update t_base_map_region set  areaName={Table_entity.Name} where areaName={map2.Name}");

                        map2.Name = Table_entity.Name;
                        map2.IsDefault = Table_entity.IsDefault;
                        map2.Description = Table_entity.Description;
                        map2.UpdateBy = _loginInfo.Account;
                        map2.UpdateTime = DateTime.Now;
                        context.Update(map2);

                        context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }





                //_unitWork.Update<Map>(u => u.Id.Equals(Table_entity.Id), u => new Map
                //{
                //    Name = Table_entity.Name,
                //    IsDefault = Table_entity.IsDefault,
                //    Description = Table_entity.Description,
                //    UpdateBy = _loginInfo.Account,
                //    UpdateTime = DateTime.Now,
                //});
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }

        /// <summary>
        /// 获取任务模拟路径
        /// </summary>
        /// <param name="keyPoints"></param>
        /// <returns></returns>
        private string GetTaskPath(string keyPoints)
        {
            TableData tableData = new TableData();

            try
            {
                List<TaskSplit> ListkeyPoints = JsonHelper.Instance.Deserialize<List<TaskSplit>>(keyPoints);
                List<TaskPreviewModel> taskSplit = new List<TaskPreviewModel>();

                string fromArea = "";
                string fromPoint = "";
                int intSeriaNo = 1;
                foreach (TaskSplit item in ListkeyPoints)
                {
                    if (fromPoint != "")
                    {
                        taskSplit.Add(new TaskPreviewModel()
                        {
                            fromArea = fromArea,
                            fromPoint = fromPoint,
                            toArea = item.Map,
                            toPoint = item.RFID,
                        });
                    }
                    fromArea = item.Map;
                    fromPoint = item.RFID;
                }

                ApiRequest apiRequest = new ApiRequest("RCS");
                string parameter = JsonHelper.Instance.Serialize(taskSplit);
                Response response = apiRequest.Post<Response>(parameter, "TaskPreview", "RCS");
                if (response.Code != 0)
                {
                    throw new Exception(response.Message);
                }
                else
                {
                    tableData.data = response.Message;
                }
            }
            catch (Exception ex)
            {
                tableData.code = 500;
                tableData.msg = ex.Message;
            }

            return JsonHelper.Instance.Serialize(tableData);
        }

        #region 地图编辑时创建模拟地图
        private void AddSimMap(Map Table_entity)
        {
            MapContent mapContent = JsonConvert.DeserializeObject<MapContent>(Table_entity.MapContent);

            foreach (Area item in mapContent.Areas)
            {
                if (item.Color.IndexOf("user_rfid") >= 0)
                {
                    if (item.SetInfo == null)
                    {
                        throw new Exception("点的属性未填写!");
                    }

                    var pointType = string.IsNullOrEmpty(item.SetInfo.Point_type) ? 1 : int.Parse(item.SetInfo.Point_type);
                    //if (item.SetInfo.Point_turn == 1)
                    //{
                    //    //整体旋转点
                    //    pointType = 12;
                    //}
                    if (item.SetInfo.Point_area == "user_quliaoqu" || item.SetInfo.Point_area == "user_fangliaoqu")
                    {
                        //取放料区的运行点给站台点的属性
                        pointType = 4;
                    }
                    string parameter = JsonHelper.Instance.Serialize(new ChangePointModel
                    {
                        Barcode = item.SetInfo.RFID,
                        AreaType = Table_entity.Name,
                        pointType = pointType,
                        intX = item.Left.Value / 30 + 1,
                        intY = 1000 - (item.Top.Value / 30 + 1),
                        isXPos = item.SetInfo.Chk_right ?? false,
                        isXNeg = item.SetInfo.Chk_left ?? false,
                        isYPos = item.SetInfo.Chk_up ?? false,
                        isYNeg = item.SetInfo.Chk_down ?? false,
                        XLength = item.SetInfo.IntXC.Value,
                        YLength = item.SetInfo.IntYC.Value,
                        isEnable = item.SetInfo.Is_enable ?? true,
                        RegionName = string.IsNullOrEmpty(item.SetInfo.RegionName) ? "" : item.SetInfo.RegionName,
                        //stopTime = string.IsNullOrEmpty(item.SetInfo.PauseTime) ? 0 : int.Parse(item.SetInfo.PauseTime),
                        isStop = item.SetInfo.IsStop ?? 0,
                        StopLevel = item.SetInfo.IntStopLevel ?? 0,
                        DlAgvOri = (int)(item.SetInfo.IntAgvAngle * 10 ?? 0),
                        type = "simInsert",
                    });

                    ApiRequest apiRequest = new ApiRequest("RCS");
                    Response response = apiRequest.Post<Response>(parameter, "ChangePoint", "RCS");
                    if (response.Code != 0)
                    {
                        throw new Exception(response.Message);
                    }
                }
            }
        }

        private void DelSimMap(Map Table_entity)
        {
            ApiRequest apiRequest = new ApiRequest("RCS");
            string parameter = JsonHelper.Instance.Serialize(new ChangePointModel
            {
                Barcode = "",
                AreaType = Table_entity.Name,
                pointType = 0,
                intX = 0,
                intY = 0,
                isXPos = false,
                isXNeg = false,
                isYPos = false,
                isYNeg = false,
                XLength = 0,
                YLength = 0,
                isEnable = true,
                RegionName = "",
                stopTime = 0,
                type = "simDelete",
            });
            Response response = apiRequest.Post<Response>(parameter, "ChangePoint", "RCS");
            if (response.Code != 0)
            {
                throw new Exception(response.Message);
            }
        }

        private void SaveSimMap(Map Table_entity)
        {
            ApiRequest apiRequest = new ApiRequest("RCS");
            string parameter = JsonHelper.Instance.Serialize(new ChangePointModel
            {
                Barcode = "",
                AreaType = Table_entity.Name,
                pointType = 0,
                intX = 0,
                intY = 0,
                isXPos = false,
                isXNeg = false,
                isYPos = false,
                isYNeg = false,
                XLength = 0,
                YLength = 0,
                isEnable = true,
                RegionName = "",
                stopTime = 0,
                type = "simSave",
            });
            Response response = apiRequest.Post<Response>(parameter, "ChangePoint", "RCS");
            if (response.Code != 0)
            {
                throw new Exception(response.Message);
            }
        }

        private void BeforDemo(Map Table_entity)
        {
            //AddSimMap(Table_entity);
            //SaveSimMap(Table_entity);
        }

        private void AfterDemo(Map Table_entity)
        {
            try
            {
                //DelSimMap(Table_entity);
                //SaveSimMap(Table_entity);
            }
            catch (Exception) { }
        }
        /// <summary>
        /// 地图编辑时模拟地图任务路径
        /// </summary>
        /// <param name="keyPoints">任务关键点</param>
        /// <param name="Table_entity">编辑后地图</param>
        /// <returns></returns>
        private string GetDemoTaskPath(string keyPoints, string areaType)
        {
            TableData tableData = new TableData();

            try
            {
                List<TaskSplit> ListkeyPoints = JsonHelper.Instance.Deserialize<List<TaskSplit>>(keyPoints);

                //DemoTaskPreviewModel demoTaskPreviewModel = new DemoTaskPreviewModel();
                List<TaskPreviewModel> taskSplit = new List<TaskPreviewModel>();

                //demoTaskPreviewModel.areaType = areaType;
                string fromArea = "";
                string fromPoint = "";
                int intSeriaNo = 1;
                foreach (TaskSplit item in ListkeyPoints)
                {
                    if (fromPoint != "")
                    {
                        taskSplit.Add(new TaskPreviewModel()
                        {
                            TaskMap = areaType,
                            fromArea = fromArea,
                            fromPoint = fromPoint,
                            toArea = item.Map,
                            toPoint = item.RFID,
                        });
                    }
                    fromArea = item.Map;
                    fromPoint = item.RFID;
                }
                //demoTaskPreviewModel.taskPreviewModels = taskSplit;

                ApiRequest apiRequest = new ApiRequest("RCS");
                string parameter = JsonHelper.Instance.Serialize(taskSplit);
                Response response = apiRequest.Post<Response>(parameter, "DemoTaskPreview", "RCS");
                if (response.Code != 0)
                {
                    throw new Exception(response.Message);
                }
                else
                {
                    tableData.data = response.Message;
                }
            }
            catch (Exception ex)
            {
                tableData.code = 500;
                tableData.msg = ex.Message;
            }

            return JsonHelper.Instance.Serialize(tableData);
        }
        #endregion


        #region 获取地图变动
        private List<ChangePointModel> GetChangedPoint(Map Table_entity)
        {
            Map map = _unitWork.FindSingle<Map>(u => u.Id.Equals(Table_entity.Id));
            MapContent mapContent_Old = JsonConvert.DeserializeObject<MapContent>(map.MapContent);
            MapContent mapContent_New = JsonConvert.DeserializeObject<MapContent>(Table_entity.MapContent);

            Area[] points_old = mapContent_Old.Areas.Where(u => u.Color.IndexOf("user_rfid") >= 0).ToArray();
            Area[] points_new = mapContent_New.Areas.Where(u => u.Color.IndexOf("user_rfid") >= 0).ToArray();

            string[] points_old_str = points_old.Select<Area, string>(u => JsonHelper.Instance.Serialize(u)).ToArray();
            string[] points_new_str = points_new.Select<Area, string>(u => JsonHelper.Instance.Serialize(u)).ToArray();

            List<string> areasAdd_str = points_new_str.Except<string>(points_old_str).ToList();
            List<string> areasDelete_str = points_old_str.Except<string>(points_new_str).ToList();
            List<string> areasSame_str = points_new_str.Intersect<string>(points_old_str).ToList();
            List<string> areasUpdate_str = points_new_str.Except<string>(areasAdd_str).Except<string>(areasSame_str).ToList();

            List<Area> areasAdd = areasAdd_str.Select<string, Area>(u => JsonHelper.Instance.Deserialize<Area>(u)).ToList();
            List<Area> areasDelete = areasDelete_str.Select<string, Area>(u => JsonHelper.Instance.Deserialize<Area>(u)).ToList();
            List<Area> areasSame = areasSame_str.Select<string, Area>(u => JsonHelper.Instance.Deserialize<Area>(u)).ToList();
            List<Area> areasUpdate = areasUpdate_str.Select<string, Area>(u => JsonHelper.Instance.Deserialize<Area>(u)).ToList();

            List<ChangePointModel> changePointModels = new List<ChangePointModel>();

            AddList(changePointModels, areasAdd, Table_entity.Name, "Add");
            AddList(changePointModels, areasDelete, Table_entity.Name, "Delete");
            AddList(changePointModels, areasUpdate, Table_entity.Name, "Update");

            return changePointModels;
        }

        private List<ChangePointModel> AddList(List<ChangePointModel> changePointModels, List<Area> areas, string areaType, string type)
        {
            foreach (var item in areas)
            {
                if (item.SetInfo == null)
                {
                    throw new Exception("点:【Id:" + item.Id + ", Left:" + item.Left + ", Top:" + item.Top + "】的属性未填写!");
                }
                var pointType = string.IsNullOrEmpty(item.SetInfo.Point_type) ? 1 : int.Parse(item.SetInfo.Point_type);
                //if (item.SetInfo.Point_turn == 1)
                //{
                //    //整体旋转点
                //    pointType = 12;
                //}
                if (item.SetInfo.Point_area == "user_quliaoqu" || item.SetInfo.Point_area == "user_fangliaoqu")
                {
                    //取放料区的运行点给站台点的属性
                    pointType = 4;
                }
                ChangePointModel changePointModel = new ChangePointModel
                {
                    Barcode = item.SetInfo.RFID,
                    AreaType = areaType,
                    pointType = pointType,
                    intX = item.Left.Value / 30 + 1,
                    intY = 1000 - (item.Top.Value / 30 + 1),
                    isXPos = item.SetInfo.Chk_right ?? false,
                    isXNeg = item.SetInfo.Chk_left ?? false,
                    isYPos = item.SetInfo.Chk_up ?? false,
                    isYNeg = item.SetInfo.Chk_down ?? false,
                    XLength = item.SetInfo.IntXC.Value,
                    YLength = item.SetInfo.IntYC.Value,
                    isEnable = item.SetInfo.Is_enable ?? true,
                    RegionName = string.IsNullOrEmpty(item.SetInfo.RegionName) ? "" : item.SetInfo.RegionName,
                    stopTime = string.IsNullOrEmpty(item.SetInfo.PauseTime) ? 0 : int.Parse(item.SetInfo.PauseTime),
                    isStop = item.SetInfo.IsStop ?? 0,
                    StopLevel = item.SetInfo.IntStopLevel ?? 0,
                    DlAgvOri = (int)(item.SetInfo.IntAgvAngle * 10 ?? 0),
                    type = type,
                };
                changePointModels.Add(changePointModel);
            }
            return changePointModels;
        }
        #endregion
        #endregion
    }
}