using Microsoft.Extensions.DependencyInjection;
using Serilog;
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.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.Business.base
* 唯一标识：b00d95c1-a164-43a3-9f34-2a5d2efb3f34
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-12 17:36:19
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business.@base
{
    public class BaseBusiness
    {
        public readonly SerilogHelper _log;

        public readonly PlcAbsractFactory _plc;

        public readonly RealTemperatureInfo _realTemperatureInfo;

        private readonly WebSocketBusiness _webSocketBusiness;

        private IServiceProvider _serviceProvider;

        public readonly Ibase_cabinet_infoServices _ibase_Cabinet_InfoServices;
        public readonly Ibase_busbar_infoServices _ibase_Busbar_InfoServices;
        private readonly Ibase_alarm_infoServices _ibase_Alarm_InfoServices;
        private readonly Irecord_busbar_alarmServices _iRecord_Busbar_AlarmServices;
        public bool isFlag = false;

        public BaseBusiness(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;

            using (var scope = _serviceProvider.CreateScope())
            {
                _log = scope.ServiceProvider.GetRequiredService<SerilogHelper>();
                _plc = scope.ServiceProvider.GetRequiredService<PlcAbsractFactory>();
                _realTemperatureInfo = scope.ServiceProvider.GetRequiredService<RealTemperatureInfo>();
                _ibase_Cabinet_InfoServices = scope.ServiceProvider.GetRequiredService<Ibase_cabinet_infoServices>();
                _ibase_Busbar_InfoServices = scope.ServiceProvider.GetRequiredService<Ibase_busbar_infoServices>();
                _ibase_Alarm_InfoServices = scope.ServiceProvider.GetRequiredService<Ibase_alarm_infoServices>();
                _iRecord_Busbar_AlarmServices = scope.ServiceProvider.GetRequiredService<Irecord_busbar_alarmServices>();

                _webSocketBusiness = scope.ServiceProvider.GetRequiredService<WebSocketBusiness>();
            }
            
        }

        /// <summary>
        /// 初始化轨道电机
        /// </summary>
        /// <param name="model">工作模式:1-自动；2-巡检；3-手动</param>
        /// <exception cref="InvalidOperationException"></exception>
        public async void InitEquip(int model)
        {
            try
            {
                int plcFlag = 0;
                do
                {

                    if (!isFlag)
                    {
                        break;
                    }

                    plcFlag = _plc.readInt32ByAddress("VD1508"); //PLC状态
                    if (plcFlag != 1)
                    {
                        _log.Info($"PLC状态不具备启动条件:VD1508值为{plcFlag}");
                        Task.Delay(1000).Wait();
                        continue;
                    }

                    if (!_plc.writeInt32ByAddress("VD1536", model)) //工作模式:1-自动；2-巡检；3-手动
                    {
                        throw new ArgumentException($"工作模式:自动模式；写入PLC失败；VD1536写{model}");
                    }

                    _log.Info($"工作模式写入PLC成功；VD1536写{model}");

                } while (plcFlag != 1);

            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"初始化轨道电机异常:{e.Message}");
            }
        }

        /// <summary>
        /// 获取电柜信息
        /// </summary>
        /// <param name="cabinetInfos"></param>
        public void GetCabinetInfos(int equipAddr,out List<base_cabinet_info> cabinetInfos)
        {
            var list = _ibase_Cabinet_InfoServices.Query(x=>x.isChecked == 1 && x.isFlag == 1).ToList();

            if (equipAddr > 20) //20 号柜子之后倒叙巡检
            {
                cabinetInfos = list.OrderByDescending(x => x.cabinetCode).ToList();
            }
            else   //右侧原点，倒序巡检
            {
                cabinetInfos = list.OrderBy(x => x.cabinetCode).ToList();
            }
        }

        /// <summary>
        /// 获取指定电柜下的母排信息
        /// </summary>
        /// <param name="cabinetCode"></param>
        /// <param name="busbarInfos"></param>
        public void GetBusbarInfos(int cabinetCode,out List<base_busbar_info> busbarInfos,int isInsp = 0)
        {
            busbarInfos = _ibase_Busbar_InfoServices.Query(x=>x.cabinetCode == cabinetCode && x.isChecked == 1 && x.isInsp == isInsp).ToList();
        }

        public void JudgBusbarIsAlarm(int busbarCode,ref record_busbar_temp busbarTemp)
        {
            try
            {
                var alarmInfos = _ibase_Alarm_InfoServices.Query(x => x.busbarCode == busbarCode).ToList();

                if (alarmInfos != null)
                {
                    foreach (var alarm in alarmInfos)
                    {
                        record_busbar_alarm busbarAlarm = new record_busbar_alarm();
                        if (alarm.judgMethod == 1) //大于
                        {
                            if (busbarTemp.tempMax < alarm.alarmValue) //取反为正常数据
                            {
                                continue;
                            }
                        }
                        else if (alarm.judgMethod == 2)  //小于
                        {
                            if (busbarTemp.tempMax > alarm.alarmValue)  //取反为正常数据
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }

                        busbarAlarm.busbarCode = busbarTemp.busbarCode;
                        busbarAlarm.cabinetCode = busbarTemp.cabinetCode;
                        busbarAlarm.tempMax = busbarTemp.tempMax;
                        busbarAlarm.tempMin = busbarTemp.tempMin;
                        busbarAlarm.tempAvg = busbarTemp.tempAvg;
                        busbarAlarm.tempDiff = busbarTemp.tempDiff;
                        busbarAlarm.filePath = busbarTemp.filePath;
                        busbarAlarm.alarmType = alarm.alarmType;
                        busbarAlarm.alarmValue = alarm.alarmValue;
                        busbarAlarm.recordTime = DateTime.Now;
                        _iRecord_Busbar_AlarmServices.Insert(busbarAlarm);

                        busbarTemp.isAlarm = 1;

                        _webSocketBusiness.Encapsulation(true,alarm,busbarAlarm);


                    }
                }
            }
            catch(Exception e)
            {
                throw new InvalidOperationException($"测温数据判断异常:{e.Message}");
            }
        }
    }
}
