using CFX;
using HslCommunication;
using Sln.Iot.CFX.CFXBusiness;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
using Sln.Iot.Common;
using Sln.Iot.PLC;
using Sln.Iot.Repository.service;
using Sln.Iot.Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace Sln.Iot.Business
{
    public class RFID02Business
    {
        private Timer _timer;

        private readonly PLCConnect _plc = PLCConnect.Instance;

        private readonly SerilogHelper _log = SerilogHelper.Instance;

        private TrayBindingService trayBindingService = TrayBindingService.Instance;
        private OvenPlcDataService ovenPlcDataService = OvenPlcDataService.Instance;

        private UnitsProcessPLCDataGetBusiness unitsProcessPLCDataGetBusiness = UnitsProcessPLCDataGetBusiness.Instance;
        private CFXUnitProcessedDataGet cfxUnitProcessedDataGet = CFXUnitProcessedDataGet.Instance;

        private WorkStageStartedEvent workStageStartedEvent = new WorkStageStartedEvent();
        private WorkStageCompletedEvent workStageCompletedEvent = new WorkStageCompletedEvent();
        private WorkCompletedEvent workCompletedEvent = new WorkCompletedEvent();
        private UnitsDepartedEvent unitsDepartedEvent = new UnitsDepartedEvent();
        private UnitsArrivedEvent unitsArrivedEvent = new UnitsArrivedEvent();
        private WorkStartedEvent workStartedEvent = new WorkStartedEvent();

        private CFXConnectOven ConnectOven = CFXConnectOven.Instance;
        private CFXConnectVacuum ConnectVacuum = CFXConnectVacuum.Instance;


        public RFID02Business()
        {
            _timer = new Timer(TimerCallback, null, 0, 2000);
        }

        /// <summary>
        /// RFID02胶机1真空箱内数据处理流程
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            try
            {
                // 定时任务逻辑
                //读取信号
                OperateResult<short> signalRes = _plc.ReadInt16(_plc.PLC23, "D900");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    //_log.Info($"RFID02:{signalValue}");
                    //如果有读取信号
                    if (signalValue == 2001)
                    {
                        //读取托盘码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.PLC23, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {
                            //转换托盘码
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            traycode = traycode.Replace("?", "");
                            traycode = traycode.Replace("\0", "");
                            _log.Info($"托盘到达-RFID02-托盘号-[{traycode}]");

                            //记录胶机1真空箱内到达时间
                            trayBindingService.UpDateTime(DateTime.Now.ToString(), traycode, "2");

                            bool res = false;
                            //写入完成信号
                            res = _plc.PlcWrite(_plc.PLC23, "D900", 2002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("真空箱内写入完成信号异常");
                            }

                            //取出work唯一guid(tid)
                            string stid = trayBindingService.TidGet(traycode);
                            if (!Guid.TryParse(stid, out Guid tid))
                            {
                                tid = Guid.Parse("11111111-1111-4111-9111-111111111111");
                                _log.Error("找不到对应的托盘信息，赋值默认GUID");
                            }

                            string[] prodcode = trayBindingService.ProdCodeGet(traycode);

                            //CFX
                            Task.Run(() =>
                            {
                                //真空箱工段完成事件
                                ConnectVacuum.PublishEvent(new CFXEnvelope(workStageCompletedEvent.Handle(tid, "vacuum", 1)));
                                _log.Info($"真空箱工段完成 ID:{tid}");
                                ConnectVacuum.PublishEvent(new CFXEnvelope(workCompletedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"工作完成事件发布 ID:{tid}");
                                ConnectVacuum.PublishEvent(new CFXEnvelope(unitsDepartedEvent.Handle(traycode, prodcode)));
                                _log.Info($"单元离站 ID:{tid}");

                                //单元抵达事件
                                ConnectOven.PublishEvent(new CFXEnvelope(unitsArrivedEvent.Handle(traycode, prodcode)));
                                //工作开始事件
                                ConnectOven.PublishEvent(new CFXEnvelope(workStartedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"隧道炉工作开始，ID:{tid}");
                                //隧道炉工段开启
                                ConnectOven.PublishEvent(new CFXEnvelope(workStageStartedEvent.Handle(tid, "oven", 1)));
                                _log.Info($"隧道炉工段开始 ID:{tid}");
                                _log.Info("===================================================================================");
                            });

                            //CFX
                        }
                        else
                        {
                            _log.Error($"PLC读取失败，原因：{trayBytesResult.Message}");
                        }
                        //流程完成
                    }
                    else if (signalValue == 2003)
                    {
                        //读取托盘码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.PLC23, "D5000", 10);
                        if (trayBytesResult.IsSuccess)
                        {
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            traycode = traycode.Replace("?", "");
                            traycode = traycode.Replace("\0", "");
                            _log.Info($"托盘离开-RFID02-托盘号-[{traycode}]");
                            GlobalVar.Connect1Entity.PassQuantity++;
                            GlobalVar.Connect2Entity.InputQuantity++;
                            //计算预热炉停留时长: time2 - time1
                            string time2 = trayBindingService.GetTimeByTrayCode(traycode, "2");
                            string time1 = trayBindingService.GetTimeByTrayCode(traycode, "1");
                            ushort spanSecond = 0;

                            if (!string.IsNullOrEmpty(time2) && !string.IsNullOrEmpty(time1))
                            {
                                TimeSpan span = Convert.ToDateTime(time2) - Convert.ToDateTime(time1);
                                spanSecond = (ushort)span.TotalSeconds;
                                GlobalVar.Connect1Entity.CycleTime = spanSecond;
                                _log.Info($"真空箱停留时长: [{spanSecond}]秒");
                            }
                            bool res = _plc.PlcWrite(_plc.PLC23, "D910", spanSecond, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID02 发送真空箱停留时长 PLC写入异常");
                            }

                            res = false;

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.PLC23, "D900", 2004, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID02 发送真空箱停留时长 PLC写入完成信号异常");
                            }
                            _log.Info("===================================================================================");


                        }
                        else
                        {
                            _log.Error($"PLC读取失败，原因：{trayBytesResult.Message}");
                        }
                    }
                }
                else
                {
                    _log.Error($"真空箱内PLC读取信号异常,原因：{signalRes.Message}");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID02业务出现异常", ex);
            }

        }
    }
}
