using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Newtonsoft.Json;
using PlcSiemens.Core.Extension;
using ServiceCenter.Extensions;
using ServiceCenter.Logs;
using ServiceCenter.Redis;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.SRM;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.Worlds;
using static System.Runtime.InteropServices.JavaScript.JSType;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  Agv交互系统
    /// </summary>
    [BelongTo(typeof(MainWorld))]
    [Description("Agv交互系统")]
    public class AgvSystems : DeviceSystem<Station>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        private List<Station> devs = new List<Station>();
        private List<SRM> srms = new List<SRM>();

        public AgvSystems()
        {
            var stations = new List<string>() { "1011", "1012", "1013", "1014", "1015", "1016", "1021", "1022", "1023", "1024", "1025", "1026", "1117", "1118",
                                                "1131", "1132", "1133", "1134", "1135", "1136", "1137", "1138", "1139","1127" };
            devs = Device.All.Where(v => stations.Contains(v.Code)).Select(v => new Station(v, this.World)).ToList();
            srms = Device.All.Where(v => v.Code is "SRM1" or "SRM2" or "SRM3" or "SRM4").Select(v => new SRM(v, this.World)).ToList();
        }

        public override void Do(Station obj)
        {
            if (obj.Entity.HasFlag(DeviceFlags.出库))
            {

                List<WCS_AgvTaskInfo> agvTaskInfos = new List<WCS_AgvTaskInfo>();
                //获取所有未结束的叫料及背负式补空AGV任务
                SqlSugarHelper.Do(db =>
                {

                    agvTaskInfos = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => (v.TaskType == AGVTaskType.CallMaterial || v.TaskType == AGVTaskType.CallForMaterial || v.TaskType == AGVTaskType.ForkliftFilling))
                                                                         .Where(v => v.Status < AGVTaskStatus.MissionCompleted)
                                                                         .SplitTable(tabs => tabs.Take(2)).OrderBy(v => v.AddTime).ToList();
                });
                //有需要处理的AGV任务
                if (agvTaskInfos.Any())
                {
                    //this.ExRecord(obj.Entity.Code, "可用出库AGV任务列表", agvTaskInfos.Select(v => v.ID).ToList());
                    //List<WCS_TaskInfo> taskInfos = new List<WCS_TaskInfo>();

                    foreach (var agv in agvTaskInfos)
                    {
                        try
                        {
                            SqlSugarHelper.Do(db =>
                            {
                                //取货点安全交互
                                if (agv.AgvStatus == AGVTaskStatus.RequestOrPermission2 && agv.Status != AGVTaskStatus.Complete2)
                                {
                                    var taskInfo = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agv.ID);
                                    agv.Status = AGVTaskStatus.Complete2;
                                    db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();
                                    taskInfo.AddWCS_TASK_DTL(db, "agv", $"允许AGV任务{agv.ID}在站台{agv.Station}取货");
                                    AgvApi.ContinueTask(agv.AgvID, agv.Station);
                                }
                                //完成任务
                                else if (agv.AgvStatus == AGVTaskStatus.MissionCompleted && agv.Status != AGVTaskStatus.MissionCompleted)
                                {
                                    if (agv.TaskType is AGVTaskType.CallForMaterial or AGVTaskType.ForkliftFilling or AGVTaskType.CallMaterial)
                                    {
                                        var taskInfo = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agv.ID);
                                        if (taskInfo == null) throw new Exception($"未找到AGV任务{agv.ID}对应WCS任务");
                                        //更新AGV任务状态
                                        agv.Status = AGVTaskStatus.MissionCompleted;
                                        db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();
                                        //更新WCS任务状态
                                        taskInfo.Status = Entity.TaskStatus.Finish;
                                        taskInfo.EedTime = DateTime.Now;
                                        db.Default.Updateable(taskInfo).ExecuteCommand();
                                        taskInfo.AddWCS_TASK_DTL(db, "agv", "任务完成");
                                        //通知WMS任务完成
                                        WmsApi.CompleteTask(taskInfo.ID);
                                        taskInfo.CompleteOrCancelTasks(db);
                                        //taskInfos.Add(taskInfo);
                                    }
                                    else
                                    {
                                        agv.Status = AGVTaskStatus.MissionCompleted;
                                        db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();
                                    }
                                }
                            });
                        }
                        catch (Exception ex)
                        {
                            World.Log(ex.Message, LogLevelEnum.Mid);
                            this.ExRecord(obj.Entity.Code, ex.Message);
                            continue;
                        }
                    }


                    //foreach (var item in taskInfos)
                    //{
                    //    WmsApi.CompleteTask(item.ID);
                    //}
                }
            }
            else if (obj.Entity.HasFlag(DeviceFlags.入库))
            {
                List<WCS_AgvTaskInfo> agvTaskInfos = new List<WCS_AgvTaskInfo>();
                //获取所有未结束的入库AGV任务
                SqlSugarHelper.Do(db =>
                {

                    agvTaskInfos = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => v.Status < AGVTaskStatus.MissionCompleted && v.TaskType == AGVTaskType.EnterDepot).SplitTable(tabs => tabs.Take(2)).OrderBy(v => v.EditTime).ToList();
                });

                if (agvTaskInfos.Any())
                {
                    //this.ExRecord(obj.Entity.Code, "可用入库AGV任务列表", agvTaskInfos.Select(v => v.ID).ToList());
                    var guid = Guid.NewGuid();
                    World.Log($"agv任务处理:开始[{guid}]", LogLevelEnum.Mid);
                    foreach (var agv in agvTaskInfos)
                    {
                        try
                        {
                            int isApplyContainue = 0;
                            string agvid = "";
                            string nextpos = "";
                            SqlSugarHelper.Do(db =>
                            {
                                //找到对应WCS任务
                                //var task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agv.ID);
                                //if (task == null) throw new Exception($"AGV任务{agv.ID}未找到对应WCS任务");
                               var agvInfo = db.Default.Queryable<WCS_AgvTaskInfo>().Where(x => x.ID == agv.ID).SplitTable(s => s.Take(3)).First();
                                #region 开始跟据AGV状态做出处理
                                //巷道分配
                                if (agvInfo.AgvStatus == AGVTaskStatus.RequestOrPermission1 && agvInfo.Status != AGVTaskStatus.Complete1)
                                {

                                    //找到对应WCS任务
                                    var task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agvInfo.ID);
                                    if (task == null) throw new Exception($"AGV任务{agvInfo.ID}未找到对应WCS任务");
                                    this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID}开始进行巷道分配");
                                    //向WMS获取巷道优先级'
                                    var res = WmsApi.GetTunnelPriorityList(task.ID);
                                    this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID},WMS返回巷道优先级{res.ResData}");
                                    var tunnelNo = res.ResData.Split(",").Select(v => "SRM" + v).ToList();

                                    //开始获取堆垛机与可用站台信息
                                    SRM srm = null;
                                    List<Station> stations = new List<Station>();
                                    if (task.Floor == 1) //一楼
                                    {
                                        //一楼三个入库口 新增一个巷道，两个入库口
                                        stations = devs.Where(v => v.Entity.Code is "1011" or "1013" or "1015" or "1117" or "1138").ToList();

                                        //过滤有任务的站台
                                        var taskinstations = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => v.TaskType == AGVTaskType.EnterDepot && v.Status < AGVTaskStatus.MissionCompleted && (v.Position == "1011" || v.Position == "1013" || v.Position == "1015" || v.Position == "1117" || v.Position == "1138")).SplitTable(v => v.Take(2)).Select(v => v.Position).ToList();
                                        stations = stations.Where(p => !taskinstations.Contains(p.Entity.Code)).ToList();

                                        //筛选出可用站台
                                        stations = stations.Where(v => v.Data.VoucherNo == v.Data2.VoucherNo && v.Data3.Status.HasFlag(StatusEunm.Auto))
                                                           .Where(v => !v.Data3.Status.HasFlag(StatusEunm.PH_Status) && !v.Data3.Status.HasFlag(StatusEunm.OT_Status))
                                                           .Where(v => !v.Data3.Status.HasFlag(StatusEunm.Run)).ToList(); // 筛选出可用站台

                                        //var putS = stations.Select(v => v.Entity.Code);
                                        var dev = devs.Find(v => v.Entity.Code == "1138");
                                        World.Log($"放货站台1138信号凭证号{dev.Data.VoucherNo}-{dev.Data2.VoucherNo}-自动{dev.Data3.Status.HasFlag(StatusEunm.Auto)}-光电{dev.Data3.Status.HasFlag(StatusEunm.PH_Status)}-有货光电{dev.Data3.Status.HasFlag(StatusEunm.OT_Status)}-{dev.Data3.Status.HasFlag(StatusEunm.Run)}");
                                        //World.Log($"可用放货站台{JsonConvert.SerializeObject(putS)}");
                                        this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID},可用放货站台", stations.Select(v => v.Entity.Code).ToList());
                                        //可用堆垛机
                                        srm = stations.Select(v => v.Entity.Sources).SelectMany(v => v).Where(v => v.IsTunnel()) //上一个地址是巷道的
                                                      .Select(v => v.Sources).SelectMany(v => v).Where(v => v.HasProtocol(typeof(ISRM520))) //筛选出堆垛机
                                                      .Select(v => new SRM(v, this.World)) //转换为SRM
                                                      .Where(v => v != null && !v.Data2.Status.HasFlag(SrmStatus.Alarm) && v.Data2.AutoStatus == SrmAutoStatus.Automatic) //筛选出可用堆垛机
                                                      .Where(v => tunnelNo.Contains(v.Entity.Code)) //筛选出巷道优先级最高的堆垛机
                                                      .MinBy(v => tunnelNo.IndexOf(v.Entity.Code));//按照巷道优先级排序

                                     
                                    }
                                    else //二楼
                                    {
                                        //二楼三个入库口 新增一个巷道，1个入库口
                                        stations = devs.Where(v => v.Entity.Code is "1021" or "1023" or "1025" or "1127").ToList();
                                        //过滤有任务的站台
                                        var taskinstations = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => v.TaskType == AGVTaskType.EnterDepot && v.Status < AGVTaskStatus.MissionCompleted && (v.Position == "1021" || v.Position == "1023" || v.Position == "1025" || v.Position == "1127")).SplitTable(v => v.Take(2)).Select(v => v.Position).ToList();
                                        stations = stations.Where(p => !taskinstations.Contains(p.Entity.Code)).ToList();

                                        //筛选出可用站台
                                        stations = stations.Where(v => v.Data.VoucherNo == v.Data2.VoucherNo && v.Data3.Status.HasFlag(StatusEunm.Auto))
                                                           .Where(v => !v.Data3.Status.HasFlag(StatusEunm.PH_Status) && !v.Data3.Status.HasFlag(StatusEunm.OT_Status))
                                                           .Where(v => !v.Data3.Status.HasFlag(StatusEunm.Run)).ToList(); // 筛选出可用站台
                                        //var putS1 = stations.Select(v => v.Entity.Code);
                                        var dev = devs.Find(v => v.Entity.Code == "1127");
                                        World.Log($"放货站台1127信号凭证号{dev.Data.VoucherNo}-{dev.Data2.VoucherNo}-自动{dev.Data3.Status.HasFlag(StatusEunm.Auto)}-光电{dev.Data3.Status.HasFlag(StatusEunm.PH_Status)}-有货光电{dev.Data3.Status.HasFlag(StatusEunm.OT_Status)}-{dev.Data3.Status.HasFlag(StatusEunm.Run)}");



                                        this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID},可用放货站台", stations.Select(v => v.Entity.Code).ToList());
                                        //可用堆垛机
                                        srm = stations.Select(v => v.Entity.Sources).SelectMany(v => v).Where(v => v.IsTunnel()) //上一个地址是巷道的
                                                      .Select(v => v.Sources).SelectMany(v => v).Where(v => v.HasProtocol(typeof(ISRM520))) //筛选出堆垛机
                                                      .Select(v => new SRM(v, this.World)) //转换为SRM
                                                      .Where(v => v != null && !v.Data2.Status.HasFlag(SrmStatus.Alarm) && v.Data2.AutoStatus == SrmAutoStatus.Automatic) //筛选出可用堆垛机
                                                      .Where(v => tunnelNo.Contains(v.Entity.Code)) //筛选出巷道优先级最高的堆垛机
                                                      .MinBy(v => tunnelNo.IndexOf(v.Entity.Code));//按照巷道优先级排序

                                    }
                                    if (srm == null) throw new Exception($"agv任务{agvInfo.ID}无可用堆垛机");

                                    //筛选出堆垛机的放货站台
                                    var nextPos = stations.FirstOrDefault(v => v.Entity.Sources.Where(t => t.IsTunnel()).Select(t => t.Sources).SelectMany(v => v) //获取所有巷道
                                                                                               .Where(t => t.HasProtocol(typeof(ISRM520)))//筛选出堆垛机
                                                                                               .SelectMany(v => v.Sources).Any(t => t.Code == srm.Entity.Parent.Code));
                                    this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID},放货站台{nextPos}");

                                    bool flag = false;
                                    //if (((task.BusType == "二楼湿拉线退料回立库" || task.BusType == "二楼湿拉线余料回立库") && task.Floor == 2))
                                    //{
                                    //    flag = true;
                                    //    nextPos.Entity.Code = "1025";
                                    //}
                                    var agvs = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => v.Status < AGVTaskStatus.MissionCompleted && v.Position == nextPos.Entity.Code).SplitTable(v => v.Take(2)).ToList();
                                    if (agvs.Any())
                                    {
                                        var msg = "已无可用放货站台,任务正在执行中:";
                                        foreach (var ag in agvs)
                                        {
                                            msg = msg + $"[任务号:{ag.ID},目标地址:{ag.Position}]";
                                        }
                                        throw new Exception(msg);
                                    }
                                    //wcs任务状态卡控，防止因光电异常误判                                   
                                    if (db.Default.Queryable<WCS_TaskInfo>().Any(v => v.AddrNext == nextPos.Entity.Code && v.Status == Entity.TaskStatus.ConveyorExecution)) return;


                                    if (RedisHub.Default.Get("TaskTun:" + task.ID) != null && RedisHub.Default.Get("TaskTun:" + task.ID) != nextPos.Entity.Code)
                                    {
                                        throw new Exception("WCS任务：" + task.ID + "已经分配过巷道，不允许重新分配不同巷道");
                                    }


                                    //更新AGV任务状态
                                    agvInfo.Status = AGVTaskStatus.Complete1;
                                    //agv.Position = flag == true ? "1025" : nextPos.Entity.Code;
                                    agvInfo.Position = nextPos.Entity.Code;
                                    var upres1 = db.Default.Updateable(agvInfo).SplitTable(x => x.Take(2)).ExecuteCommand();
                                    //更新WCS任务状态
                                    //if (flag)
                                    //{
                                    //    srm.Entity.Code = "SRM3";
                                    //    task.Device = srm.Entity.Code;
                                    //    task.Tunnel = "3";
                                    //    task.AddrNext = "1025";
                                    //    task.SrmStation = "1025";
                                    //}
                                    //else
                                    {
                                        task.Device = srm.Entity.Code;
                                        task.Tunnel = task.Device.GetLastDigit().ToString();
                                        task.AddrNext = agvInfo.Position;
                                        task.SrmStation = nextPos.Entity.Code;
                                    }
                                    var upres =  db.Default.Updateable(task).ExecuteCommand();
                                    task.AddWCS_TASK_DTL(db, "AGV巷道分配点", nextPos.Entity.Code, $"任务分配至堆垛机:{srm.Entity.Code}");
                                    this.ExRecord(obj.Entity.Code, $"AGV任务{agvInfo.ID}分配至堆垛机:{srm.Entity.Code}");


                                    if (upres > 0 && upres1 > 0)
                                    {
                                        //调继续执行任务接口(监控发现海康接口有不响应的情况，会导致事务不执行,把接口调用拿到事务外面)
                                        //AgvApi.ContinueTask(agvInfo.AgvID, nextPos.Entity.Code);
                                        isApplyContainue = 1;
                                        agvid = agvInfo.AgvID;
                                        nextpos = nextPos.Entity.Code;
                                        RedisHub.Default.Set("TaskTun:" + task.ID, nextPos.Entity.Code, 600);
                                    }

                                }
                                //放货站点安全交互
                                else if (agvInfo.AgvStatus == AGVTaskStatus.RequestOrPermission2 && agvInfo.Status != AGVTaskStatus.Complete2)
                                {
                                    //找到对应WCS任务
                                    var task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agvInfo.ID);
                                    if (task == null) throw new Exception($"AGV任务{agvInfo.ID}未找到对应WCS任务");

                                    if (agvInfo.Position.IsNullOrEmpty()) throw new Exception($"无有效放货地址");

                                    if (db.Default.Queryable<WCS_TaskInfo>().Any(v => v.AddrNext == agvInfo.Position && v.Status == Entity.TaskStatus.ConveyorExecution)) throw new Exception($"AGV请求放货，但{agvInfo.Position}上任务状态异常"); ;
                                    var dev = devs.Find(v => v.Entity.Code == agvInfo.Position);

                                    if (dev.Data.VoucherNo != dev.Data2.VoucherNo) throw new Exception($"AGV请求放货，但{dev.Entity.Code}凭证号不一致");
                                    if (!dev.Data3.Status.HasFlag(StatusEunm.Auto)) throw new Exception($"AGV请求放货，但{dev.Entity.Code}不在自动状态");
                                    if (dev.Data3.Status.HasFlag(StatusEunm.PH_Status)) throw new Exception($"AGV请求放货，但{dev.Entity.Code}光电有货");
                                    if (dev.Data3.Status.HasFlag(StatusEunm.OT_Status)) throw new Exception($"AGV请求放货，但{dev.Entity.Code}任务有货");
                                    if (dev.Data3.Status.HasFlag(StatusEunm.Run)) throw new Exception($"AGV请求放货，但{dev.Entity.Code}在运行状态");
                                    agvInfo.Status = AGVTaskStatus.Complete2;
                                    db.Default.Updateable(agvInfo).SplitTable(x => x.Take(2)).ExecuteCommand();

                                    dev.Data.TaskNumber = task.ID;
                                    World.Log($"agvRequestOrPermission2:taskid[{dev.Data.TaskNumber}]", LogLevelEnum.Mid);
                                    //调继续执行任务接口
                                    AgvApi.ContinueTask(agvInfo.AgvID, dev.Entity.Code);
                                }
                                //完成任务
                                else if (agvInfo.AgvStatus == AGVTaskStatus.MissionCompleted && agvInfo.Status != AGVTaskStatus.MissionCompleted)
                                {
                                    agvInfo.Status = AGVTaskStatus.MissionCompleted;
                                    db.Default.Updateable(agvInfo).SplitTable(x => x.Take(2)).ExecuteCommand();
                                }

                                #endregion 开始跟据AGV状态做出处理
                            });
                            if (isApplyContainue > 0)
                            {
                                SqlSugarHelper.Do(db =>
                                {
                                    var agvInfo = db.Default.Queryable<WCS_AgvTaskInfo>().Where(x => x.AgvID == agvid).SplitTable(s => s.Take(2)).First();
                                    if (agvInfo.Status == AGVTaskStatus.Complete1)
                                    {
                                        AgvApi.ContinueTask(agvid, nextpos);
                                    }
                                });
                                //AgvApi.ContinueTask(agvid, nextpos);
                            }
                        }
                        catch (Exception ex)
                        {
                            World.Log(ex.Message, LogLevelEnum.Mid);
                            this.ExRecord(obj.Entity.Code, ex.Message);
                            continue;
                        }
                    }
                    World.Log($"agv任务处理:结束[{guid}]", LogLevelEnum.Mid);
                }
            }
        }

        public override bool Select(Device dev)
        {
            return dev.Code is "1011" or "1012";
        }
    }
}
