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.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using static System.Runtime.CompilerServices.RuntimeHelpers;

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

        private readonly PLCConnect _plc = PLCConnect.Instance;

        private readonly SerilogHelper _log = SerilogHelper.Instance;
        private OvenPlcDataService ovenPlcDataService = OvenPlcDataService.Instance;
        private VacuumInjectionPlcDataService vacuumInjectionPlcDataService = VacuumInjectionPlcDataService.Instance;

        private UnitsProcessPLCDataGetBusiness unitsProcessPLCDataGetBusiness = UnitsProcessPLCDataGetBusiness.Instance;

        private TrayBindingService trayBindingService = TrayBindingService.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 RFID04Business()
        {
            _timer = new Timer(TimerCallback, null, 0, 2000);
        }

        /// <summary>
        /// RFID04胶机2真空箱前数据处理流程
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            try
            {
                // 定时任务逻辑
                //读取信号
                OperateResult<short> signalRes = _plc.ReadInt16(_plc.DeltaInstance2, "D800");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    // 如果有读取信号
                    // 读电子标签
                    if (signalValue == 4001)
                    {
                        //读取托盘码和产品码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.DeltaInstance2, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {
                            //转换托盘吗
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            _log.Info("RFID04" + traycode);

                            //sql更新
                            //取出work唯一guid(tid)
                            string stid = trayBindingService.TidGet(traycode);
                            Guid.TryParse(stid, out Guid tid);

                            bool res = trayBindingService.UpDateTime(DateTime.Now.ToString(), traycode, "2");
                            if (!res)
                            {
                                _log.Error("胶机2真空箱前开始时间数据库写入异常");
                            }

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.DeltaInstance2, "D800", 4002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("胶机2真空箱前开始时间PLC写入完成信号异常");
                            }

                            //CFX
                            Task.Run(() =>
                            {
                                //预固炉工段完成事件
                                connect3.PublishEvent(new CFXEnvelope(workStageCompletedEvent.Handle(tid, "PreCureOven", 2)));
                                _log.Info($"预固炉工段完成, {tid}");
                                //真空箱2工段开启
                                connect1.PublishEvent(new CFXEnvelope(workStageStartedEvent.Handle(tid, "VacuumInjection2", 2)));
                                _log.Info($"真空箱2工段开启, {tid}");

                                //预固炉数据采集
                                var data = unitsProcessPLCDataGetBusiness.PreCureOvenPlcDataGet();
                                ovenPlcDataService.UpdateDataPreCure(stid, data);
                                _log.Info($"预固炉温度数据采集, " +
                                       $"PreCureOven1TempActValue:{data.PreCureOven1TempActValue} " +
                                       $"PreCureOven2TempActValue:{data.PreCureOven2TempActValue} " +
                                       $"PreCureOven3TempActValue:{data.PreCureOven3TempActValue} " +
                                       $"PreCureOven4TempActValue:{data.PreCureOven4TempActValue}");
                            });
                        }
                        //流程完成
                    }
                    // 计算时间差
                    if (signalValue == 4003)
                    {
                        //读取托盘码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.DeltaInstance2, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {
                            //转换托盘吗
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);

                            //sql更新
                            string nowTime = DateTime.Now.ToString();
                            bool res = TrayBindingService.Instance.UpDateTime(nowTime, traycode, "3");
                            if (!res)
                            {
                                _log.Error("胶机2真空箱前时间计算数据库写入异常");
                            }
                            //取之前存的时间
                            string time2 = TrayBindingService.Instance.GetTime2ByTrayCode(traycode);
                            ushort spanSecond = 0;
                            if (!time2.IsNullOrEmpty())
                            {
                                //计算时间差
                                TimeSpan span = Convert.ToDateTime(time2) - Convert.ToDateTime(nowTime);
                                spanSecond = (ushort)span.TotalSeconds;
                                _log.Info($"预固炉时间差" + spanSecond);
                            }
                            res = _plc.PlcWrite(_plc.DeltaInstance2, "D810", spanSecond, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("胶机2真空箱前时间计算结果PLC写入异常");
                            }
                            //写入完成信号
                            res = _plc.PlcWrite(_plc.DeltaInstance2, "D800", 4004, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("胶机2真空箱前时间计算PLC写入完成信号异常");
                            }
                        }
                        //流程完成
                    }
                }
                else
                {
                    _log.Error("胶机2真空箱前开始时间读PLC取信号异常");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID0业务出现异常", ex);
            }
        }
    }
}
