using PlcSiemens.Core.Extension;
using ServiceCenter.Logs;
using ServiceCenter.Redis;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using System.Threading.Tasks;
using WCS.Core;
using WCS.Entity;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.WebApi.Models.AGV.Response;
using WCS.WorkEngineering.Worlds;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  无交互系统
    /// </summary>
    [BelongTo(typeof(NoInteractionWorld))]
    [Description("无交互系统")]
    public class NoInteractionSystems : DeviceSystem<Station>
    {
        public NoInteractionSystems()
        {
        }

        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Station obj)
        {
            var key = $"WCS:Lock:无交互系统{obj.Entity.Code}";
            try
            {
                if (RedisHub.Default.Get(key) != null)
                {
                    throw new KnownException($"[{obj.Entity.Code}]--触发并发管控", LogLevelEnum.High);
                }
                RedisHub.Default.Set(key, obj.Entity.Code);

                #region 处理所有的新增任务

                try
                {
                    List<WCS_TaskInfo> taskInfos = new List<WCS_TaskInfo>();
                    SqlSugarHelper.Do(db =>
                    {
                        taskInfos = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.Status == Entity.TaskStatus.NewBuild).ToList();
                    });
                    if (taskInfos.Any())
                    {
                        foreach (var item in taskInfos)
                        {
                            try
                            {
                                SqlSugarHelper.Do(db =>
                                {
                                    var task = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.ID == item.ID).First() ?? throw new Exception($"未找到对应的WCS任务[{item.ID}]");
                                    if (task.Type == TaskType.EnterDepot)
                                    {
                                        //创建AGV任务
                                        var agvTask = new WCS_AgvTaskInfo()
                                        {
                                            ID = db.GetAGVTaskId(),
                                            TaskType = AGVTaskType.EnterDepot,
                                            Status = AGVTaskStatus.NewBuild,
                                            Station = task.WorkBench,
                                            AddWho = "WCS",
                                            //Position = task.SrmStation
                                        };
                                        if (task.Floor == 2)
                                        {
                                            //task.Tunnel = "3";
                                            task.Tunnel = "";
                                            task.Device = "SRM3";
                                            task.SrmStation = "1025";
                                        }
                                        db.Default.Insertable(agvTask).SplitTable().ExecuteCommand();
                                        //更新任务状态
                                        task.Status = Entity.TaskStatus.WaitingToExecute;
                                        task.AgvTaskID = agvTask.ID;
                                        db.Default.Updateable(task).ExecuteCommand();
                                        task.AddWCS_TASK_DTL(db, task.Device, $"初始化入库任务信息,并创建AGV任务中间表,AGV任务目标地址:{agvTask.Position}");
                                    }
                                    else if (task.Type == TaskType.OutDepot)
                                    {
                                        #region 二楼非半自动手动出库任务需要创建AGV任务

                                        if (task.Floor == 2 && task.OutType != OutTypeEnum.半自动手动出库任务)
                                        {
                                            //创建AGV任务
                                            var agvTask = new WCS_AgvTaskInfo()
                                            {
                                                ID = db.GetAGVTaskId(),
                                                TaskType = AGVTaskType.CallMaterial,
                                                Status = AGVTaskStatus.NewBuild,
                                                Station = task.WorkBench,
                                                AddWho = "WCS"
                                            };
                                            db.Default.Insertable(agvTask).SplitTable().ExecuteCommand();
                                            task.AgvTaskID = agvTask.ID;
                                        }
                                        else if (task.Floor == 1 && task.BusType == "一楼出满轮")
                                        {
                                            //创建AGV任务
                                            var agvTask = new WCS_AgvTaskInfo()
                                            {
                                                ID = db.GetAGVTaskId(),
                                                TaskType = AGVTaskType.CallMaterial,
                                                Status = AGVTaskStatus.NewBuild,
                                                Station = task.SrmStation,
                                                Position = task.AddrTo,
                                                WorkShop = 111,
                                                AddWho = "WCS"
                                            };
                                            db.Default.Insertable(agvTask).SplitTable().ExecuteCommand();
                                            task.AgvTaskID = agvTask.ID;
                                        }
                                        else if (task.BusType == "一楼立库出空轮")
                                        {
                                            //创建AGV任务
                                            var agvTask = new WCS_AgvTaskInfo()
                                            {
                                                ID = db.GetAGVTaskId(),
                                                TaskType = AGVTaskType.CallForMaterial,
                                                Status = AGVTaskStatus.NewBuild,
                                                Station = task.SrmStation,
                                                Position = task.AddrTo,
                                                AddWho = "WCS"
                                            };
                                            db.Default.Insertable(agvTask).SplitTable().ExecuteCommand();
                                            task.AgvTaskID = agvTask.ID;
                                        }

                                        #endregion 二楼非半自动手动出库任务需要创建AGV任务

                                        if (task.SrmStation.IsNullOrEmpty()) //如果没有指定放货站台
                                        {
                                            //获取堆垛机到目标地址的路径信息
                                            var path = DevicePath.GetPath(task.Device, task.AddrTo);
                                            task.SrmStation = path.Points[1].Code;
                                        }
                                        //更新任务状态
                                        task.Status = Entity.TaskStatus.WaitingToExecute;
                                        db.Default.Updateable(task).ExecuteCommand();
                                        task.AddWCS_TASK_DTL(db, task.Device, $"初始化出库任务信息,放货站台:{task.SrmStation}");
                                    }
                                    else if (task.Type == TaskType.Delivery) //一楼叉车搬运任务
                                    {
                                        var agv = new WCS_AgvTaskInfo()
                                        {
                                            ID = db.GetAGVTaskId(),
                                            TaskType = AGVTaskType.ForkliftFilling,
                                            Status = AGVTaskStatus.NewBuild,
                                            Station = task.WorkBench,
                                            AddWho = "WCS"
                                        };
                                        db.Default.Insertable(agv).SplitTable().ExecuteCommand();
                                        //更新WCS数据
                                        task.Status = Entity.TaskStatus.WaitingToExecute;
                                        task.AgvTaskID = agv.ID;
                                        db.Default.Updateable(task).ExecuteCommand();
                                        task.AddWCS_TASK_DTL(db, task.Device, $"初始化搬运任务信息,并创建AGV任务");
                                    }
                                    else if (task.Type == TaskType.EmptyInit)
                                    {
                                        //更新任务状态
                                        task.Status = Entity.TaskStatus.WaitingToExecute;
                                        db.Default.Updateable(task).ExecuteCommand();
                                        task.AddWCS_TASK_DTL(db, task.Device, $"初始化任务信息");
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                World.Log(ex.Message, LogLevelEnum.Mid);
                                continue;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    World.Log(ex.Message, LogLevelEnum.Mid);
                }

                #endregion 处理所有的新增任务

                #region 下发入库AGV任务

                List<WCS_AgvTaskInfo> agvTaskInfos = new List<WCS_AgvTaskInfo>();

                SqlSugarHelper.Do(db =>
                {
                    agvTaskInfos = db.Default.Queryable<WCS_AgvTaskInfo>().Where(t => t.Status == AGVTaskStatus.NewBuild && t.TaskType == AGVTaskType.EnterDepot).SplitTable(v => v.Take(2)).ToList();
                });

                if (agvTaskInfos.Any())
                {
                    foreach (var item in agvTaskInfos)
                    {
                        try
                        {
                            SqlSugarHelper.Do(db =>
                            {
                                string barCode = "";
                                var agv = db.Default.Queryable<WCS_AgvTaskInfo>().Where(t => t.ID == item.ID).SplitTable(v => v.Take(2)).First() ?? throw new Exception($"未找到对应的AGV任务:{item.ID}");
                                //获取对应wcs任务
                                var wcs = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.AgvTaskID == agv.ID && t.Status == Entity.TaskStatus.WaitingToExecute).First() ?? throw new Exception($"AGV任务[{item.ID}]未找到对应的WCS任务");                               
                                switch (wcs.Floor)
                                {
                                    case 1: //一楼下发AGV任务
                                        var res = AgvApi.满轮入库(wcs.BarCode, agv.Station, Guid.NewGuid().ToString().Replace("-", ""), "1");
                                        agv.Status = AGVTaskStatus.Confirm;
                                        agv.AgvID = res.data;
                                        db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();
                                        break;

                                    case 2:
                                        barCode = wcs.BarCode;
                                        if (!string.IsNullOrEmpty(wcs.BarCode) && wcs.BarCode.Contains("-"))
                                        {
                                            barCode = wcs.BarCode.Substring(0, wcs.BarCode.IndexOf("-"));
                                        }                                       
                                        var agvRes = IwmsApi.空轮回库(wcs.MatCode, wcs.SrmStation, wcs.IsSurplus, wcs.IsRework, agv.ID, barCode, wcs.AddWho);
                                        agv.Status = AGVTaskStatus.Confirm;
                                        agv.AgvID = agvRes.data;
                                        db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();
                                        break;

                                    default:
                                        break;
                                }

                                //更新WCS数据
                                wcs.Status = Entity.TaskStatus.AGVExecution;
                                db.Default.Updateable(wcs).ExecuteCommand();
                                wcs.AddWCS_TASK_DTL(db, wcs.Device, $"任务下发至AGV-AGV任务ID{agv.AgvID}");
                            });
                        }
                        catch (Exception ex)
                        {
                            World.Log(ex.Message, LogLevelEnum.Mid);
                            continue;
                        }
                    }
                }

                #endregion 下发入库AGV任务

                #region 一楼叉车补空任务处理


                List<WCS_AgvTaskInfo> agvTaskInfos1 = new List<WCS_AgvTaskInfo>();

                SqlSugarHelper.Do(db =>
                {
                    agvTaskInfos1 = db.Default.Queryable<WCS_AgvTaskInfo>().Where(t => t.Status == AGVTaskStatus.NewBuild && t.TaskType == AGVTaskType.ForkliftFilling).SplitTable(v => v.Take(2)).ToList();
                });

                if (agvTaskInfos1.Any())
                {
                    foreach (var item in agvTaskInfos1)
                    {
                        try
                        {
                            GenAgvSchedulingTaskResponse res = new GenAgvSchedulingTaskResponse();
                            SqlSugarHelper.Do(db =>
                            {
                                var agv = db.Default.Queryable<WCS_AgvTaskInfo>().Where(t => t.ID == item.ID).SplitTable(v => v.Take(2)).First() ?? throw new Exception($"未找到对应的AGV任务:{item.ID}");
                                //获取对应wcs任务
                                var wcs = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.AgvTaskID == agv.ID && t.Status == Entity.TaskStatus.WaitingToExecute).First() ?? throw new Exception($"AGV任务[{item.ID}]未找到对应的WCS任务");
                                //下发AGV任务
                                res = AgvApi.机台补空(agv.Station, Guid.NewGuid().ToString().Replace("-", ""), "1");
                                agv.Status = AGVTaskStatus.Confirm;
                                agv.AgvID = res.data;
                                db.Default.Updateable(agv).SplitTable(x => x.Take(2)).ExecuteCommand();

                                wcs.Status = Entity.TaskStatus.AGVExecution;
                                db.Default.Updateable(wcs).ExecuteCommand();
                                wcs.AddWCS_TASK_DTL(db, wcs.Device, $"任务下发至AGV,AGV任务号:{res.data}");
                            });
                        }
                        catch (Exception ex)
                        {
                            World.Log(ex.Message, LogLevelEnum.Mid);
                            continue;
                        }
                    }
                }

                #endregion 移动任务处理
            }
            finally
            {
                RedisHub.Default.Del(key);
            }
        }

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