using Amqp.Framing;
using CFX;
using CFX.Structures.PressInsertion;
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;
using Sln.Iot.Repository.dao;
using Sln.Iot.Repository.service;
using Sln.Iot.Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace Sln.Iot.Business
{
    /// <summary>
    /// RFID01真空箱内
    /// </summary>
    public class RFID01Business
    {
        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 UnitsArrivedEvent unitsArrivedEvent = new UnitsArrivedEvent();
        private WorkStartedEvent workStartedEvent = new WorkStartedEvent();
        private WorkStageStartedEvent workStageStartedEvent = new WorkStageStartedEvent();
        private WorkCompletedEvent workCompletedEvent = new WorkCompletedEvent();
        private UnitsDepartedEvent unitsDepartedEvent = new UnitsDepartedEvent();
        private UnitsProcessedEvent unitsProcessedEvent = new UnitsProcessedEvent();

        private TrayBindingService trayBindingService = TrayBindingService.Instance;
        private CFXConnectVacuum connectVacuum = CFXConnectVacuum.Instance;

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

        /// <summary>
        /// RFID01真空箱内
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            try
            {
                // 定时任务逻辑
                //读取信号
                OperateResult<short> signalRes = _plc.ReadInt16(_plc.PLC22, "D800");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    //_log.Info($"______________________________________________");
                    //_log.Info($"RFID01:{signalValue}");
                    //如果有读取信号
                    if (signalValue == 1001)
                    {
                        //读取托盘码和产品码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.PLC22, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {

                            //转换托盘码
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            traycode = traycode.Replace("?", "");
                            traycode = traycode.Replace("\0", "");
                            _log.Info($"托盘到达-RFID01-托盘号-[{traycode}]");

                            //记录预热炉到达时间
                            trayBindingService.UpDateTime(DateTime.Now.ToString(), traycode, "1");

                            //写入完成信号
                            bool res = _plc.PlcWrite(_plc.PLC22, "D800", 1002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID01 读电子标签 PLC写入完成信号异常");
                            }

                            //取出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(unitsArrivedEvent.Handle(traycode, prodcode)));
                                //工作开始事件
                                connectVacuum.PublishEvent(new CFXEnvelope(workStartedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"工作开始，ID:{tid}");
                                //真空箱工段开启
                                connectVacuum.PublishEvent(new CFXEnvelope(workStageStartedEvent.Handle(tid, "vacuum", 1)));
                                _log.Info($"真空箱工段开始 ID:{tid}");
                                _log.Info("===================================================================================");
                            });
                        }
                        else
                        {
                            _log.Error($"PLC读取失败，原因1：{trayBytesResult.Message} ");
                        }
                        //流程完成
                    }
                    else if (signalValue == 1003)
                    {
                        //读取托盘码
                        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($"托盘离开-RFID01-托盘号-[{traycode}]");

                            GlobalVar.Connect1Entity.InputQuantity++;

                            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.VacuumPlcDataGet();
                                _log.Info($"真空灌胶机数据 — " +
                                    $"推胶速度设定值:{data.GluePushSpeedSetValue} " +
                                    $"胶量设定值:[{data.GlueAmountSetValue1},{data.GlueAmountSetValue2},{data.GlueAmountSetValue3},{data.GlueAmountSetValue4},{data.GlueAmountSetValue5},{data.GlueAmountSetValue6},{data.GlueAmountSetValue7},{data.GlueAmountSetValue8},{data.GlueAmountSetValue9},{data.GlueAmountSetValue10}] " +
                                    $"真空度设定值:{data.VacuumDegreeSetValue} 保压时长设定值:{data.PressureHoldTimeSetValue} " +
                                    $"真空箱启用设定值:{data.VacuumIsUseSetValue} 总胶量设定值:{data.TotalGlueAmountSetValue} " +
                                    $"A泵压力实际值:{data.PumpAPressureActValue} B泵压力实际值:{data.PumpBPressureActValue} " +
                                    $"灌胶真空度实际值:{data.VacuumDegreeActValue} 配方数据:{data.FormulaData}");
                                connectVacuum.PublishEvent(new CFXEnvelope(unitsProcessedEvent.Handle(tid, cfxUnitProcessedDataGet.ProcessDataGetVacuum(data))));
                                _log.Info("===================================================================================");
                            });

                            //写入完成信号
                            bool res = _plc.PlcWrite(_plc.PLC22, "D800", 1004, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("RFID01 读胶机参数 PLC写入完成信号异常");
                            }
                        }
                    }
                }
                else
                {
                    _log.Error($"隧道炉PLC读取信号异常,原因：{signalRes.Message}");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID01业务出现异常", ex);
            }
        }
    }
}
