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

namespace ProjectManagementSystem.TaskBookEvent
{
    public class TaskBookBehavior_63009 : BaseTaskBookBehaviorV2
    {
        LocationPropertyManager locationManager = new LocationPropertyManager();

        public TaskBookBehavior_63009() : base(63009, "双层滚筒续接任务")
        {
        }

        private bool GetNextTask(TaskData taskData, StepData stepInfo, out string nextTemplateName, out string nextLocation)
        {
            nextTemplateName = null;
            nextLocation = null;

            switch (taskData.TaskBook)
            {
                case "上层取满盘":
                    var agvData = PmsApi.GetCarrier(taskData.Carrier);
                    if (agvData == null)
                    {
                        Log(taskData, stepInfo, $"获取AGV数据失败");
                        return false;
                    }

                    bool lowerRollerHasMaterial = agvData.LogicBits.GetBitVaule(10);
                    if(lowerRollerHasMaterial)
                    {
                        nextTemplateName = "下层放空盘";
                        nextLocation = stepInfo.WareHouseID;
                    }
                    else
                    {
                        nextTemplateName = "上层放满盘";
                        nextLocation = stepInfo.WareHouseID.GetLocationMember("续接任务放货点");
                    }
                    return true;
                case "下层放空盘":
                    nextTemplateName = "上层放满盘";
                    nextLocation = stepInfo.WareHouseID.GetLocationMember("续接任务放货点");
                    return true;
                case "上层放满盘":

                    //下层PLC请求空盘运输 设备->AGV
                    int plcRequest = GetInpuptIO(taskData, stepInfo, "PLC放料请求");
                    if(plcRequest == 1)
                    {
                        nextTemplateName = "下层取空盘";
                        nextLocation = stepInfo.WareHouseID;
                        return true;
                    }
                    else if(plcRequest == 0)
                    {
                        nextTemplateName = string.Empty;
                        nextLocation = string.Empty;
                        return true;
                    }

                    break;
                default:
                    break;
            }

            return false;
        }

        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;
        }

        public override bool TaskBookOperator(TaskData taskData, StepData stepInfo)
        {
            try
            {
                var resultNext = GetNextTask(taskData, stepInfo, out string nextTemplateName, out string nextLocation);
                if(!resultNext)
                {
                    return false;
                }

                if(string.IsNullOrEmpty(nextTemplateName))
                {
                    Log(taskData, stepInfo, $"获取下个任务模板失败");
                    return true;
                }
                if (string.IsNullOrEmpty(nextLocation))
                {
                    Log(taskData, stepInfo, $"获取下个任务点失败");
                    return true;
                }

                Log(taskData, stepInfo, $"已获取下个任务模板：{nextTemplateName} 下个任务点：{nextLocation}");

                MidTaskInfoEx data = new MidTaskInfoEx();
                data.TemplateName = nextTemplateName;
                data.ParametersDic.Add("U1", nextLocation);
                data.AgvId = taskData.Carrier;
                data.AgvType = "1";
                data.ParentTaskId = taskData.TaskID;

                var result = PmsTaskService.Instance.TaskAdd(data, new string[] { });
                if (!result)
                {
                    Log(taskData, stepInfo, $"续接任务失败");
                    return false;
                }

                //Log(taskDetailInfo, stepInfo, $"续接任务成功 {result.message}");
                System.Threading.Thread.Sleep(1000);
                return true;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return false;
        }
    }
}
