using CFX;
using CFX.Structures.UVCuring;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
using Sln.Iot.PLC;
using Sln.Iot.Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sln.Iot.Business
{
    /// <summary>
    /// 配方支持类
    /// </summary>
    public class RecipeBusiness
    {
        private Timer _timer;

        private readonly PLCConnect _plc = PLCConnect.Instance;
        private readonly SerilogHelper _log = SerilogHelper.Instance;

        private readonly RecipeActivatedEvent recipeActivatedEvent = new RecipeActivatedEvent();
        private readonly RecipeModifiedEvent recipeModifiedEvent = new RecipeModifiedEvent();

        private readonly CFXConnectVacuum connect1 = CFXConnectVacuum.Instance;

        public RecipeBusiness()
        {
            _timer = new Timer(TimerCallback, null, 0, 5000);
        }

        /// <summary>
        /// 检测配方变化
        /// </summary>
        /// <param name="state"></param>
        public void TimerCallback(object? state)
        {
            string recipeName1 = "recipeName";
            try
            {
                var Result1 = _plc.ReadInt16(_plc.PLC21, "D8");

                //_log.Info($"真空箱1配方标识{Result1.Content}");
                //_log.Info($"真空箱2配方标识{Result2.Content}");
                //_log.Info($"————————————————————");

                if (Result1.Content != 0)
                {
                    //获取现在激活的配方
                    var res1 = _plc.ReadBytes(_plc.PLC21, "D12600", 10);
                    if (res1.IsSuccess)
                    {
                        recipeName1 = Encoding.ASCII.GetString(ToolBusiness.SwapAdjacentBytes(res1.Content));
                    }
                }

                if (Result1.IsSuccess)
                {
                    if (Result1.Content == 2)
                    {
                        //发布消息
                        connect1.PublishEvent(new CFXEnvelope(recipeModifiedEvent.Handle(recipeName1)));
                        _plc.PlcWrite(_plc.PLC21, "D8", 0, DataTypeEnum.Int16);
                        _log.Info($"真空箱1配方修改{recipeName1}");
                    }
                    else if (Result1.Content == 4)
                    {
                        //发布消息
                        connect1.PublishEvent(new CFXEnvelope(recipeActivatedEvent.Handle(recipeName1, "vacuum", 1)));
                        _plc.PlcWrite(_plc.PLC21, "D8", 0, DataTypeEnum.Int16);
                        _log.Info($"真空箱1配方激活{recipeName1}");
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error($"RecipeBusiness定时任务异常：{ex.Message}");
            }
        }
    }
}
