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.Config;
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;

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

        private readonly PLCConnect _plc = PLCConnect.Instance;

        private readonly SerilogHelper _log = SerilogHelper.Instance;

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

        private TrayBindingService trayBindingService = TrayBindingService.Instance;
        private WorkStageStartedEvent workStageStartedEvent = new WorkStageStartedEvent();
        private WorkStageCompletedEvent workStageCompletedEvent = new WorkStageCompletedEvent();
        private WorkCompletedEvent workCompletedEvent = new WorkCompletedEvent();
        private UnitsDepartedEvent unitsDepartedEvent = new UnitsDepartedEvent();
        private UnitsProcessedEvent unitsProcessedEvent = new UnitsProcessedEvent();

        private CFXConnectOven ConnectOven = CFXConnectOven.Instance;


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

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

                            bool res = trayBindingService.UpDateTime(DateTime.Now.ToString(), traycode, "3");
                            if (!res)
                            {
                                _log.Error("隧道炉外时间更新失败（未扫托盘号）");
                            }

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.PLC24, "D800", 3002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("隧道炉外写入完成信号异常");
                            }

                            //sql更新
                            //取出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(() =>
                            {
                                //烤炉工段完成事件
                                ConnectOven.PublishEvent(new CFXEnvelope(workStageCompletedEvent.Handle(tid, "oven", 1)));
                                _log.Info($"隧道炉工段完成 ID:{tid}");
                                ConnectOven.PublishEvent(new CFXEnvelope(workCompletedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"工作完成事件发布 ID:{tid}");
                                ConnectOven.PublishEvent(new CFXEnvelope(unitsDepartedEvent.Handle(traycode, prodcode)));
                                _log.Info($"单元离站 ID:{tid}");
                                _log.Info("===================================================================================");
                            });
                        }
                        else
                        {
                            _log.Error($"PLC读取失败，原因：{trayBytesResult.Message}");
                        }
                        //流程完成
                    }
                    else if (signalValue == 3003)
                    {
                        //读取托盘码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.PLC24, "D5000", 10);
                        if (trayBytesResult.IsSuccess)
                        {

                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            traycode = traycode.Replace("?", "");
                            traycode = traycode.Replace("\0", "");
                            _log.Info($"托盘离开-RFID03-托盘号-[{traycode}]");
                            GlobalVar.Connect2Entity.PassQuantity++;
                            //计算真空箱1停留时长: time3 - time2
                            string time3 = trayBindingService.GetTimeByTrayCode(traycode, "3");
                            string time2 = trayBindingService.GetTimeByTrayCode(traycode, "2");
                            ushort spanSecond = 0;
                            if (!string.IsNullOrEmpty(time3) && !string.IsNullOrEmpty(time2))
                            {
                                TimeSpan span = Convert.ToDateTime(time3) - Convert.ToDateTime(time2);
                                spanSecond = (ushort)span.TotalSeconds;
                                GlobalVar.Connect2Entity.CycleTime = spanSecond;
                                _log.Info($"烤炉停留时长: [{spanSecond}]秒");
                            }
                            bool res = _plc.PlcWrite(_plc.PLC24, "D810", spanSecond, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID03 发送烤炉停留时长 PLC写入异常");
                            }

                            res = false;

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.PLC24, "D800", 3004, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID03 发送烤炉停留时长 PLC写入完成信号异常");
                            }

                            Task.Run(() =>
                            {
                                //取出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");
                                }
                                var data = unitsProcessPLCDataGetBusiness.OvenPlcDataGet();
                                _log.Info($"隧道炉数据 — " +
                                    $"隧道炉1温度设定值:{data.CureOven1SetValue} 隧道炉2温度设定值:{data.CureOven2SetValue} " +
                                    $"隧道炉1温度实际值:{data.CureOven1ActValue} 隧道炉2温度实际值:{data.CureOven2ActValue}");
                                ConnectOven.PublishEvent(new CFXEnvelope(unitsProcessedEvent.Handle(tid, cfxUnitProcessedDataGet.ProcessDataGetOven(data))));
                                _log.Info("===================================================================================");
                            });
                        }
                        else
                        {
                            _log.Error($"PLC读取失败，原因：{trayBytesResult.Message}");
                        }


                    }
                }
                else
                {
                    _log.Error($"隧道炉外PLC读取信号异常,原因：{signalRes.Message}");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID03业务出现异常", ex);
            }
        }
    }
}
