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.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.Worlds;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;
using TaskStatus = WCS.Entity.TaskStatus;

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

        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Device<IStation520> 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}]");
                                    switch (task.Type)
                                    {
                                        case TaskType.SetPlate:
                                            if (task.AddrFrom != "Robot")
                                            {
                                                //更新任务状态
                                                task.Status = TaskStatus.WaitingToExecute;
                                                db.Default.Updateable(task).ExecuteCommand();
                                                task.AddWCS_TASK_DTL(db.Default, task.Device, $"初始化入库任务信息");
                                            }
                                            break;

                                        case TaskType.EnterDepot:
                                            //更新任务状态
                                            task.Status = Entity.TaskStatus.WaitingToExecute;
                                            switch (task.WarehouseCode)
                                            {
                                                case "1N":
                                                    task.Device = "SRM1";
                                                    break;
                                            }

                                            if (task.AddrFrom is "1666")
                                            {
                                                task.Device = "SRM1";
                                            }

                                            //计算下一个地址
                                            var path1 = DevicePath.GetPath(task.AddrFrom, task.Device);
                                            task.AddrNext = path1.Points[1].Code;
                                            task.SrmStation = task.BarCode is "TPA" or "TPB" ? task.AddrFrom : path1.Points[2].Code;

                                            db.Default.Updateable(task).ExecuteCommand();
                                            task.AddWCS_TASK_DTL(db.Default, task.Device, $"初始化入库任务信息");
                                            break;

                                        case TaskType.OutDepot:
                                            {
                                                if (task.Device.Contains("Robot"))
                                                {
                                                    var pos = task.AddrFrom.Split("-");
                                                    task.Status = Entity.TaskStatus.WaitingToExecute;
                                                    task.Line = pos[0].ToShort();
                                                    task.Col = pos[1].ToShort();
                                                    task.Layer = pos[2].ToShort();
                                                    task.Depth = pos[3].ToShort();
                                                    db.Default.Updateable(task).ExecuteCommand();
                                                    task.AddWCS_TASK_DTL(db.Default, task.Device, $"初始化出库任务信息,放货站台:{task.SrmStation}");
                                                }
                                                else
                                                {
                                                    if (task.SrmStation == "1")
                                                    {
                                                        task.SrmStation = "";
                                                        task.AddrTo = "2534";
                                                        task.Device = "SRM" + task.WarehouseCode.Substring(0, 1);
                                                    }
                                                    if (task.SrmStation.IsNullOrEmpty()) //如果没有指定放货站台
                                                    {
                                                        if (task.Device.IsNullOrEmpty())
                                                        {
                                                            task.Device = "SRM" + task.Tunnel.GetLastDigit();
                                                        }
                                                        //获取堆垛机到目标地址的路径信息
                                                        var path = DevicePath.GetPath(task.Device, task.AddrTo);
                                                        task.SrmStation = path.Points[1].Code;
                                                    }

                                                    var devs = Device.All.Where(x => x.HasFlag(DeviceFlags.AGV取货站台口)).Select(x => x.Code);
                                                    if (devs.Contains(task.SrmStation))
                                                    {
                                                        //开始处理车间叫料AGV任务任务
                                                        db.Default.Insertable(new WCS_AgvTaskInfo()
                                                        {
                                                            ID = db.GetAgvTaskId(),
                                                            TaskType = AGVTaskType.CallMaterial,
                                                            Status = AGVTaskStatus.NewBuild,
                                                            TaskId = task.ID,
                                                            Position = task.WorkBench,
                                                            Station = obj.Entity.Code,
                                                            AddWho = "WCS",
                                                            AddTime = DateTime.Now
                                                        }).SplitTable().ExecuteCommand();

                                                        db.Default.Insertable(new WCS_AgvTaskInfo()
                                                        {
                                                            ID = db.GetAgvTaskId(),
                                                            TaskType = AGVTaskType.EnterDepot,
                                                            Status = AGVTaskStatus.NewBuild,
                                                            TaskId = task.ID,
                                                            Position = task.WorkBench,
                                                            Station = obj.Entity.Code,
                                                            AddWho = "WCS",
                                                            AddTime = DateTime.Now
                                                        }).SplitTable().ExecuteCommand();
                                                    }
                                                    //更新任务状态
                                                    task.Status = Entity.TaskStatus.WaitingToExecute;
                                                    db.Default.Updateable(task).ExecuteCommand();
                                                    task.AddWCS_TASK_DTL(db.Default, task.Device, $"初始化出库任务信息,放货站台:{task.SrmStation}");
                                                }
                                                break;
                                            }
                                        case TaskType.Delivery:
                                            break;

                                        case TaskType.EmptyInit:
                                            break;
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                World.Log(ex.Message, LogLevelEnum.Mid);
                                continue;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    World.Log(ex.Message, LogLevelEnum.Mid);
                }

                #endregion 处理所有的新增任务
            }
            finally
            {
                RedisHub.Default.Del(key);
            }
        }

        public override bool Select(Device dev)
        {
            return dev.Code == nameof(NoInteractionSystems);
        }
    }
}
