using HslCommunication;
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.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;

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

        /// <summary>
        /// RFID01上料提升机数据处理流程业务刷新
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            // 定时任务逻辑
            //读取信号
            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", 20);
                    OperateResult<byte[]> pordBytesResult = _plc.ReadBytes(_plc.DeltaInstance3, "D8000", 120);
                    //成功验证
                    if (trayBytesResult.IsSuccess && pordBytesResult.IsSuccess)
                    {
                        //转换托盘码
                        string traycode = Encoding.ASCII.GetString(trayBytesResult.Content);

                        byte[] prodBytes = trayBytesResult.Content;
                        string[] prodcode = new string[6];
                        //分割转换产品码
                        for (int i = 0; i < 6; i++)
                        {
                            prodcode[i] = Encoding.ASCII.GetString(prodBytes[(i * 20)..(i * 20 + 20)]);
                        }
                        //sql更新
                        bool res = TrayBindingService.Instance.TrayBindingRefresh(traycode, prodcode);
                        if (!res)
                        {
                            _log.Error("上料提升机数据库写入异常");
                        }
                        //写入完成信号
                        res = _plc.PlcWrite(_plc.DeltaInstance3, "D500", 1002, DataTypeEnum.UInt16).IsSuccess;
                        if (!res)
                        {
                            _log.Error("上料提升机PLC写入完成信号异常");
                        }
                    }
                    //流程完成
                }
            }
            else
            {
                _log.Error("上料提升机PLC读取信号异常");
            }
        }
    }
}
