using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc.S7;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Khd.Core.Plc;
using System.Windows.Threading;

namespace Khd.Core.Wpf.WindowPage
{


    /// <summary>
    /// HoistWarnInfoWindow.xaml 的交互逻辑
    /// 
    /// 提升机异常处理步骤：
    /// 前置条件:提升机无报警==》PLC触摸屏有报警先复位消除报警、有急停先拔起来急停按钮（5F上电、复位、蓝色确认按钮）
    /// 1.点击删除任务按钮，删除提升机已经下发的正在执行的任务
    /// 2.选择问题楼层，不需要选择，读PLC自动判断
    /// 3.点击对应楼层步序清0，提升机状态清0
    /// 4.点击对应楼层出，将托盘出到接驳位
    /// 5.重新下发任务
    /// 
    /// </summary>
    public partial class HoistWarnHandlerWindow : Window
    {
        private readonly long T01 = 6;
        //提升机当前楼层
        private long currentFloor = 1;

        private bool taskHandlerFlag = false;

        /// <summary>
        /// 提升机当前楼层 
        /// </summary>
        private BasePlcpoint currentfloor06;
        /// <summary>
        /// 提升机步序清0
        /// </summary>
        private BasePlcpoint hoisterStepClear;

        private DispatcherTimer _timer;
        private int _timeRemaining = 30; // 初始时间为30秒


        private IHost _host;
        public HoistWarnHandlerWindow(IHost host)
        {
            _host = host;
            InitializeComponent();
            getCurrentFloor();
        }


        private void getCurrentFloor()
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            dbContext.ChangeTracker.Clear();
         
            //一楼提升机当前楼层 写
            this.currentfloor06 = SystemData.BasePlcpoints.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("currentfloor06"));
            var currentfloor06Value = SystemData.PlcDic[0].Read(this.currentfloor06.plcpointAddress);   //提升机当前楼层 读
            currentFloor = Convert.ToInt32(currentfloor06Value);
            FloorTxt.Text = currentFloor.ToString();

        }

      
        private void Window_StateChanged(object sender, System.EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                Close();
            }
        }


     
    

        /// <summary>
        /// 1.手动提升机操作到起始地楼层或目的楼层
        ///如果有任务，校验是否在起始地或者目的地楼层，不在的话校验不通过
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManualHoistButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                getCurrentFloor();
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                dbContext.ChangeTracker.Clear();
                var wcsTask = dbContext.WcsTask.Where(t => t.nextPointId == T01 && t.taskStatus > 0 && t.taskStatus <= 5).FirstOrDefault();
                if (wcsTask != null)
                {
                    if (wcsTask.currPointId != currentFloor && wcsTask.endPointId != currentFloor)
                    {
                        this.Msg.Text = DateTime.Now + " 提升机当前在" + currentFloor + "楼，需要到达起始地楼层:" + wcsTask.currPointId + " 或者到达终点楼层:" + wcsTask.endPointId;
                        this.ManualHoistButton.Background = new SolidColorBrush(Colors.Red);
                        return;
                    }
                }

                this.Msg.Text = DateTime.Now + " 手动提升机到达" + currentFloor + "楼，通过校验";
                this.ManualHoistButton.Background = new SolidColorBrush(Colors.LimeGreen);
                this.ManualHoistButton.IsEnabled = false;
                HoistClearButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                this.Msg.Text = DateTime.Now + " 校验手动提升机操作到起始地楼层或目的楼层:" + ex.Message;
                this.ManualHoistButton.Background = new SolidColorBrush(Colors.Red);

            }
        }


        /// <summary>
        /// 2.提升机步序清0，轿厢线步序清0
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HoistClear_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ///轿厢线步序清0
                this.hoisterStepClear = SystemData.BasePlcpoints.First(t => t.plcpointNo== "hoisterStepClear");
                SystemData.PlcDic[0].Write(hoisterStepClear.plcpointAddress, 1);
                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    SystemData.PlcDic[0].Write(hoisterStepClear.plcpointAddress, 0);
                });


                this.HoistClearButton.Background = new SolidColorBrush(Colors.LimeGreen);
                this.Msg.Text = DateTime.Now + " 轿厢线步序清0成功，请等待30s以后，提升机还未动作，请点击任务处理按钮...";
                this.HoistClearButton.IsEnabled = false;
                #region 开始定时器30s倒计时
                // 初始化定时器
                _timeRemaining = 30; // 重置时间为30秒
                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromSeconds(1); // 每秒触发一次
                _timer.Tick += Timer_Tick; // 设置定时器事件处理器
                _timer.Start(); // 启动定时器

                #endregion


            }
            catch (Exception ex)
            {
                this.Msg.Text = DateTime.Now + " 轿厢线步序清0出现异常:" + ex.Message;
                this.HoistClearButton.Background = new SolidColorBrush(Colors.Red);
            }
        }


        private void Timer_Tick(object sender, EventArgs e)
        {
            if (_timeRemaining > 0)
            {
                _timeRemaining--;
                UpdateTimeDisplay();
            }
            else
            {
                _timer.Stop(); // 倒计时结束，停止定时器
                this.Msg.Text = DateTime.Now + " 倒计时结束,允许下一步操作";
                if (taskHandlerFlag)
                {
                    PalletOutButton.IsEnabled = true;
                }
                else
                {
                    TaskHandlerButton.IsEnabled = true;
                }
            }
        }

        private void UpdateTimeDisplay()
        {
            if (taskHandlerFlag)
            {
                this.timeTxt2.Text = _timeRemaining.ToString();
            }
            else
            {
                this.timeTxt1.Text = _timeRemaining.ToString();
            }
           
        }


      
        /// <summary>
        /// 3.任务处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskHandlerButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                dbContext.ChangeTracker.Clear();
                var wcsTask = dbContext.WcsTask.Where(t => t.nextPointId == T01 && t.taskStatus > 0 && t.taskStatus <= 5).FirstOrDefault();
                if (wcsTask != null)
                {
                    if (wcsTask.currPointId == currentFloor)  //在起始地楼层
                    {
                        #region 读接驳位RFID ，防止托盘还没走，但是任务状态不为0，需要重新把状态重置0下发
                        //提升机当前楼层 
                        this.currentfloor06 = SystemData.BasePlcpoints.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("currentfloor06"));
                        var currentfloor06Value = SystemData.PlcDic[0].Read(this.currentfloor06.plcpointAddress);   //提升机当前楼层 读
                        currentFloor = Convert.ToInt32(currentfloor06Value);

                        FloorTxt.Text = currentFloor.ToString();
                        //接驳位RFID
                        BasePlcpoint LineRFID = SystemData.BasePlcpoints.First(t => t.plcpointNo == $"RFID00{currentFloor}");
                        var rfid = SystemData.PlcDic[0].ReadRFID(LineRFID.plcpointAddress);
                        #endregion

                        if (!string.IsNullOrEmpty(wcsTask.containerNo) && rfid.Contains(wcsTask.containerNo))  // 在出发地接驳位并且任务RFID不为空，与接驳位RFID相同
                        {
                            wcsTask.taskStatus = 0;
                            //if(wcsTask.endPointId == currentFloor)  //到达终点
                            //{
                            //    wcsTask.taskStatus = 5;
                            //}else if(wcsTask.currPointId == currentFloor)  //托盘还在起始地
                            //{
                            //    wcsTask.taskStatus = 0;
                            //}  
                        }
                        else//在提升机里面
                        {
                            wcsTask.taskStatus = 2;
                        }
                    }
                    else if (wcsTask.endPointId == currentFloor)  //在目的地楼层
                    {
                        #region 读接驳位RFID ，防止托盘已经到达目的楼层，但是任务状态不为5，需要自动更新
                        //提升机当前楼层 
                        this.currentfloor06 = SystemData.BasePlcpoints.First(t => t.equipmentNo.Contains("Hoister") && t.plcpointNo.Contains("currentfloor06"));
                        var currentfloor06Value = SystemData.PlcDic[0].Read(this.currentfloor06.plcpointAddress);   //提升机当前楼层 读
                        currentFloor = Convert.ToInt32(currentfloor06Value);

                        FloorTxt.Text = currentFloor.ToString();

                        //接驳位RFID
                        BasePlcpoint LineRFID = SystemData.BasePlcpoints.First(t => t.plcpointNo == $"RFID00{currentFloor}");
                        var rfid = SystemData.PlcDic[0].ReadRFID(LineRFID.plcpointAddress);
                        #endregion

                        if (!string.IsNullOrEmpty(wcsTask.containerNo) && rfid.Contains(wcsTask.containerNo))  // 在目的地接驳位并且任务RFID不为空，与接驳位RFID相同
                        {
                            wcsTask.taskStatus = 4;
                           
                        }
                        else//在提升机里面
                        {
                            wcsTask.taskStatus = 3;
                        }
                        
                    }
                    dbContext.WcsTask.Update(wcsTask);
                    dbContext.SaveChanges();
                }

                this.TaskHandlerButton.Background = new SolidColorBrush(Colors.LimeGreen);
                this.Msg.Text = DateTime.Now + " 任务处理成功，请等待30s以后提升机或者AGV还未动作，点击出提升机按钮...";
                taskHandlerFlag = true;
                this.TaskHandlerButton.IsEnabled = false;
                #region 开始定时器30s倒计时
                // 初始化定时器
                _timeRemaining = 30; // 重置时间为30秒
                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromSeconds(1); // 每秒触发一次
                _timer.Tick += Timer_Tick; // 设置定时器事件处理器
                _timer.Start(); // 启动定时器

                #endregion
            }catch(Exception ex)
            {
                this.Msg.Text = DateTime.Now + " 任务处理异常:" + ex.Message;
                this.TaskHandlerButton.Background = new SolidColorBrush(Colors.Red);
            }

        }

        /// <summary>
        /// 4.下发提升机出轿厢任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PalletOutButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.floorNo == currentFloor && t.plcpointNo.Contains("wcsrun"));
                SystemData.PlcDic[0].WriteToPoint(basePlcpoint.plcpointAddress, "2", basePlcpoint.plcpointLength.ToString());//去向为2，表示提升机已到达目的地，让货出去
                this.Msg.Text = DateTime.Now + " 提升机下发" + currentFloor + "楼出库指令";
                this.PalletOutButton.Background = new SolidColorBrush(Colors.LimeGreen);
                this.PalletOutButton.IsEnabled = false;
            }
            catch (Exception ex)
            {
                this.Msg.Text = DateTime.Now + " 下发提升机出轿厢任务异常:" + ex.Message;
                this.PalletOutButton.Background = new SolidColorBrush(Colors.Red);
            }
        }
    }
}
