using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using Pms.DataLibrary.Order;
using Pms.Models;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Common.Models;
using ProjectManagementSystem.Common.Service;
using ProjectManagementSystem.Common.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.TaskBookEvent
{
    public class TaskBookBehavior_63040 : BaseTaskBookBehaviorV2
    {
        //LocationPropertyManager locationManager = new LocationPropertyManager();
        public TaskBookBehavior_63040() : base(63040, "跳步骤（双层滚筒）")
        {
        }

        private int GetInpuptIO(TaskData taskData, StepData stepInfo, string columnName)
        {
            var routeConfig = ExcelConfig.Instance.GetRouteConfig(stepInfo.WareHouseID);
            if (routeConfig == null)
            {
                Log(taskData, stepInfo, "查找库位配置信息失败");
                return -1;
            }

            if (routeConfig.IOTransID <= 0)
            {
                Log(taskData, stepInfo, "获取库位对接盒ID失败");
                return -1;
            }

            int id = routeConfig.IOTransID;
            if (!DeviceControl.Instance.Communication.InfoIODictionary.ContainsKey(id))
            {
                Log(taskData, stepInfo, $"获取库位对接盒{id}，没有此盒子数据，检查盒子是否连接网络");
                return -1;
            }

            var infoIO = DeviceControl.Instance.Communication.InfoIODictionary[id];
            if (!infoIO.DataValid)
            {
                Log(taskData, stepInfo, $"获取库位对接盒{id}，盒子已掉线！");
                return -1;
            }

            string realAddr = routeConfig.LocationCode.GetLocationMember(columnName);
            if (string.IsNullOrEmpty(realAddr))
            {
                Log(taskData, stepInfo, $"获取实际地址失败 {columnName}");
                return -1;
            }

            var ret = DeviceControl.Instance.GetInputIO(id, realAddr);
            return ret.Item1 && ret.Item2 ? 1 : 0;
        }

        private int GetNextTemplateStepID(TaskData taskData, StepData stepInfo)
        {
            var plcCallAddr = stepInfo.WareHouseID.GetLocationMember("PLC叫料信号");
            if (!string.IsNullOrEmpty(plcCallAddr))
            {
                var agvData = PmsApi.GetCarrier(taskData.Carrier);
                if (agvData == null)
                {
                    Log(taskData, stepInfo, $"获取AGV数据失败");
                    return -1;
                }

                //起点工位
                bool lowerRollerHasMaterial = agvData.LogicBits.GetBitVaule(10);
                if (!lowerRollerHasMaterial)
                {
                    //下层滚筒没有物料，需要跳过步骤
                    return taskData.StepList
                        .Where(d => d.StepID > taskData.CurrentStepID)
                        .OrderBy(d => d.StepID)
                        .FirstOrDefault(d => d.PmsBehavior == 63305)
                        .TemplateStepID;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                //下层PLC请求空盘运输 设备->AGV
                int plcRequest = GetInpuptIO(taskData, stepInfo, "PLC放料请求");
                if (plcRequest == 1)
                {
                    //有请求信号，不需要跳步骤
                    return 0;
                }
                else if (plcRequest == 0)
                {
                    //没有请求信号需要跳步骤
                    return taskData.StepList
                        .Where(d => d.StepID > taskData.CurrentStepID)
                        .OrderBy(d => d.StepID)
                        .FirstOrDefault(d => d.PmsBehavior == 63305)
                        .TemplateStepID;
                }
                else
                {
                    return -1;
                }
            }
        }

        public override bool TaskBookOperator(TaskData taskData, StepData stepInfo)
        {
            try
            {

                int nextStepId = GetNextTemplateStepID(taskData, stepInfo);
                if (nextStepId < 0)
                {
                    return false;
                }

                if (nextStepId > 0)
                {
                    var result = PmsApi.TaskStepSkip(taskData.TaskID, nextStepId);
                    Log(taskData, stepInfo, $"任务跳步骤到{nextStepId} {result.ToChineseString()}");

                    return result;
                }

                return true;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return false;
        }
    }
}
