using CFX;
using CFX.Structures;
using HslCommunication;
using Sln.Iot.CFX.CFXBusiness;
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;

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

        private readonly PLCConnect _plc = PLCConnect.Instance;

        private readonly SerilogHelper _log = SerilogHelper.Instance;


        //CFX数据采集业务
        private UnitsProcessPLCDataGetBusiness unitsProcessPLCDataGetBusiness = UnitsProcessPLCDataGetBusiness.Instance;
        private CFXUnitProcessedDataGet cFXUnitProcessedDataGet = CFXUnitProcessedDataGet.Instance;

        //SQL服务
        private OvenPlcDataService ovenPlcDataService = OvenPlcDataService.Instance;
        private VacuumInjectionPlcDataService vacuumInjectionPlcDataService = VacuumInjectionPlcDataService.Instance;
        private TrayBindingService trayBindingService = TrayBindingService.Instance;

        //CFX事件
        private UnitsDepartedEvent unitsDepartedEvent = new UnitsDepartedEvent();
        private WorkStageCompletedEvent workStageCompletedEvent = new WorkStageCompletedEvent();
        private UnitsProcessedEvent unitsProcessedEvent = new UnitsProcessedEvent();
        private WorkCompletedEvent workCompletedEvent = new WorkCompletedEvent();

        // CFX连接
        private CFXConnect1 connect1 = CFXConnect1.Instance;
        private CFXConnect2 connect2 = CFXConnect2.Instance;
        private CFXConnect3 connect3 = CFXConnect3.Instance;

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

        /// <summary>
        /// RFID06下料提升机数据处理流程
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            try
            {
                // 定时任务逻辑
                //读取信号
                OperateResult<short> signalRes = _plc.ReadInt16(_plc.DeltaInstance4, "D500");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    //如果有读取信号
                    if (signalValue == 6001)
                    {
                        //读取托盘码和产品码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.DeltaInstance4, "D5000", 10);
                        //成功验证
                        if (trayBytesResult.IsSuccess)
                        {
                            //转换托盘吗
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            _log.Info("RFID06" + traycode);

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

                            //待开发
                            string[] prodcode = trayBindingService.ProdCodeGet(traycode);

                            bool res = trayBindingService.TrayCodeDelete(traycode);

                            if (!res)
                            {
                                _log.Error("下料提升机绑定数据删除异常或删除条数为0");
                            }

                            //写入完成信号
                            res = _plc.PlcWrite(_plc.DeltaInstance4, "D500", 6002, DataTypeEnum.UInt16).IsSuccess;
                            if (!res)
                            {
                                _log.Error("下料提升机PLC写入完成信号异常");
                            }

                            //CFX
                            Task.Run(() =>
                            {
                                //固化炉工段完成事件
                                connect3.PublishEvent(new CFXEnvelope(workStageCompletedEvent.Handle(tid, "CureOven", 3)));
                                _log.Info($"固化炉工段完成, {tid}");
                                //单元离站事件
                                connect2.PublishEvent(new CFXEnvelope(unitsDepartedEvent.Handle(traycode, prodcode)));
                                _log.Info($"{traycode} 单元离站 ");
                                //工单完成事件
                                connect2.PublishEvent(new CFXEnvelope(workCompletedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"工单完成 ID:{tid}");

                                //固化炉数据采集
                                var unitsdata = unitsProcessPLCDataGetBusiness.CureOvenPlcDataGet();
                                //存数据库里整合
                                ovenPlcDataService.UpdateDataCure(stid, unitsdata);
                                //取出整合数据
                                unitsdata = ovenPlcDataService.GetData(stid);

                                connect3.PublishEvent(new CFXEnvelope(unitsProcessedEvent.Handle(tid, cFXUnitProcessedDataGet.ProcessDataGet3(unitsdata))));
                                _log.Info($"隧道烤箱温度数据上传, " +
                                           $"PreheatOvenTempActValue:{unitsdata.PreheatOvenTempActValue} " +
                                           $"PreCureOven1TempActValue:{unitsdata.PreCureOven1TempActValue} " +
                                           $"PreCureOven2TempActValue:{unitsdata.PreCureOven2TempActValue} " +
                                           $"PreCureOven3TempActValue:{unitsdata.PreCureOven3TempActValue} " +
                                           $"PreCureOven4TempActValue:{unitsdata.PreCureOven4TempActValue} " +
                                           $"CureOven1TempActValue:{unitsdata.CureOven1TempActValue} " +
                                           $"CureOven2TempActValue:{unitsdata.CureOven2TempActValue} " +
                                           $"CureOven3TempActValue:{unitsdata.CureOven3TempActValue} " +
                                           $"CureOven4TempActValue:{unitsdata.CureOven4TempActValue} ");
                            });
                        }
                        //流程完成
                    }
                }
                else
                {
                    _log.Error("下料提升机PLC读取信号异常");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID0业务出现异常", ex);
            }
            
        }
    }
}
