using CFX;
using HslCommunication;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
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 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 VacuumInjectionPlcDataService vacuumInjectionPlcDataService = VacuumInjectionPlcDataService.Instance;

        private UnitsProcessPLCDataGetBusiness unitsProcessPLCDataGetBusiness = UnitsProcessPLCDataGetBusiness.Instance;

        private WorkStageStartedEvent workStageStartedEvent = new WorkStageStartedEvent();
        private WorkStageCompletedEvent workStageCompletedEvent = new WorkStageCompletedEvent();
        private CFXConnect1 connect1 = CFXConnect1.Instance;
        private CFXConnect2 connect2 = CFXConnect2.Instance;
        private CFXConnect3 connect3 = CFXConnect3.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.DeltaInstance1, "D800");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    //如果有读取信号
                    if (signalValue == 2001)
                    {
                        //读取托盘码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.DeltaInstance1, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {
                            //转换托盘码
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            _log.Info("RFID02" + traycode);

                            //sql更新

                            //待开发 记录数据
                            //取出work唯一guid(tid)
                            string stid = trayBindingService.TidGet(traycode);
                            Guid.TryParse(stid, out Guid tid);

                            bool res = false;
                            if (!res)
                            {
                                _log.Error("胶机1真空箱内数据库写入异常");
                            }

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.DeltaInstance1, "D800", 2002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("胶机1真空箱内写入完成信号异常");
                            }

                            //CFX
                            Task.Run(() =>
                            {
                                //预热炉工段完成事件
                                connect3.PublishEvent(new CFXEnvelope(workStageCompletedEvent.Handle(tid, "PreHeatOven", 1)));
                                _log.Info($"预热炉工段完成 ID:{tid}");
                                //真空箱1工段开启
                                connect1.PublishEvent(new CFXEnvelope(workStageStartedEvent.Handle(tid, "VacuumInjection1", 1)));
                                _log.Info($"真空箱1工段开始 ID:{tid}");


                                //预热炉数据采集
                                var data = unitsProcessPLCDataGetBusiness.PreHeatOvenPlcDataGet();
                                ovenPlcDataService.InsertData(stid, data);
                                _log.Info($"预热炉数据采集, {data}");
                                //真空箱1数据采集
                                var data2 = unitsProcessPLCDataGetBusiness.Vacuum1PlcDataGet();
                                vacuumInjectionPlcDataService.InsertData(stid, data2);
                                _log.Info($"真空箱1温度数据采集, " +
                                    $"GlueAmountSetValue1:{data2.GlueAmountSetValue1} " +
                                    $"GluePushSpeedSetValue1:{data2.GluePushSpeedSetValue1} " +
                                    $"BarrelA1TempActValue1:{data2.BarrelA1TempActValue1} " +
                                    $"BarrelA2TempActValue1:{data2.BarrelA2TempActValue1} " +
                                    $"BarrelB1TempActValue1:{data2.BarrelB1TempActValue1} " +
                                    $"BarrelB2TempActValue1:{data2.BarrelB2TempActValue1} " +
                                    $"PumpAPressureActValue1:{data2.PumpAPressureActValue1} " +
                                    $"PumpBPressureActValue1:{data2.PumpBPressureActValue1} " +
                                    $"VacuumDegreeActValue1:{data2.VacuumDegreeActValue1} " +
                                    $"PressureHoldTimeSetValue1:{data2.PressureHoldTimeSetValue1}");
                            });

                            //CFX
                        }
                        //流程完成
                    }
                }
                else
                {
                    _log.Error("胶机1真空箱内PLC读取信号异常");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID02业务出现异常", ex);
            }
            
        }
    }
}
