using Amqp.Framing;
using CFX;
using CFX.Structures.PressInsertion;
using HslCommunication;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
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.Text;
using System.Threading.Tasks;

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

        private readonly PLCConnect _plc = PLCConnect.Instance;

        private readonly SerilogHelper _log = SerilogHelper.Instance;

        private UnitsArrivedEvent unitsArrivedEvent = new UnitsArrivedEvent();
        private WorkStartedEvent workStartedEvent = new WorkStartedEvent();
        private WorkStageStartedEvent workStageStartedEvent = new WorkStageStartedEvent();

        private TrayBindingService trayBindingService = TrayBindingService.Instance;
        private CFXConnect1 connect1 = CFXConnect1.Instance;
        private CFXConnect2 connect2 = CFXConnect2.Instance;
        private CFXConnect3 connect3 = CFXConnect3.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.DeltaInstance3, "D500");
                //成功验证
                if (signalRes.IsSuccess)
                {
                    short signalValue = signalRes.Content;
                    //如果有读取信号
                    if (signalValue == 1001)
                    {
                        //读取托盘码和产品码
                        OperateResult<byte[]> trayBytesResult = _plc.ReadBytes(_plc.DeltaInstance3, "D5000", 10);
                        OperateResult<byte[]> pordBytesResult = _plc.ReadBytes(_plc.DeltaInstance3, "D8000", 60);
                        //成功验证
                        if (trayBytesResult.IsSuccess && pordBytesResult.IsSuccess)
                        {
                            //转换托盘码
                            string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);
                            _log.Info("RFID01" + traycode);
                            byte[] prodBytes = pordBytesResult.Content;
                            string[] prodcode = new string[6];
                            //分割转换产品码
                            for (int i = 0; i < 6; i++)
                            {
                                prodcode[i] = Encoding.ASCII.GetString(prodBytes[(i * 20)..(i * 20 + 20)]);
                            }

                            connect1.SendValidateUnitsRequest("", traycode, prodcode);

                            //生成work唯一guid(tid)
                            Guid tid = new Guid();
                            //sql更新
                            bool res = trayBindingService.TrayBindingRefresh(tid, traycode, prodcode);
                            if (!res)
                            {
                                _log.Error("上料提升机数据库写入异常");
                            }

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

                            //CFX
                            Task.Run(() =>
                            {
                                //单元抵达事件
                                connect2.PublishEvent(new CFXEnvelope(unitsArrivedEvent.Handle(traycode, prodcode)));
                                _log.Info($"{traycode} 抵达设备");
                                //工作开始事件
                                connect2.PublishEvent(new CFXEnvelope(workStartedEvent.Handle(tid, traycode, prodcode)));
                                _log.Info($"工作开始，ID:{tid}");
                                //预热炉工段开启
                                connect3.PublishEvent(new CFXEnvelope(workStageStartedEvent.Handle(tid, "PreHeatOven", 1)));
                                _log.Info($"预热炉工段开始 ID:{tid}");
                            });
                        }
                        //流程完成
                    }
                }
                else
                {
                    _log.Error("上料提升机PLC读取信号异常");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RFID01业务出现异常", ex);
            }
        }
    }
}
