using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.WebApi;
using ProjectManagementSystem.Common.Extenions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectManagementSystem.Common.Core;

namespace ProjectManagementSystem.TaskBookEvent
{
    public class AsyncBehaviorRollerAllowIn_IO : AsyncBehavior
    {
        public string AllowInColumnName { get; set; } = "AGV滚筒允许进入";

        public bool IsLogicBitsOn(int agvId, int bitIndex)
        {
            var agvData = PmsApi.GetCarrier(agvId);
            if (agvData == null) return false;

            //判断AGV滚筒是否已经转动
            return agvData.LogicBits.GetBitVaule(bitIndex);
        }

        public override bool CustomOperator(TaskData taskData, StepData stepInfo)
        {
            //var allowIn2 = (stepInfo.Param1 & 0x5555) > 0;
            //Log(taskData, stepInfo, $"允许进入 {stepInfo.Param1} {allowIn2}");
            //return false;

            var routeConfig = ExcelConfig.Instance.GetRouteConfig(stepInfo.WareHouseID);
            if (routeConfig == null)
            {
                Log(taskData, stepInfo, "查找库位配置信息失败");
                return false;
            }

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

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

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

            bool allowIn = IsLogicBitsOn(taskData.Carrier, 7);
            if(stepInfo.AgvBehavior == 65350
                && stepInfo.Param1 > 0
                && allowIn)
            {
                //执行的是设备->滚筒的上料任务
                allowIn = (stepInfo.Param1 & 0x5555) > 0;
            }

            string allowInAddr = routeConfig.LocationCode.GetLocationMember(AllowInColumnName);

            DeviceControl.Instance.SetOutputIO(id, allowInAddr, allowIn);
            System.Threading.Thread.Sleep(100);
            var realValue = DeviceControl.Instance.GetOutputIO(id, allowInAddr);

            bool result = (allowIn == (realValue.Item1 && realValue.Item2));
            Log(taskData, stepInfo, $"ID{id} {AllowInColumnName} {allowInAddr}={allowIn} 写入{result.ToChineseString()}");

            return false;
        }
    }
}
