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

namespace ProjectManagementSystem.TaskEvent
{
    public class ProcessAgvAlarmLight : ICustomProcess
    {
        private int[] ignoreAlarmIds = ExcelConfig.Instance.VcuAlarmInfoList?.Where(d => d.Ignore).Select(d => d.AlarmId).ToArray();

        private bool firstStart = true;
        private bool lastAgvAlarm;
        public DateTime SetTrafficLightTime { get; set; }
        public bool ReSetTrafficLight
        {
            get { return (DateTime.Now - SetTrafficLightTime).TotalSeconds > 60; }
        }


        public void CustomProcess(List<TaskData> taskDataList)
        {
            var agvDataList = PmsApi.GetAllCarrier();
            if (agvDataList == null) return;

            var agvData = agvDataList.FirstOrDefault(d => d.Online && d.AlarmList != null && d.AlarmList.Exists(a => a.alarmId > 0 && !ignoreAlarmIds.Contains(a.alarmId)));
            var agvAlarm = agvData != null;

            if (lastAgvAlarm != agvAlarm || firstStart || ReSetTrafficLight)
            {
                SetTrafficLightTime = DateTime.Now;
                lastAgvAlarm = agvAlarm;

                var lightNumber = 1;
                var lightType = agvAlarm ? 1 : 0;
                DeviceControl.Instance.SetAlarmLight(lightNumber, lightType);

                if (lightType == 0)
                {
                    CLog.Instance.TaskLog.WriteInfo($"AGV报警灯{lightNumber} 灭灯");
                }
                else
                {
                    var alarmId = agvData?.AlarmList?.FirstOrDefault(a => a.alarmId > 0 && !ignoreAlarmIds.Contains(a.alarmId))?.alarmId;
                    var alarmName = ExcelConfig.Instance.GetVcuAlarmInfo(alarmId ?? 0)?.AlarmName;

                    CLog.Instance.TaskLog.WriteInfo($"AGV报警灯{lightNumber} 亮灯 AGV{agvData?.AgvID}报警代码:{alarmId} {alarmName}");
                }
            }

            firstStart = false;
        }
    }
}
