using ServiceCenter.Logs;
using ServiceCenter.SqlSugars;
using System.ComponentModel;
using WCS.Core;
using WCS.Entity;
using WCS.Entity.Protocol.BCR;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.Worlds;
using DeviceFlags = WCS.WorkEngineering.Extensions.DeviceFlags;
using TaskStatus = WCS.Entity.TaskStatus;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  一楼入库工位处理系统
    /// </summary>
    [BelongTo(typeof(MainWorld))]
    [Description("一楼入库工位处理系统")]
    public class 一楼入库工位处理系统 : DeviceSystem<Station>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        private List<BCR> BCRS = new List<BCR>();

        public 一楼入库工位处理系统()
        {
            BCRS = Device.All.Where(v => v.HasProtocol<IBCR81>()).Select(v => new BCR(v, World)).ToList();
        }

        public override void Do(Station obj)
        {
            obj.入库站点是否被禁止();
            obj.入库站点是否满足执行条件();

            WCS_TaskInfo task = null;//处理完成的任务
            try
            {
                SqlSugarHelper.Do(_db =>
                {
                    var db = _db.Default;
                    WCS_TaskInfo taskInfo = null;
                    if (!obj.Data3.Status.HasFlag(StatusEunm.PH_Status) && obj.Data2.Request == 0) return;
                    //判断是否有空轮初始化任务
                    if (db.Queryable<WCS_TaskInfo>().Count(v => v.Type == TaskType.EmptyInit && v.Status == TaskStatus.WaitingToExecute && v.SrmStation == obj.Entity.Code) > 1)
                    {
                        throw new KnownException($"{obj.Entity.Code}站台存在多个空轮初始化入库任务,请取消RFID不是站台实物的任务", LogLevelEnum.Mid);
                    }
                    taskInfo = db.Queryable<WCS_TaskInfo>().First(v => v.Type == TaskType.EmptyInit && v.Status == TaskStatus.WaitingToExecute && v.SrmStation == obj.Entity.Code);

                    string barcode = "";
                    //manlun
                    if (taskInfo == null)
                    {
                        //获取RFID
                        barcode = BCRS.GetBCRCode(obj.Entity.Code);
                        //跟据RFID获取对应的任务
                        taskInfo = db.Queryable<WCS_TaskInfo>().First(v => v.BarCode == barcode) ?? throw new KnownException($"未找到RFID:{barcode}对应WCS任务,请检查扫码是否异常", LogLevelEnum.Mid);
                        if (taskInfo.Status != Entity.TaskStatus.AGVExecution)
                        {
                            if (db.Queryable<WCS_TaskDtl>().SplitTable(v => v.Take(2)).Any(v => v.ParentTaskCode == taskInfo.ID && v.Desc.Contains("等待分配货位后堆垛机进行取货"))) return;
                            else throw new KnownException($"任务:{taskInfo.ID}不是AGV执行状态，请检查异常原因", LogLevelEnum.High);
                        }

                        if (!obj.Data3.Status.HasFlag(StatusEunm.ManualStorage)) //不是手动入库
                        {
                            //判断AGV任务目标地址是否是当前地址
                            var agv = db.Queryable<WCS_AgvTaskInfo>().SplitTable(v => v.Take(2)).First(v => v.ID == taskInfo.AgvTaskID) ?? throw new KnownException($"任务{taskInfo.ID}未找到对应AGV任务", LogLevelEnum.Mid);
                            if (taskInfo.AddrNext != obj.Entity.Code) throw new KnownException($"任务{taskInfo.ID}不是货架上的任务，请检查RFID是否正确", LogLevelEnum.Mid);
                            if (agv.Position != obj.Entity.Code) throw new KnownException($"任务{taskInfo.ID}对应AGV任务目标地址不是当前站台", LogLevelEnum.Mid);
                        }
                        //获取称重
                        var dev91 = Device.All.Where(v => v.Code == obj.Entity.Code).Select(v => new Device<IStation91>(v, this.World)).FirstOrDefault();

                        //if (obj.Entity.Code != "1117")
                        //{
                            taskInfo.Weight = dev91.Data.Weight;
                        //}
                        //else
                        //{
                        //    taskInfo.Weight = 800;
                        //}

                        
                        if (taskInfo.Weight < 130) throw new KnownException($"称重结果错误:{taskInfo.Weight}", LogLevelEnum.Mid);
                        //上抛重量
                        try { WmsApi.WcsUploadInfo(taskInfo.ID, (decimal)taskInfo.Weight, taskInfo.BarCode); } catch (Exception ex) { World.Log(ex.Message, LogLevelEnum.Mid); }
                    }
                    else//空轮初始化任务
                    {
                        //获取称重
                        var dev91 = Device.All.Where(v => v.Code == obj.Entity.Code).Select(v => new Device<IStation91>(v, this.World)).FirstOrDefault();

                        //if (obj.Entity.Code != "1117")
                        //{
                            taskInfo.Weight = dev91.Data.Weight;
                        //}
                        //else
                        //{
                        //    taskInfo.Weight = 200;
                        //}
                        //taskInfo.Weight = dev91.Data.Weight;
                        if (taskInfo.Weight < 140) throw new KnownException($"称重结果错误:{taskInfo.Weight}", LogLevelEnum.Mid);
                        //上抛重量
                        try { WmsApi.WcsUploadInfo(taskInfo.ID, (decimal)taskInfo.Weight, taskInfo.BarCode); } catch (Exception ex) { World.Log(ex.Message, LogLevelEnum.Mid); }
                    }
                    

                    taskInfo.Status = Entity.TaskStatus.ConveyorExecution;
                    db.Updateable(taskInfo).ExecuteCommand();
                    taskInfo.AddWCS_TASK_DTL(_db, obj.Entity.Code, "SRM", $"状态更新为{Entity.TaskStatus.ConveyorExecution},等待分配货位后堆垛机进行取货");
                    task = taskInfo;
                });
            }
            catch (Exception ex)
            {
                throw new KnownException(ex.Message, LogLevelEnum.High);
            }
            if (task == null) return;
            obj.Data.TaskNumber = task.ID;
            obj.Data.VoucherNo++;
        }

        public override bool Select(Device dev)
        {
            return dev.HasFlag(DeviceFlags.一楼入库口);
        }
    }
}
