using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Extenions;
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 AsyncBehaviorPauseCarrier : AsyncBehavior
    {
        public string OnlineModeAddr { get; set; } = "PLC在线模式";
        public string AlarmAddr { get; set; } = "PLC故障";
        public string EStopAddr { get; set; } = "PLC急停";

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

            var tempResult = routeConfig.PlcReadWrite.Read(routeConfig.PlcHeartbearAddr, 1);

            bool onlineMode = tempResult.IsSuccess && tempResult.Content[0].GetBitVaule(2);
            bool alarm = tempResult.IsSuccess && tempResult.Content[0].GetBitVaule(3);
            bool eStop = tempResult.IsSuccess && tempResult.Content[0].GetBitVaule(4);
            bool realEStop = !eStop;

            string onlineModeAddr = routeConfig.LocationCode.GetLocationMember(OnlineModeAddr);
            string alarmAddr = routeConfig.LocationCode.GetLocationMember(AlarmAddr);
            string eStopAddr = routeConfig.LocationCode.GetLocationMember(EStopAddr);

            bool needPause = !onlineMode && alarm || realEStop;
            if (needPause)
            {
                bool result = PmsApi.CarrierPause(taskData.Carrier);
                Log(taskData, stepInfo, $"暂停小车{result.ToChineseString()} {OnlineModeAddr}{onlineModeAddr}={onlineMode} {AlarmAddr}{alarmAddr}={alarm} {EStopAddr}{eStopAddr}={eStop}");
            }

            bool needResume = onlineMode && !alarm && !realEStop;
            if (needResume)
            {
                bool result = PmsApi.CarrierResume(taskData.Carrier);
                Log(taskData, stepInfo, $"恢复小车{result.ToChineseString()} {OnlineModeAddr}{onlineModeAddr}={onlineMode} {AlarmAddr}{alarmAddr}={alarm} {EStopAddr}{eStopAddr}={eStop}");
            }

            return false;
        }
    }
}
