using Admin.Core.IService;
using Admin.Core.Model;
using Aucma.Core.HwPLc;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;

namespace Aucma.Core.OldBoxFoam.Business
{
    /// <summary>
    /// 班组信息切换
    /// </summary>
    public class TeamSwitchBusiness
    {
        private readonly log4net.ILog log = LogManager.GetLogger(typeof(TeamSwitchBusiness));

        private readonly IBoxFoamPlanServices _boxFoamPlanServices;
        private readonly IBoxFoamDataServices _oldBoxFoamDataServices;
        private readonly IBoxFoamDataRecordServices _boxFoamDataRecordServices;
        public TeamSwitchBusiness()
        {
            _boxFoamPlanServices = App.ServiceProvider.GetService<IBoxFoamPlanServices>();

            _oldBoxFoamDataServices = App.ServiceProvider.GetService<IBoxFoamDataServices>();

            _boxFoamDataRecordServices = App.ServiceProvider.GetService<IBoxFoamDataRecordServices>();
        }

        public void Init()
        {

            DayShiftInfoCut();
            NightShiftInfoCut();
        }

        /// <summary>
        /// 白班信息切换
        /// </summary>
        private void DayShiftInfoCut()
        {
            DateTime now = DateTime.Now;

            DateTime scheduledTime = new DateTime(now.Year, now.Month, now.Day, 08, 00, 00);

            if (now > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }
            TimeSpan timeToGo = scheduledTime - now;
            int dueTime = (int)timeToGo.TotalMilliseconds;

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += DayShiftTimerCallback;
            timer.AutoReset = true;
            timer.Interval = dueTime;
            timer.Start();
        }

        private void DayShiftTimerCallback(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("切换为白班!");

            UpdateShiftInfo(1);

            #region 重新定义Timer,进行第二天执行
            DateTime now = DateTime.Now;

            DateTime scheduledTime = new DateTime(now.Year, now.Month, now.Day, 08, 00, 00);

            if (now > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }

            TimeSpan timeToGo = scheduledTime - now;
            int dueTime = (int)timeToGo.TotalMilliseconds;

            System.Timers.Timer timer = (System.Timers.Timer)sender;
            timer.Elapsed += DayShiftTimerCallback;
            timer.AutoReset = true;
            timer.Interval = dueTime;
            timer.Start();
            #endregion
        }

        /// <summary>
        /// 夜班班组切换
        /// </summary>
        private void NightShiftInfoCut()
        {
            DateTime now = DateTime.Now;

            DateTime scheduledTime = new DateTime(now.Year, now.Month, now.Day, 20, 00, 00);

            if (now > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }
            TimeSpan timeToGo = scheduledTime - now;
            int dueTime = (int)timeToGo.TotalMilliseconds;

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += NightShiftTimerCallback;
            timer.AutoReset = true;
            timer.Interval = dueTime;
            timer.Start();
        }

        private void NightShiftTimerCallback(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("切换为夜班!");

            UpdateShiftInfo(2);

            #region 重新定义Timer,进行第二天执行
            DateTime now = DateTime.Now;

            DateTime scheduledTime = new DateTime(now.Year, now.Month, now.Day, 20, 00, 00);

            if (now > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }

            TimeSpan timeToGo = scheduledTime - now;
            int dueTime = (int)timeToGo.TotalMilliseconds;

            System.Timers.Timer timer = (System.Timers.Timer)sender;
            timer.Elapsed += NightShiftTimerCallback;
            timer.AutoReset = true;
            timer.Interval = dueTime;
            timer.Start();
            #endregion
        }

        /// <summary>
        /// 班组切换
        /// </summary>
        /// <param name="shiftType">班组类型:1-白班;2-夜班</param>
        private void UpdateShiftInfo(int shiftType)
        {
            log.Warn($"{(shiftType == 1 ? "白班" : "夜班")}班组切换,开始处理切换逻辑");
            try
            {
                //下发PLC清空产量信号
                #region 清空PLC产量,写1保持500毫秒后写0
                ClearPlcOutPut("1");
                Thread.Sleep(500);
                ClearPlcOutPut("0");
                #endregion

                //小时统计报表数据存至记录表,清空小时统计报表

                var hourDataList = _oldBoxFoamDataServices.Query(x => x.ProductLineCode == "CX_01" && x.StationCode == "1105");
                List<BoxFoamDataRecord> hourRecordList = new List<BoxFoamDataRecord>();
                if (hourDataList != null)
                {
                    foreach (var item in hourDataList)
                    {
                        BoxFoamDataRecord hourRecord = new BoxFoamDataRecord();
                        hourRecord.OrderCode = item.OrderCode;
                        hourRecord.ProductLineCode = item.ProductLineCode;
                        hourRecord.Fixturestatus = item.Production;
                        hourRecord.CuringTimeSettingValue = item.CuringTimeSettingValue;
                        hourRecord.ActualValue = item.ActualValue;
                        hourRecord.AnHour = item.AnHour;
                        hourRecord.TwoHour = item.TwoHour;
                        hourRecord.ThreeHour = item.ThreeHour;
                        hourRecord.FourHour = item.FourHour;
                        hourRecord.FiveHour = item.FiveHour;
                        hourRecord.SixHour = item.SixHour;
                        hourRecord.SevenHour = item.SevenHour;
                        hourRecord.EightHour = item.EightHour;
                        hourRecord.NineHour = item.NineHour;
                        hourRecord.TenHour = item.TenHour;
                        hourRecord.ElevenHour = item.ElevenHour;
                        hourRecord.TwelveHour = item.TwelveHour;
                        hourRecord.BoxFixturesideplate = item.BoxFixturesideplate;
                        hourRecord.BoxClosebetatemperature = item.BoxClosebetatemperature;
                        hourRecord.BoxBeat = item.BoxBeat;
                        hourRecord.CreateTime = DateTime.Now;
                        hourRecordList.Add(hourRecord);

                        bool deleteFlag = _oldBoxFoamDataServices.DeleteAsync(item).Result;
                        if (deleteFlag)
                        {
                            log.Warn($"{item.Fixtureboxtype}:小时数据清除成功");
                        }
                        else
                        {
                            log.Warn($"{item.Fixtureboxtype}:小时数据清除失败");
                        }
                    }
                }
                int addFlag = _boxFoamDataRecordServices.AddAsync(hourRecordList).Result;
                if (addFlag > 0)
                {
                    log.Warn("班组切换小时数据记录保存成功");
                }
                else
                {
                    log.Warn("班组切换小时数据记录保存失败");
                }
                //当班计划,班组计划设为0
                var planInfoList = _boxFoamPlanServices.QueryAsync(x => x.ProductLineCode == "CX_01" && x.StationCode == "1105" && x.ShiftType == 1).Result;

                if (planInfoList != null)
                {
                    foreach (var plan in planInfoList)
                    {

                        plan.ShiftType = 0;

                        bool updateFlag = _boxFoamPlanServices.UpdateAsync(plan).Result;
                        if (updateFlag)
                        {
                            log.Warn($"计划:{plan.OrderCode},班组切换标识更新成功");

                            if (plan.PlanAmount > plan.CompleteAmount)
                            {
                                plan.PlanAmount = plan.PlanAmount - plan.CompleteAmount;
                                plan.CompleteAmount = 0;
                                plan.ShiftType = 1;

                                int saveFlag = _boxFoamPlanServices.AddAsync(plan).Result;
                                if (saveFlag > 0)
                                {
                                    log.Warn($"计划:{plan.OrderCode},剩余计划:{plan.PlanAmount},未完成进行顺延,执行成功");
                                }
                                else
                                {
                                    log.Warn($"计划:{plan.OrderCode},剩余计划:{plan.PlanAmount},未完成进行顺延,执行失败");
                                }
                            }
                        }
                        else
                        {
                            log.Warn($"计划:{plan.OrderCode},班组切换标识更新失败");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Warn($"{(shiftType == 1 ? "白班" : "夜班")}班组切换,切换逻辑处理异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 清空PLC产量数据
        /// </summary>
        /// <param name="value"></param>
        private void ClearPlcOutPut(string value)
        {
            var obj1 = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("OldMelsecPlc1"));
            if (obj1 != null)
            {
                if (obj1.plc.IsConnected)
                {
                    var flag = obj1.plc.WriteInt16("M216", value);//换班 数据清空
                    log.Warn($"班组切换清空A区产量数据写{value}:{(flag == true ? "成功" : "失败")}");
                }
            }
            var obj2 = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("OldMelsecPlc2"));
            if (obj2 != null)
            {
                if (obj2.plc.IsConnected)
                {
                    bool flag = obj2.plc.WriteInt16("M216", value);//换班 数据清空
                    log.Warn($"班组切换清空B区产量数据写{value}:{(flag == true ? "成功" : "失败")}");
                }
            }
            var obj3 = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("OldMelsecPlc3"));
            if (obj3 != null)
            {
                if (obj3.plc.IsConnected)
                {
                    var flag = obj3.plc.WriteInt16("M216", value);//换班 数据清空
                    log.Warn($"班组切换清空C区产量数据写{value}:{(flag == true ? "成功" : "失败")}");
                }
            }
            var obj4 = PlcHelper.melsecList.FirstOrDefault(d => d.EquipName.Equals("OldMelsecPlc4"));
            if (obj4 != null)
            {
                if (obj4.plc.IsConnected)
                {
                    var flag = obj4.plc.WriteInt16("M216", value);//换班 数据清空
                    log.Warn($"班组切换清空D区产量数据写{value}:{(flag == true ? "成功" : "失败")}");
                }
            }
        }
    }
}