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 : 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 routeConfig = ExcelConfig.Instance.GetRouteConfig(stepInfo.WareHouseID);
            if (routeConfig == null)
            {
                Log(taskData, stepInfo, "查找库位配置信息失败");
                return false;
            }
            if (string.IsNullOrEmpty(routeConfig.PlcIpAddr))
            {
                Log(taskData, stepInfo, "PlcIp地址为空");
                return false;
            }


            bool allowIn = IsLogicBitsOn(taskData.Carrier, 7);
            string allowInAddr = routeConfig.LocationCode.GetLocationMember(AllowInColumnName);

            var result = routeConfig.PlcReadWrite.Write(allowInAddr, allowIn);
            Log(taskData, stepInfo, $"{AllowInColumnName} {allowInAddr}={allowIn} 写入{result.IsSuccess.ToChineseString()}");

            return false;
        }
    }
}
