using ServiceCenter.Extensions;
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 WCS.WorkEngineering.Worlds.Logs;
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()
        {
            devs = Device.All.Where(v => v.HasFlag(DeviceFlags.入库, DeviceFlags.巷道口)).Select(v => new Station(v, this.World)).ToList();
            srms = Device.All.Where(v => v.HasProtocol(typeof(ISRM520))).Select(v => new SRM(v, this.World)).ToList();
        }

        public override void Do(Station obj)
        {
            if (obj.Entity.HasFlag(DeviceFlags.出库))
            {
                SqlSugarHelper.Do(db =>
                {
                    //获取所有未结束的AGV任务
                    var agvTaks = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => (v.TaskType == AGVTaskType.CallMaterial || v.TaskType == AGVTaskType.CallForMaterial) && v.Status < AGVTaskStatus.MissionCompleted && v.Status > AGVTaskStatus.NewBuild).SplitTable(tabs => tabs.Take(2)).ToList();

                    foreach (var agv in agvTaks)
                    {
                        switch (agv.Status)
                        {
                            case AGVTaskStatus.RequestOrPermission2:
                                //调继续执行任务接口
                                var res = AgvApi.ContinueTask(agv.AgvID, agv.Station);
                                agv.Status = AGVTaskStatus.Complete2;

                                break;
                        }

                        db.Default.Updateable(agv).SplitTable().ExecuteCommand();
                    }

                    db.Default.SaveQueues();
                });
            }
            else if (obj.Entity.HasFlag(DeviceFlags.入库))
            {
                SqlSugarHelper.Do(db =>
                {
                    //获取所有未结束的AGV任务
                    var agvTaks = db.Default.Queryable<WCS_AgvTaskInfo>().Where(v => v.Status < AGVTaskStatus.MissionCompleted && v.TaskType == AGVTaskType.EnterDepot).SplitTable(tabs => tabs.Take(2)).ToList().OrderBy(v => v.EditTime);

                    foreach (var agv in agvTaks)
                    {
                        var task = db.Default.Queryable<WCS_TaskInfo>().First(v => v.AgvTaskID == agv.ID);
                        switch (agv.Status)
                        {
                            case AGVTaskStatus.RequestOrPermission1: //获取巷道
                                var res = WmsApi.GetTunnelPriorityList(task.ID);
                                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").ToList();

                                    //筛选出可用站台
                                    stations = stations.Where(v => v.Data.VoucherNo == v.Data2.VoucherNo
                                                                && v.Data3.Status.HasFlag(StatusEunm.Auto)
                                                                && !v.Data3.Status.HasFlag(StatusEunm.PH_Status)
                                                                && !v.Data3.Status.HasFlag(StatusEunm.OT_Status)
                                                                && !v.Data3.Status.HasFlag(StatusEunm.Run)).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))
                                                         .Where(v => !v.Data2.Status.HasFlag(SrmStatus.Alarm) && v.Data2.RunStatus == SrmRunStatus.Idle && v.Data2.AutoStatus == SrmAutoStatus.Automatic)
                                                         .MinBy(v => tunnelNo.IndexOf(v.Entity.Code));
                                }
                                else //二楼
                                {
                                }
                                if (srm == null)
                                {
                                    World.Log("无可用堆垛机", LogLevelEnum.Mid);
                                    continue;
                                };

                                task.Device = srm.Entity.Code;
                                task.Tunnel = task.Device.GetLastDigit().ToString();
                                agv.Status = AGVTaskStatus.Complete1;

                                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));
                                agv.Position = nextPos.Entity.Code;
                                task.AddWCS_TASK_DTL(db, "AGV巷道分配点", nextPos.Entity.Code, $"任务分配至堆垛机:{srm.Entity.Code}");
                                db.Default.Updateable(task).ExecuteCommand();
                                //调继续执行任务接口
                                AgvApi.ContinueTask(agv.AgvID, nextPos.Entity.Code);
                                break;

                            case AGVTaskStatus.RequestOrPermission2: //安全交互
                                var dev = devs.Find(v => v.Entity.Code == agv.Position);
                                if (dev.Data.VoucherNo != dev.Data2.VoucherNo)
                                {
                                    World.Log($"AGV请求放货，但{obj.Entity.Code}凭证号不一致", LogLevelEnum.Mid);
                                    continue;
                                }
                                if (!dev.Data3.Status.HasFlag(StatusEunm.Auto))
                                {
                                    World.Log($"AGV请求放货，但{obj.Entity.Code}不在自动状态", LogLevelEnum.Mid);
                                    continue;
                                }
                                if (dev.Data3.Status.HasFlag(StatusEunm.PH_Status))
                                {
                                    World.Log($"AGV请求放货，但{obj.Entity.Code}光电有货", LogLevelEnum.Mid);
                                    continue;
                                }
                                if (dev.Data3.Status.HasFlag(StatusEunm.OT_Status))
                                {
                                    World.Log($"AGV请求放货，但{obj.Entity.Code}任务有货", LogLevelEnum.Mid);
                                    continue;
                                }
                                if (dev.Data3.Status.HasFlag(StatusEunm.Run))
                                {
                                    World.Log($"AGV请求放货，但{obj.Entity.Code}在运行状态", LogLevelEnum.Mid);
                                    continue;
                                }
                                //调继续执行任务接口
                                AgvApi.ContinueTask(agv.AgvID, dev.Entity.Code);
                                agv.Status = AGVTaskStatus.Complete2;
                                break;

                            case AGVTaskStatus.MissionCompleted:
                                break;
                        }

                        db.Default.Updateable(agv).SplitTable().ExecuteCommand();
                    }
                });
            }
        }

        public override bool Select(Device dev)
        {
            //return dev.HasFlag(DeviceFlags.巷道口);
            return dev.Code is "1011" or "1012";
        }
    }
}
