using SlnMesnac.Business.@base;
using SlnMesnac.Model.dto;
using SlnMesnac.Plc;
using SlnMesnac.Repository;
using SlnMesnac.Repository.service;
using SlnMesnac.Serilog;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.Business
* 唯一标识：2202e7a9-f41e-4b59-b139-05f10987e114
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-11-29 10:58:14
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business
{
    public class FixedPointBusiness : BaseBusiness
    {
        private readonly Irecord_busbar_tempServices _record_busbar_TempServices;

        public FixedPointBusiness(Irecord_busbar_tempServices record_busbar_TempServices, IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _record_busbar_TempServices = record_busbar_TempServices;
        }


        public void StartFixedPoint(base_busbar_info busbarInfo)
        {
            try
            {
                Task.Run(() =>
                {
                    isFlag = true;

                    Task.Delay(1000).Wait();

                    base.InitEquip(3); //判断PLC状态，下发工作模式

                    if (!isFlag)
                    {
                        _log.Info($"定点巡检取消");
                        return;
                    }

                    SendTrackMotorAddress(busbarInfo);

                    isFlag = false;

                    _log.Info($"定点巡检结束");
                });
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"自动巡检逻辑处理异常:{ex.Message}");
            }
        }

        public void EndFixedPoint(base_busbar_info busbarInfo,bool isClose = false)
        {

            if (isClose)
            {
                _log.Info($"定点巡检取消");
                isFlag = false;
                return;
            }

            if (busbarInfo.isRotate == 1)
            {
                GimbaRotationControlEvent?.Invoke("20", "4", "10");
            }

            if (!_plc.writeInt32ByAddress("VD1512", 1)) //母排检测完成下发检测完成信号，升降电机可以回到原位等待
            {
                throw new ArgumentException($"定点巡检模式下发检测完成信号写入失败；VD1512写1");
            }
            _log.Info($"定点巡检模式下发检测完成信号写入PLC成功；VD1512写1");
            //_log.Info($"定点巡检结束");

        }


        /// <summary>
        /// 下发轨道电机位置编号
        /// </summary>
        /// <param name="item"></param>
        /// <exception cref="ArgumentException"></exception>
        private void SendTrackMotorAddress(base_busbar_info busbarInfo)
        {
            if (!_plc.writeInt32ByAddress("VD1520", (int)busbarInfo.cabinetCode)) //下发电柜编号，通知轨道电机前往指定电柜位置
            {
                throw new ArgumentException($"定点巡检模式下发轨道电机前往指定位置编号写入失败；VD1520写{(int)busbarInfo.cabinetCode}");
            }
            _log.Info($"定点巡检模式下发轨道电机前往指定位置成功；VD1520写{(int)busbarInfo.cabinetCode}");

            this.AwaitArriveSignal("VD1528"); //等待轨道相机到位信号

            if (!isFlag)
            {
                return;
            }

            this.SendLiftMotorDict(busbarInfo);

        }

        /// <summary>
        /// 等待PLC到位信号
        /// </summary>
        /// <param name="signal"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private void AwaitArriveSignal(string signal)
        {
            try
            {
                bool is_arrive = true;
                while (is_arrive)
                {
                    if (!isFlag)
                    {
                        break;
                    }

                    int rewrite = _plc.readInt32ByAddress("VD1554");
                    if (rewrite == 1)
                    {
                        _plc.writeInt32ByAddress("VD1554", 0);
                        if (!_plc.writeInt32ByAddress("VD1536", 3)) //工作模式:1-自动；2-巡检；3-手动
                        {
                            throw new ArgumentException($"VD1554为1重新写入工作模式:自动模式；写入PLC失败；VD1536写3");
                        }

                        _log.Info($"VD1554为1重新写入工作模式:自动模式；写入PLC成功；VD1536写3");
                    }

                    int is_arrive_flag = _plc.readInt32ByAddress(signal); //读取PLC轨道电机到位信号
                    if (is_arrive_flag == 1)
                    {
                        _log.Info($"PLC已到达指定位置；{signal}值为{is_arrive_flag}");
                        if (!_plc.writeInt32ByAddress(signal, 0))
                        {
                            throw new ArgumentException($"PLC到位信号复位失败；{signal}写0");
                        }

                        is_arrive = false;

                        continue;
                    }

                    _log.Info($"等待PLC前往指定位置；{signal}值为{is_arrive_flag}");

                    Task.Delay(1000).Wait();
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"等待到位信号处理异常:{e.Message}");
            }
        }

        public readonly RealTemperatureInfo _realTemperatureInfo = new RealTemperatureInfo();

        public delegate void GimbaRotationControl(string wPanPos, string wTiltPos, string wZoomPos);
        public event GimbaRotationControl GimbaRotationControlEvent;

        public delegate void CaptureAlarmPicture(string sJpegPicFileName);
        public event CaptureAlarmPicture CaptureAlarmPictureEvent;


        private void SendLiftMotorDict(base_busbar_info busbar)
        {
            if (!_plc.writeFloatByAddress("VD1524", ((float)busbar.busbarDist))) //下发母排距离，升降电机升降的距离
            {
                throw new ArgumentException($"下发母排升降距离写入失败；VD1524写{busbar.cabinetCode}");
            }
            _log.Info($"下发母排升降距离成功；VD1524写{busbar.busbarDist}");

            this.AwaitArriveSignal("VD1504");  //等待升降电机到位信号

            if (!isFlag)
            {
                return;
            }

            //控制云台旋转
            if (busbar.isRotate == 1)
            {
                GimbaRotationControlEvent?.Invoke(busbar.wPanPos, busbar.wTiltPos, busbar.wZoomPos);
            }

            _log.Info($"2S后开始测温");
            Task.Delay(2000).Wait();
            _log.Info($"温度测量完成，最高温度:{_realTemperatureInfo.fMaxTemperature};最低温度:{_realTemperatureInfo.fMinTemperature};平均温度:{_realTemperatureInfo.fAverageTemperature};温差:{_realTemperatureInfo.fTemperatureDiff}");
            this.SaveBusbarTemp(busbar.busbarCode, busbar.cabinetCode, _realTemperatureInfo, busbar.isPictures);
        }

        /// <summary>
        /// 保存母排测温数据
        /// </summary>
        /// <param name="busbarCode"></param>
        /// <param name="cabinetCode"></param>
        /// <param name="realTemperatureInfo"></param>
        private void SaveBusbarTemp(int? busbarCode, int? cabinetCode, RealTemperatureInfo realTemperatureInfo, int isPictures)
        {
            try
            {

                var record = new record_busbar_temp()
                {
                    busbarCode = busbarCode,
                    cabinetCode = cabinetCode,
                    tempMax = (decimal)realTemperatureInfo.fMaxTemperature,
                    tempMin = (decimal)realTemperatureInfo.fMinTemperature,
                    tempAvg = (decimal)realTemperatureInfo.fAverageTemperature,
                    tempDiff = (decimal)realTemperatureInfo.fTemperatureDiff,
                    routModel = 3,
                    recordTime = DateTime.Now,
                };

                //if (realTemperatureInfo.fMaxTemperature > 65)
                //{
                //    record.isAlarm = 1;
                //    string sJpegPicFileName = $"{cabinetCode}_{busbarCode}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.jpg";
                //    record.filePath = sJpegPicFileName;
                //    CaptureAlarmPictureEvent?.Invoke(sJpegPicFileName);
                //}
                //else
                //{
                //    if (isPictures == 1)
                //    {
                //        string sJpegPicFileName = $"{cabinetCode}_{busbarCode}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.jpg";
                //        record.filePath = sJpegPicFileName;
                //        CaptureAlarmPictureEvent?.Invoke(sJpegPicFileName);
                //    }
                //}

                string sJpegPicFileName = $"{cabinetCode}_{busbarCode}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.jpg";
                record.filePath = sJpegPicFileName;
                CaptureAlarmPictureEvent?.Invoke(sJpegPicFileName);

                base.JudgBusbarIsAlarm((int)busbarCode, ref record);

                var res = _record_busbar_TempServices.Insert(record);

                if (res)
                {
                    _log.Info($"{cabinetCode}号电柜{busbarCode}排数据保存成功");
                }
                else
                {
                    _log.Info($"{cabinetCode}号电柜{busbarCode}排数据保存失败");
                }
            }
            catch (Exception e)
            {
                _log.Info($"{cabinetCode}号电柜{busbarCode}排数据保存异常:{e.Message}");
            }
        }

    }
}
