using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc.S7;
using Khd.Core.Wcs.Global;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Z.EntityFramework.Plus;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 四楼接驳位
    /// </summary>
    public class FourthFloorPoint
    {
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly int Floor;
        private readonly IHost _host;
        private readonly BasePlcpoint LineRFID;
        private readonly BasePlcpoint LineSignal;
        public FourthFloorPoint(IHost host, int floor)
        {
            Floor = floor;
            this._host = host;
            this.LineRFID = StaticData.BasePlcpointList.First(t => t.plcpointNo == "RFID004");
            this.LineSignal = StaticData.BasePlcpointList.First(t => t.plcpointNo.Contains("linesignal04"));
        }

        public void StartPoint()
        {
            Thread MonitorInLocatorPointThread = new Thread(MonitorInLocatorPoint);
            MonitorInLocatorPointThread.IsBackground = true;
            MonitorInLocatorPointThread.Name = "FourthFloorPoint";
            MonitorInLocatorPointThread.Start();
            Console.WriteLine($"{DateTime.Now}:四楼接驳位线程开始");
        }

        private void MonitorInLocatorPoint()
        {
            List<int> ITypes = new List<int> { 1, 3, 5, 7 };
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            while (true)
            {
                try
                {
                    dbContext.ChangeTracker.Entries().ToList().ForEach(e => e.Reload());
                    //入库任务
                    var rfid = StaticData.PlcDic[0].ReadRFID(LineRFID.plcpointAddress);
                    var isSignal = StaticData.PlcDic[0].Read(LineSignal.plcpointAddress);
                    if (rfid != null && isSignal != null)
                    {
                        if (Convert.ToInt32(isSignal) == 1)//托盘到位
                        {
                            WcsTask? wcsTask = dbContext.WcsTask.Where(t => t.nextPointId == 4).FirstOrDefault();
                            if (wcsTask != null)
                            {
                                if (wcsTask.taskStatus == 5)//提升机上来的
                                {
                                    //清除托盘信息
                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.FirstOrDefault(t => t.palletInfoCode == rfid);
                                    if (mesBasePalletInfo != null)
                                    {
                                        MesBaseBarcodeInfo? mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.Where(t => t.palletInfoCode == rfid).FirstOrDefault();
                                        if (mesBaseBarcodeInfo != null)
                                        {
                                            mesBaseBarcodeInfo.palletInfoCode = null;
                                            dbContext.Update(mesBaseBarcodeInfo);
                                        }
                                        mesBasePalletInfo.bindAmount = null;
                                        mesBasePalletInfo.bindAmount = null;
                                        mesBasePalletInfo.materialBarcode = null;
                                        mesBasePalletInfo.materialCode = null;
                                        mesBasePalletInfo.materialId = null;
                                        mesBasePalletInfo.materialName = null;
                                        mesBasePalletInfo.updateBy = "WCS";
                                        mesBasePalletInfo.updateTime = DateTime.Now;
                                        dbContext.Update(mesBasePalletInfo);
                                        dbContext.Remove(wcsTask);
                                        dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(t => new WcsTaskLog { taskStatus = 6 });
                                        dbContext.Remove(wcsTask);
                                        dbContext.SaveChanges();
                                    }
                                }
                            }
                            else
                            {
                                bool hasTask = dbContext.WcsTask.Where(t => t.currPointId == 4 || (t.endPointId == 4 && t.taskStatus > 0)).Any();
                                //如果有任务往当前楼层送，报警
                                BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.objid == 4);
                                BaseEquip nextEquip = StaticData.BaseEquip.First(t => t.objid == 6);
                                if (!hasTask)
                                {
                                    MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.Where(t => t.palletInfoCode == rfid).FirstOrDefault();
                                    if (mesBasePalletInfo != null)
                                    {
                                        var warehouseId = dbContext.WmsWarehouseMaterial.Where(t => t.storageType == "1" && t.storageId == mesBasePalletInfo.materialId).FirstOrDefault()?.warehouseId;
                                        if (warehouseId != null)
                                        {
                                            var TargetFloor = dbContext.WmsBaseWarehouse.Where(t => t.warehouseId == warehouseId).FirstOrDefault();
                                            if (TargetFloor != null)
                                            {
                                                if (TargetFloor.warehouseFloor == Floor)
                                                {
                                                    continue;
                                                }
                                                var dic = StaticData.BaseDictionary.Where(t => t.dicKey == "TaskType" && t.agvType == "I" && t.dicField == TargetFloor.warehouseInstockType).FirstOrDefault();
                                                if (dic != null)
                                                {
                                                    var newTask = new WcsTask()
                                                    {
                                                        objid = StaticData.SnowId.NextId(),
                                                        serialNo = SystemData.GetSerialNo(dbContext),
                                                        taskType = Convert.ToInt32(dic.dicValue),
                                                        taskStatus = 0,
                                                        containerNo = rfid,
                                                        materialBarcode = mesBasePalletInfo.materialBarcode,
                                                        materialId = mesBasePalletInfo.materialId,
                                                        qty = Convert.ToInt32(mesBasePalletInfo.bindAmount),
                                                        currPointId = lineEquip.objid,
                                                        currPointNo = lineEquip.equipNo,
                                                        nextPointId = nextEquip.objid,
                                                        nextPointNo = nextEquip.equipNo,
                                                        endPointId = warehouseId,
                                                        fromFloorNo = 4,
                                                        floorNo = TargetFloor.warehouseFloor,
                                                        useFlag = 1,
                                                        createBy = "一楼接驳位",
                                                        createTime = DateTime.Now,
                                                        remark = "一楼创建入库任务"
                                                    };
                                                    dbContext.Add(newTask);
                                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                    dbContext.Add(wcsTaskLog);
                                                    dbContext.SaveChanges();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

                    }
                    else
                    {
                        _logger.Error(ex.Message + "\n" + ex.StackTrace);
                    }
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }
    }
}
