using Castle.Core.Internal;
using Newtonsoft.Json;
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.BCR;
using WCS.Entity.Protocol.Station;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.Worlds;
using TaskStatus = WCS.Entity.TaskStatus;

namespace WCS.WorkEngineering.Systems
{
    /// <summary>
    ///  满轮主线预写入目标地址
    /// </summary>
    [BelongTo(typeof(SortingMainLineWorld))]
    [Description("满轮主线预写入目标地址")]
    public class 满轮主线预写入目标地址 : DeviceSystem<Device<IStation523, IBCR83, IStation525>>
    {
        protected override bool ParallelDo => true;

        protected override bool SaveLogsToFile => true;

        public override void Do(Device<IStation523, IBCR83, IStation525> obj)
        {
            //待处理条码组
            var pendingBcrList = obj.Data2.GetBcrCodeList().Where(x => !x.IsNullOrEmpty());
            //缓存条码组
            var cacheBcrList = obj.Data3.GetBcrCodeList();
            var codes = pendingBcrList.Where(x => !cacheBcrList.Contains(x));
            World.Log($"预分配点:{JsonConvert.SerializeObject(cacheBcrList)}");
            //循环处理所有缓存条码组中没有的条码
            foreach (var bcrCode in codes)
            {
                //取出预分配地址，并计算相关信息
                var key = $"AllocationWarehouseSort:{bcrCode}";
                var value = RedisHub.WMS.Get(key);
                if (value == null)
                {
                    World.Log($"{bcrCode}:找不到分库记录", LogLevelEnum.High);
                    continue;
                }
                var mainlineDiversion = JsonConvert.DeserializeObject<MainlineDiversion>(value);
                var srmCode = mainlineDiversion.WarehouseCode.WarehouseToSrm();
                var next = DevicePath.GetPath(obj.Entity.Code, srmCode).Points[1].Code;

                //开始检查任务信息
                var db = new SqlSugarHelper();
                var task = db.Default.Queryable<WCS_TaskInfo>().Single(x => x.BarCode == bcrCode && x.ID == mainlineDiversion.TaskId && x.Status == TaskStatus.NewBuild);
                if (task == null)
                {
                    World.Log($"{bcrCode}-{mainlineDiversion}:找不到匹配任务", LogLevelEnum.High);
                    continue;
                }

                try
                {
                    db.Connect.BeginTran();
                    task.Status = TaskStatus.WaitingToExecute;
                    task.EditWho = "WCS";
                    task.EditTime = DateTime.Now;
                    db.Default.Updateable(task).ExecuteCommand();
                    task.AddWCS_TASK_DTL(db.Default, obj.Entity.Code, next.ToString(), "任务完成预分流");
                    db.Connect.CommitTran();
                }
                catch (Exception e)
                {
                    db.Connect.RollbackTran();
                    World.Log($"{bcrCode}-{mainlineDiversion}:----{e.Message}", LogLevelEnum.High);
                    continue;
                }

                //开始赋值
                obj.Data3.GetType().GetProperty($"BcrCode{obj.Data3.NextIndex}").SetValue(obj.Data3, bcrCode);
                obj.Data3.GetType().GetProperty($"TaskNumber{obj.Data3.NextIndex}").SetValue(obj.Data3, task.ID);
                obj.Data3.GetType().GetProperty($"GoodsEnd{obj.Data3.NextIndex}").SetValue(obj.Data3, next.ToShort());
                if (obj.Data3.NextIndex >= 49)
                {
                    obj.Data3.NextIndex = 0;
                }
                else
                {
                    obj.Data3.NextIndex++;
                }
            }

            World.Log($"预分配信息:{JsonConvert.SerializeObject(obj.Data3.GetBcrCodeList())}");
        }

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

    /// <summary>
    ///  主线分流
    /// </summary>
    public class MainlineDiversion
    {
        /// <summary>
        ///  任务号
        /// </summary>
        public int TaskId { get; set; }

        /// <summary>
        ///  仓库号
        /// </summary>
        public string WarehouseCode { get; set; }
    }
}
