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_63041 : BaseTaskBookBehaviorV2
    {
        private int agvRollerBehavior = 65350;

        //LocationPropertyManager locationManager = new LocationPropertyManager();
        public TaskBookBehavior_63041() : base(63041, "变更滚筒动作参数（双层滚筒）")
        {
        }

        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 (bool, int, int, int) GetNextInfo(TaskData taskData, StepData stepInfo)
        {
            //var plcCallAddr = stepInfo.WareHouseID.GetLocationMember("PLC叫料信号");
            if (stepInfo.WareHouseID == "STN1180")
            {
                var agvData = PmsApi.GetCarrier(taskData.Carrier);
                if (agvData == null)
                {
                    Log(taskData, stepInfo, $"获取AGV数据失败");
                    return (false, 0, 0, 0);
                }

                //起点工位
                bool lowerRollerHasMaterial = agvData.LogicBits.GetBitVaule(10);
                if (!lowerRollerHasMaterial)
                {
                    //下层滚筒没有物料，需要变参数
                    int stepId = taskData.StepList
                        .Where(d => d.StepID > taskData.CurrentStepID)
                        .OrderBy(d => d.StepID)
                        .FirstOrDefault(d => d.AgvBehavior == agvRollerBehavior)
                        .TemplateStepID;

                    return (true, stepId, 17, 63301);
                }
                else
                {
                    return (true, 0, 0, 0);
                }
            }
            else
            {
                //下层PLC请求空盘运输 设备->AGV
                int plcRequest = GetInpuptIO(taskData, stepInfo, "PLC放料请求");
                if (plcRequest == 1)
                {
                    //有请求信号，不需要变参数
                    return (true, 0, 0, 0);
                }
                else if (plcRequest == 0)
                {
                    //没有请求信号需要变参数
                    int stepId = taskData.StepList
                        .Where(d => d.StepID > taskData.CurrentStepID)
                        .OrderBy(d => d.StepID)
                        .FirstOrDefault(d => d.AgvBehavior == agvRollerBehavior)
                        .TemplateStepID;

                    return (true, stepId, 136, 0);
                }
                else
                {
                    return (false, 0, 0, 0);
                }
            }
        }

        public override bool TaskBookOperator(TaskData taskData, StepData stepInfo)
        {
            try
            {
                var nextInfo = GetNextInfo(taskData, stepInfo);
                if (nextInfo.Item1 == false)
                {
                    return false;
                }

                if (nextInfo.Item2 > 0 && nextInfo.Item3 > 0)
                {
                    if (nextInfo.Item4 > 0)
                    {
                        var result2 = PmsApi.UpdateStepAgvBehavior(taskData.TaskID, nextInfo.Item2 - 1, false, 0, 0, 0, 0, nextInfo.Item4);
                        Log(taskData, stepInfo, $"任务变更PMS行为码 Step{nextInfo.Item2} {nextInfo.Item4} {result2.ToChineseString()}");

                        if (!result2)
                        {
                            return result2;
                        }
                    }

                    var result = PmsApi.UpdateStepAgvBehavior(taskData.TaskID, nextInfo.Item2, true, agvRollerBehavior, nextInfo.Item3, 0, 0, 0);
                    Log(taskData, stepInfo, $"任务变更AGV行为码 Step{nextInfo.Item2} {agvRollerBehavior} 参数{nextInfo.Item3} {result.ToChineseString()}");

                    return result;
                }

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