using Newtonsoft.Json;
using PlcSiemens.Core.Extension;
using ServiceCenter.Extensions;
using ServiceCenter.Logs;
using ServiceCenter.SqlSugars;
using SqlSugar;
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;

        public override void Do(Device<IStation523, IBCR83, IStation525> obj)
        {
            try
            {
                var devCode = obj.Entity.Code switch
                {
                    "18" => "22",
                    "38" => "41",
                    "58" => "61",
                    "118" => "122",
                    "138" => "141",
                    "158" => "161",
                    _ => throw new ArgumentOutOfRangeException()
                };
                var dev = new Device<IStation520>(Device.All.First(x => x.Code == devCode), World);
                dev.Data.Mode = StationMode.Automatic;
                //从DB83中获取待处理条码组
                var pendingBcrList = obj.Data2.GetBcrCodeList().Where(x => !x.IsNullOrEmpty());
                //从DB525获取已处理条码组
                var cacheBcrList = obj.Data3.GetBcrCodeList();
                //筛选出未处理条码组
                var codes = pendingBcrList.Where(x => !cacheBcrList.Contains(x));
                World.Log($"扫码器:{JsonConvert.SerializeObject(pendingBcrList)}");
                World.Log($"缓存信息:{JsonConvert.SerializeObject(cacheBcrList)}");
                //循环处理所有缓存条码组中没有的条码
                foreach (var bcrCode in codes)
                {
                    WCS_TaskInfo taskInfo = null;
                    fjSysConfig config = new fjSysConfig();
                    SqlSugarHelper.Do(_db =>
                    {
                        var db = _db.Default;
                        var task = db.Queryable<WCS_TaskInfo>().NoLock().First(x => x.BarCode == bcrCode && x.Status == TaskStatus.NewBuild);
                        if (task == null)
                        {
                            World.Log($"{bcrCode}:找不到匹配的任务", LogLevelEnum.High);
                            return;
                        }
                        var config1 = db.Queryable<fjSysConfig>().NoLock().First(x => x.Code == $"{task.WarehouseCode}-Flow");
                        if (config1 == null)
                        {
                            config.Code = "4";
                        }

                        config = config1;
                        taskInfo = task;
                    });
                    if (taskInfo == null)
                    {
                        continue;
                    }
                    var srmCode = taskInfo.WarehouseCode.WarehouseToSrm();
                    var path = DevicePath.GetPath(obj.Entity.Code, srmCode);
                    if (path == null || path is { Points.Count: < 2 })
                    {
                        World.Log($"{bcrCode}:路径错误，当前位置{obj.Entity.Code}，目标位置:{srmCode}", LogLevelEnum.High);
                        continue;
                    }

                    var next = path.Points[1].Code;

                    #region 计算应该去哪个分拣库

                    //应该要去的分拣库

                    if (taskInfo.WarehouseCode.Contains("N"))
                    {
                        next = config.Code switch
                        {
                            "1" => "418",
                            "2" => "818",
                            "3" => "1218",
                            _ => next
                        };
                    }
                    else if (taskInfo.WarehouseCode.Contains("S"))
                    {
                        next = config.Code switch
                        {
                            "1" => "618",
                            "2" => "1018",
                            "3" => "1418",
                            _ => next
                        };
                    }

                    #endregion 计算应该去哪个分拣库

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

                dev.Data.Mode = StationMode.Automatic;
            }
            catch (Exception e)
            {
                World.Log($"{e.Message}:---{e.StackTrace}", LogLevelEnum.High);
            }
        }

        public override bool Select(Device dev)
        {
            var codes = new List<string>();
            if (WorkStart.WareHouses.Contains("FJ1")) codes.AddRange(new List<string>() { "18", "118" });
            if (WorkStart.WareHouses.Contains("FJ2")) codes.AddRange(new List<string>() { "38", "58" });
            if (WorkStart.WareHouses.Contains("FJ3")) codes.AddRange(new List<string>() { "138", "158" });

            return codes.Contains(dev.Code);
            return false;
        }
    }

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

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

    /// <summary>
    ///  配置信息表
    /// </summary>
    [Tenant("fj")]
    [SugarTable("sys_config", "配置信息表")]
    public class fjSysConfig : BaseModel
    {
        /// <summary>
        ///  编号
        /// </summary>
        [SugarColumn(ColumnName = "code", Length = 100)]
        public string Code { get; set; }

        /// <summary>
        ///  名称
        /// </summary>
        [SugarColumn(ColumnName = "name", Length = 100)]
        public string Name { get; set; }

        /// <summary>
        ///  内容
        /// </summary>
        [SugarColumn(ColumnName = "scontent", Length = 100)]
        public string SContent { get; set; }

        /// <summary>
        ///  类型
        /// </summary>
        [SugarColumn(ColumnName = "stype", Length = 50)]
        public string SType { get; set; }

        [SugarColumn(ColumnName = "default1", Length = 100, IsNullable = true)]
        public string Default1 { get; set; }

        [SugarColumn(ColumnName = "default2", Length = 100, IsNullable = true)]
        public string Default2 { get; set; }

        [SugarColumn(ColumnName = "default3", Length = 100, IsNullable = true)]
        public string Default3 { get; set; }
    }

    /// <summary>
    ///  物料表
    /// </summary>
    [Tenant("fj")]
    [SugarTable("Base_MatInfo")]
    public partial class BaseMatinfo : BaseModel
    {
        /// <summary>
        ///  仓库ID
        /// </summary>
        [SugarColumn(ColumnDataType = "bigint", IsNullable = false)]
        public long WarehouseId { get; set; }

        /// <summary>
        ///  编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = false)]
        public string Code { get; set; }

        /// <summary>
        ///  名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 200, IsNullable = false)]
        public string Name { get; set; }

        /// <summary>
        ///  短描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string ShortDesc { get; set; }

        /// <summary>
        ///  长描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 500, IsNullable = true)]
        public string FullDesc { get; set; }

        /// <summary>
        /// 补充描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 500, IsNullable = true)]
        public string ExtDesc { get; set; }

        /// <summary>
        ///  英文名
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string Enname { get; set; }

        /// <summary>
        ///  组ID
        /// </summary>
        [SugarColumn(ColumnDataType = "bigint", IsNullable = false)]
        public long MatGrpId { get; set; }

        /// <summary>
        ///  叶类编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string Leafcode { get; set; }

        /// <summary>
        ///  叶类名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string LeafName { get; set; }

        /// <summary>
        ///  中类编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string MidCode { get; set; }

        /// <summary>
        ///  中类名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string MidName { get; set; }

        /// <summary>
        ///  大类编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string HeadCode { get; set; }

        /// <summary>
        ///  大类名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string HeadName { get; set; }

        /// <summary>
        ///  规格型号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string Description { get; set; }

        /// <summary>
        ///  材质
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string Texture { get; set; }

        /// <summary>
        ///  图号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string FigureNo { get; set; }

        /// <summary>
        ///  强度
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string Strength { get; set; }

        /// <summary>
        ///  镀层
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string Plating { get; set; }

        /// <summary>
        ///  镀层克重
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? PlatingWeight { get; set; }

        /// <summary>
        ///  镀层主元素含量
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? PlatingContQty { get; set; }

        /// <summary>
        ///  线密度
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Linear { get; set; }

        /// <summary>
        ///  产品号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string ProCode { get; set; }

        /// <summary>
        ///  产品描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string ProName { get; set; }

        /// <summary>
        ///  产品强度
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string ProStre { get; set; }

        /// <summary>
        ///  线密度上限
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? LinearMax { get; set; }

        /// <summary>
        ///  线密度下限
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? LinearMin { get; set; }

        /// <summary>
        ///  线密度目标值
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? LinearTar { get; set; }

        /// <summary>
        ///  单丝倍数
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Mono { get; set; }

        /// <summary>
        ///  工字轮型号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string SpoolType { get; set; }

        /// <summary>
        ///  工字轮料号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string SpoolCode { get; set; }

        /// <summary>
        ///  单卷长度
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Length { get; set; }

        /// <summary>
        ///  涂油量
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? OilQty { get; set; }

        /// <summary>
        ///  润滑液种类
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string LubType { get; set; }

        /// <summary>
        ///  排线间距
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? LineSpace { get; set; }

        /// <summary>
        ///  线长度
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? LineLength { get; set; }

        /// <summary>
        ///  捻向
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string LayDirect { get; set; }

        /// <summary>
        ///  客户标准索引号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string CumIndex { get; set; }

        /// <summary>
        ///  有无焊点
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string IsSolder { get; set; }

        /// <summary>
        ///  SKU号
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string SkuCode { get; set; }

        /// <summary>
        ///  SKU描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 200, IsNullable = true)]
        public string SkuDesc { get; set; }

        /// <summary>
        ///  控制扭转
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string Tors { get; set; }

        /// <summary>
        ///  包装组ID
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string PackGrpId { get; set; }

        /// <summary>
        ///  黑盘取样
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string BlackSamp { get; set; }

        /// <summary>
        ///  黑盘检验
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string BlackChk { get; set; }

        /// <summary>
        ///  客户编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string CustCode { get; set; }

        /// <summary>
        ///  客户描述
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string CustName { get; set; }

        /// <summary>
        ///  收货地址编码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string AddressCode { get; set; }

        /// <summary>
        ///  收货地址名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string AddressName { get; set; }

        /// <summary>
        ///  生产批次数量（箱/批）
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Qty { get; set; }

        /// <summary>
        ///  每箱最大焊点盘数（个）
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? BoxMaxSolder { get; set; }

        /// <summary>
        ///  工字轮最大焊点数（个）
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? SpoolMaxSolder { get; set; }

        /// <summary>
        ///  OVC比例
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Ovc { get; set; }

        /// <summary>
        ///  起鼓等级
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string DrummLevel { get; set; }

        /// <summary>
        ///  公司代码
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 50, IsNullable = true)]
        public string ComCode { get; set; }

        /// <summary>
        ///  公司名称
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 100, IsNullable = true)]
        public string ComName { get; set; }

        /// <summary>
        ///  计量单位
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 10, IsNullable = true)]
        public string CalcUnit { get; set; }

        /// <summary>
        ///  库存单位
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 10, IsNullable = true)]
        public string StockUnit { get; set; }

        /// <summary>
        ///  单重
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = true)]
        public decimal? Weight { get; set; }

        /// <summary>
        ///  单重单位
        /// </summary>
        [SugarColumn(ColumnDataType = "nvarchar", Length = 10, IsNullable = true)]
        public string WeightUnit { get; set; }

        /// <summary>
        ///  是否启用时效
        /// </summary>
        [SugarColumn(ColumnDataType = "bit", IsNullable = false)]
        public bool IsHold { get; set; }

        /// <summary>
        ///  时效时长(小时)
        /// </summary>
        [SugarColumn(ColumnDataType = "decimal", Length = 18, IsNullable = false)]
        public decimal HoldDuration { get; set; }

        /// <summary>
        ///  超时时间-小时
        /// </summary>
        [SugarColumn(ColumnDataType = "int", IsNullable = true)]
        public int TimeOut { get; set; }
    }
}