using PlcSiemens.Core.Extension;
using ServiceCenter.Redis;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
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;
using WCS.WorkEngineering.Worlds.Logs;

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
                {
                    SqlSugarHelper.Do(db =>
                    {
                        var tasks = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.Status == Entity.TaskStatus.NewBuild).ToList();
                        if (!tasks.Any()) return;
                        tasks.ForEach(task =>
                        {
                            switch (task.Type)
                            {
                                case TaskType.SetPlate:
                                    break;

                                case TaskType.EnterDepot:
                                    //创建AGV任务
                                    var agvTask = new WCS_AgvTaskInfo()
                                    {
                                        ID = db.GetAGVTaskId(),
                                        TaskType = AGVTaskType.EnterDepot,
                                        Status = AGVTaskStatus.NewBuild,
                                        Station = task.WorkBench,
                                        AddWho = "WCS"
                                    };
                                    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任务中间表");
                                    break;

                                case TaskType.OutDepot:
                                    if (task.Floor == 2)
                                    {  //创建AGV任务
                                        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;
                                    }
                                    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}");
                                    break;

                                case TaskType.TransferDepot:
                                    break;

                                case 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任务");
                                    break;

                                case TaskType.EmptyInit:
                                    //更新任务状态
                                    task.Status = Entity.TaskStatus.WaitingToExecute;
                                    db.Default.Updateable(task).ExecuteCommand();
                                    task.AddWCS_TASK_DTL(db, task.Device, $"初始化任务信息");
                                    break;

                                default:
                                    break;
                            }
                        });
                    });
                }
                catch (Exception ex)
                {
                    World.Log(ex.Message, Worlds.Logs.LogLevelEnum.Mid);
                }

                #endregion 处理所有的新增任务

                #region 下发入库AGV任务

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

                    if (agvTasks.Count > 0)
                    {
                        foreach (var agv in agvTasks)
                        {
                            //开始处理
                            try
                            {
                                //获取对应wcs任务
                                var wcs = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.AgvTaskID == agv.ID && t.Status == Entity.TaskStatus.WaitingToExecute).First();

                                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().ExecuteCommand();
                                        break;

                                    case 2:
                                        var agvRes = IwmsApi.空轮回库(wcs.MatCode, wcs.SrmStation, wcs.IsSurplus, wcs.IsRework, agv.ID, wcs.BarCode);
                                        agv.Status = AGVTaskStatus.Confirm;
                                        agv.AgvID = agvRes.data;
                                        db.Default.Updateable(agv).SplitTable().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, Worlds.Logs.LogLevelEnum.Mid);
                                continue;
                            }
                        }
                    }
                });

                #endregion 下发入库AGV任务

                #region 移动任务处理

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

                        if (agvTasks.Count > 0)
                        {
                            foreach (var agv in agvTasks)
                            {
                                //开始处理
                                GenAgvSchedulingTaskResponse res = new GenAgvSchedulingTaskResponse();
                                try
                                {
                                    //获取对应wcs任务
                                    var wcs = db.Default.Queryable<WCS_TaskInfo>().Where(t => t.AgvTaskID == agv.ID && t.Status == Entity.TaskStatus.WaitingToExecute).First();
                                    //下发AGV任务
                                    res = AgvApi.机台补空(agv.Station, Guid.NewGuid().ToString().Replace("-", ""), "1");
                                    agv.Status = AGVTaskStatus.Confirm;
                                    agv.AgvID = res.data;
                                    db.Default.Updateable(agv).SplitTable().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, Worlds.Logs.LogLevelEnum.Mid);
                                    continue;
                                }
                            }
                        }
                    });
                }
                catch { }

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

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