using Khd.Core.Domain.Dto.TaskType;
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;

namespace Khd.Core.Wcs.Wcs
{
    /// <summary>
    /// 二楼接驳位调度
    /// </summary>
    public class SecondFloorPoint
    {
        private readonly LoggerUtils _logger = new LoggerUtils();
        private readonly IHost _host;
        private readonly BasePlcpoint LineRFID;
        private readonly BasePlcpoint LineSignal;
        int FloorNo { get; set; }
        public SecondFloorPoint(IHost host, int floor)
        {
            this._host = host;
            FloorNo = floor;
            this.LineRFID = StaticData.BasePlcpointList.First(t => t.plcpointNo == "RFID002");
            this.LineSignal = StaticData.BasePlcpointList.First(t => t.plcpointNo == "linesignal02");
        }
        /// <summary>
        /// 启动上件扫描监听
        /// </summary>
        public void StartPoint()
        {

            Thread FlowPointThread = new Thread(MonitorInLocatorPoint);
            FlowPointThread.Name = "SecondFloorPoint";
            FlowPointThread.IsBackground = true;
            FlowPointThread.Start();
            Console.WriteLine(DateTime.Now + ":二楼接驳位扫描线程启动");
            _logger.Info("二楼接驳位扫描线程启动");
        }

        public void MonitorInLocatorPoint()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            BaseEquip inEquip = StaticData.BaseEquip.First(t => t.objid == 36);//小包入口
            BaseEquip outEquip = StaticData.BaseEquip.First(t => t.objid == 37);//小包出口
            BaseEquip lineEquip = StaticData.BaseEquip.First(t => t.objid == 2);//二楼接驳位
            BaseEquip agvEquip = StaticData.BaseEquip.First(t => t.objid == 8);//二楼叉车
            BaseEquip tsjEquip = StaticData.BaseEquip.First(t => t.objid == 6);//提升机
            var agvPutPoint = StaticData.BasePlcpointList.First(t => t.id == 54);//二楼小包入口点位
            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)
                        {
                            //获取条码信息
                            BaseEquip baseEquip = StaticData.BaseEquip.First(t => t.objid == 2);
                            var wcsTask = dbContext.WcsTask.Where(t => t.nextPointId == 2).OrderBy(t => t.createTime).FirstOrDefault();
                            if (wcsTask != null)
                            {
                                if (wcsTask.taskStatus == 5 && (wcsTask.nextPointId == 6 || wcsTask.nextPointId == 2))//入托盘入口,提升机任务是完成状态
                                {
                                    object? agvPutValue = null;
                                    try
                                    {
                                        agvPutValue = StaticData.PlcDic[2].Read(agvPutPoint.plcpointAddress);
                                    }
                                    catch
                                    {

                                    }
                                    if (wcsTask.taskType != 99)//不是人工任务
                                    {
                                        bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == inEquip.objid).Any();
                                        if (agvPutValue != null && Convert.ToInt32(agvPutValue) == 0 && !hasTask)//小包入口要料
                                        {
                                            dbContext.WcsTask.Remove(wcsTask);//删除原本的任务
                                            WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                            newTask.taskStatus = 0;
                                            newTask.objid = StaticData.SnowId.NextId();
                                            newTask.nextPointId = agvEquip.objid;//小车执行该任务
                                            newTask.nextPointNo = agvEquip.equipNo;
                                            newTask.createTime = DateTime.Now;
                                            newTask.updateTime = DateTime.Now;
                                            newTask.containerNo = rfid;//容器号
                                            newTask.currPointId = lineEquip.objid;//起始地为二楼接驳位
                                            newTask.currPointNo = lineEquip.equipNo;
                                            newTask.endPointId = inEquip.objid;//终点为小包入口
                                            newTask.endPointNo = inEquip.equipNo;
                                            newTask.taskType = StaticTaskType.SecondLineToSmallPackage;//提升机到小包入口的任务类型
                                            newTask.useFlag = 1;
                                            dbContext.WcsTask.Add(newTask);
                                            WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                            dbContext.Add(wcsTaskLog);
                                            dbContext.SaveChanges();
                                            _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                            Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                        }
                                        else
                                        {
                                            BaseEquip? endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 20 && t.equipStatus == 0 && t.emptyCount == 0);//二楼周转位
                                            if (endEquip != null)
                                            {
                                                dbContext.WcsTask.Remove(wcsTask);//删除原本的任务
                                                WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                                newTask.taskStatus = 0;
                                                newTask.objid = StaticData.SnowId.NextId();
                                                newTask.nextPointId = agvEquip.objid;//小车执行该任务
                                                newTask.nextPointNo = agvEquip.equipNo;
                                                newTask.createTime = DateTime.Now;
                                                newTask.updateTime = DateTime.Now;
                                                newTask.containerNo = rfid;//容器号
                                                newTask.currPointId = lineEquip.objid;//起始地为二楼接驳位
                                                newTask.currPointNo = lineEquip.equipNo;
                                                newTask.endPointId = endEquip.objid;//终点为周转位
                                                newTask.endPointNo = endEquip.equipNo;
                                                newTask.taskType = StaticTaskType.SecondLiftToTransit;//提升机到周转位的任务类型
                                                newTask.useFlag = 1;
                                                dbContext.WcsTask.Add(newTask);
                                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                dbContext.Add(wcsTaskLog);
                                                dbContext.SaveChanges();
                                                _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (wcsTask.endPointId == 36)//目的地是小包入口
                                        {
                                            bool hasTask = dbContext.WcsTask.Where(t => t.endPointId == inEquip.objid).Any();
                                            if (agvPutValue != null && Convert.ToInt32(agvPutValue) == 0 && !hasTask)//小包入口要料
                                            {
                                                dbContext.WcsTask.Remove(wcsTask);
                                                WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                                newTask.taskStatus = 0;
                                                newTask.objid = StaticData.SnowId.NextId();
                                                newTask.nextPointId = agvEquip.objid;
                                                newTask.nextPointNo = agvEquip.equipNo;
                                                newTask.createTime = DateTime.Now;
                                                newTask.updateTime = DateTime.Now;
                                                newTask.containerNo = rfid;
                                                newTask.currPointId = lineEquip.objid;
                                                newTask.currPointNo = lineEquip.equipNo;
                                                newTask.endPointId = inEquip.objid;
                                                newTask.endPointNo = inEquip.equipNo;
                                                newTask.taskType = StaticTaskType.SecondLineToSmallPackage;//到小包入口
                                                newTask.useFlag = 1;
                                                dbContext.WcsTask.Add(newTask);
                                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                dbContext.Add(wcsTaskLog);
                                                dbContext.SaveChanges();
                                                _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                            }
                                            else
                                            {
                                                BaseEquip? endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 20 && t.equipStatus == 0 && t.emptyCount == 0);
                                                if (endEquip != null)
                                                {
                                                    dbContext.WcsTask.Remove(wcsTask);
                                                    WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                                    newTask.taskStatus = 0;
                                                    newTask.objid = StaticData.SnowId.NextId();
                                                    newTask.nextPointId = agvEquip.objid;
                                                    newTask.nextPointNo = agvEquip.equipNo;
                                                    newTask.createTime = DateTime.Now;
                                                    newTask.updateTime = DateTime.Now;
                                                    newTask.containerNo = rfid;
                                                    newTask.currPointId = lineEquip.objid;
                                                    newTask.currPointNo = lineEquip.equipNo;
                                                    newTask.endPointId = endEquip.objid;
                                                    newTask.endPointNo = endEquip.equipNo;
                                                    newTask.taskType = StaticTaskType.SecondLiftToTransit;//到周转位
                                                    newTask.useFlag = 1;
                                                    dbContext.WcsTask.Add(newTask);
                                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                    dbContext.Add(wcsTaskLog);
                                                    dbContext.SaveChanges();
                                                    _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                    Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                }
                                            }
                                        }
                                        else if (wcsTask.endPointId == 38)//目的地是废料区
                                        {
                                            var endEquip = dbContext.BaseEquip.First(t => t.objid == 38);//废料区
                                            if (endEquip.emptyCount == 0)//废料区没有托盘
                                            {
                                                dbContext.WcsTask.Remove(wcsTask);
                                                WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                                newTask.taskStatus = 0;
                                                newTask.objid = StaticData.SnowId.NextId();
                                                newTask.nextPointId = agvEquip.objid;
                                                newTask.nextPointNo = agvEquip.equipNo;
                                                newTask.createTime = DateTime.Now;
                                                newTask.updateTime = DateTime.Now;
                                                newTask.containerNo = rfid;
                                                newTask.currPointId = lineEquip.objid;
                                                newTask.currPointNo = lineEquip.equipNo;
                                                newTask.taskType = StaticTaskType.SecondLiftToWaste;
                                                newTask.useFlag = 1;
                                                dbContext.WcsTask.Add(newTask);
                                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                dbContext.Add(wcsTaskLog);
                                                dbContext.SaveChanges();
                                                _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                            }
                                            else
                                            {
                                                endEquip = dbContext.BaseEquip.FirstOrDefault(t => t.equipType == 20 && t.equipStatus == 0 && t.emptyCount == 0);//周转位
                                                if (endEquip != null)
                                                {
                                                    dbContext.WcsTask.Remove(wcsTask);
                                                    WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                                    newTask.taskStatus = 0;
                                                    newTask.objid = StaticData.SnowId.NextId();
                                                    newTask.nextPointId = agvEquip.objid;
                                                    newTask.nextPointNo = agvEquip.equipNo;
                                                    newTask.createTime = DateTime.Now;
                                                    newTask.updateTime = DateTime.Now;
                                                    newTask.containerNo = rfid;
                                                    newTask.currPointId = lineEquip.objid;
                                                    newTask.currPointNo = lineEquip.equipNo;
                                                    newTask.endPointId = endEquip.objid;
                                                    newTask.endPointNo = endEquip.equipNo;
                                                    newTask.taskType = StaticTaskType.SecondLiftToTransit;
                                                    newTask.useFlag = 1;
                                                    dbContext.WcsTask.Add(newTask);
                                                    WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                                    dbContext.Add(wcsTaskLog);
                                                    dbContext.SaveChanges();
                                                    _logger.Info("二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                    Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务入库成功,托盘号:" + rfid);
                                                }
                                            }
                                        }
                                    }
                                }
                                else if (wcsTask.taskStatus == 8)//小车任务完成
                                {
                                    if (wcsTask.taskType == StaticTaskType.SecondStorageToLift && wcsTask.containerNo == rfid)//50是成品出库
                                    {
                                        BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == 1);
                                        dbContext.WcsTask.Remove(wcsTask);
                                        WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                        newTask.serialNo = SystemData.GetSerialNo(dbContext);
                                        newTask.taskStatus = 0;
                                        newTask.objid = StaticData.SnowId.NextId();
                                        newTask.nextPointId = tsjEquip.objid;
                                        newTask.nextPointNo = tsjEquip.equipNo;
                                        newTask.createTime = DateTime.Now;
                                        newTask.updateTime = DateTime.Now;
                                        newTask.endPointId = endEquip.objid;
                                        newTask.endPointNo = endEquip.equipNo;
                                        newTask.containerNo = rfid;
                                        newTask.currPointId = lineEquip.objid;
                                        newTask.currPointNo = lineEquip.equipNo;
                                        newTask.useFlag = 1;
                                        newTask.fromFloorNo = 2;
                                        newTask.floorNo = endEquip.floorNo;
                                        dbContext.WcsTask.Add(newTask);
                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                        dbContext.Add(wcsTaskLog);
                                        dbContext.SaveChanges();
                                        _logger.Info("二楼接驳位生成任务出库成功,托盘号:" + rfid);
                                        Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务出库成功,托盘号:" + rfid);
                                    }
                                    else//一般情况下是废料的任务
                                    {
                                        BaseEquip endEquip = StaticData.BaseEquip.First(t => t.objid == wcsTask.endPointId);
                                        dbContext.WcsTask.Remove(wcsTask);
                                        WcsTask newTask = CoreMapper.Map<WcsTask>(wcsTask);
                                        newTask.serialNo = SystemData.GetSerialNo(dbContext);
                                        newTask.taskStatus = 0;
                                        newTask.objid = StaticData.SnowId.NextId();
                                        newTask.nextPointId = tsjEquip.objid;
                                        newTask.nextPointNo = tsjEquip.equipNo;
                                        newTask.createTime = DateTime.Now;
                                        newTask.updateTime = DateTime.Now;
                                        newTask.endPointId = endEquip.objid;
                                        newTask.endPointNo = endEquip.equipNo;
                                        newTask.containerNo = rfid;
                                        newTask.currPointId = lineEquip.objid;
                                        newTask.currPointNo = lineEquip.equipNo;
                                        newTask.useFlag = 1;
                                        newTask.fromFloorNo = 2;
                                        newTask.floorNo = endEquip.floorNo;
                                        dbContext.WcsTask.Add(newTask);
                                        WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(newTask);
                                        dbContext.Add(wcsTaskLog);
                                        dbContext.SaveChanges();
                                        _logger.Info("二楼接驳位生成任务出库成功,托盘号:" + rfid);
                                        Console.WriteLine(DateTime.Now + ":二楼接驳位生成任务出库成功,托盘号:" + rfid);
                                    }

                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is PlcException)
                    {

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