using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc;
using Khd.Core.Plc.S7;
using Khd.Core.Wpf.Form;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Khd.Core.Wpf.TaskForm
{
    /// <summary>
    /// AddTask.xaml 的交互逻辑
    /// </summary>
    public partial class AddTask : Window
    {
        private List<EquipMessage> startEquips = new List<EquipMessage>();
        private List<EquipMessage> endEquips = new List<EquipMessage>();
        private List<BaseEquip> baseEquips = new List<BaseEquip>();
        private readonly IHost _host;
        public AddTask(IHost host)
        {
            InitializeComponent();
            _host = host;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var scope = _host.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            baseEquips = dbContext.BaseEquip.ToList();
            foreach (var equip in baseEquips)
            {
                if (equip.ud1 == "1")
                {
                    startEquips.Add(new EquipMessage
                    {
                        Id = equip.objid,
                        equipName = equip.equipName,
                        equipNo = equip.equipNo,
                        equipType = equip.equipType,
                        equipStatus = equip.equipStatus,
                        floorNo = equip.floorNo,
                        IsEnabled = true
                    });
                }
                if (equip.ud2 == "1" && equip.emptyCount == 0)
                {
                    endEquips.Add(new EquipMessage
                    {
                        Id = equip.objid,
                        equipName = equip.equipName,
                        equipNo = equip.equipNo,
                        equipType = equip.equipType,
                        equipStatus = equip.equipStatus,
                        floorNo = equip.floorNo,
                        IsEnabled = true
                    });
                }
            }
            this.StartPoint.ItemsSource = startEquips;
            this.EndPoint.ItemsSource = endEquips;
        }

        private void AddTaskBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = _host.Services.CreateScope();
                var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                if (StartPoint.SelectedItem is EquipMessage startEquip && EndPoint.SelectedItem is EquipMessage endEquip)
                {
                    if (startEquip.equipType == 1)
                    {
                        BasePlcpoint linesignal = SystemData.BasePlcpoints.First(t => t.plcpointNo == $"linesignal0{startEquip.floorNo}");
                        var linesignalValue = SystemData.PlcDic[0].Read(linesignal.plcpointAddress);
                        if (linesignalValue != null && Convert.ToInt32(linesignalValue) == 1)
                        {
                            BasePlcpoint basePlcpoint = SystemData.BasePlcpoints.First(t => t.plcpointNo == $"RFID00{startEquip.floorNo}");
                            string? rfid = SystemData.PlcDic[0].ReadRFID(basePlcpoint.plcpointAddress);
                            MesBasePalletInfo? mesBasePalletInfo = dbContext.MesBasePalletInfo.Where(t => t.palletInfoCode == rfid).FirstOrDefault();
                            WcsTask? task = dbContext.WcsTask.FirstOrDefault(t => t.containerNo == rfid);
                            if (task == null)
                            {
                                int qty = 1;
                                if (int.TryParse(EmptyCount.SelectedIndex.ToString(), out int emptyCount))
                                {
                                    qty = emptyCount + 1;
                                }
                                BaseEquip baseEquip = baseEquips.First(t => t.equipType == 2);//提升机
                                WcsTask wcsTask = new()
                                {
                                    objid = FormBoardT._jcSnowId.NextId(),
                                    taskType = 99,
                                    containerNo = rfid,
                                    currPointId = startEquip.Id,
                                    currPointNo = startEquip.equipNo,
                                    nextPointId = baseEquip.objid,
                                    nextPointNo = baseEquip.equipNo,
                                    endPointId = endEquip.Id,
                                    endPointNo = endEquip.equipNo,
                                    fromFloorNo = startEquip.floorNo,
                                    floorNo = endEquip.floorNo,
                                    materialBarcode = mesBasePalletInfo?.materialBarcode,
                                    materialId = mesBasePalletInfo?.materialId,
                                    taskStatus = 0,
                                    createBy = "人工",
                                    createTime = DateTime.Now,
                                    equipmentNo = startEquip.equipNo,
                                    useFlag = 0,
                                    qty = qty,
                                    isEmpty = "1"
                                };
                                dbContext.Add(wcsTask);
                                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(wcsTask);
                                dbContext.Add(wcsTaskLog);
                                dbContext.SaveChanges();
                            }
                            else
                            {
                                MessageBox.Show("该RFID的任务已经存在！");
                            }
                        }
                        else
                        {
                            MessageBox.Show("未检测到起始地楼层的到位信号");
                        }
                    }
                    this.Close();
                }
                else
                {
                    MessageBox.Show("请选择起点和终点");
                }
            }
            catch (Exception ex)
            {
                if (ex is PlcException)
                {
                    try
                    {
                        MessageBox.Show("PLC断开连接，正在重连");
                        Task.Run(() =>
                        {
                            SystemData.PlcDic[0] = new Plc.S7.Plc(SystemData.PlcDic[0].CPU, SystemData.PlcDic[0].IP, SystemData.PlcDic[0].Port, SystemData.PlcDic[0].Rack, SystemData.PlcDic[0].Slot);
                            SystemData.PlcDic[0].Open();
                        });
                    }
                    catch
                    {
                        MessageBox.Show("PLC连接失败,无法读取任务");
                    }
                }
            }

        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void EndPoint_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (StartPoint.SelectedItem is EquipMessage startEquip)
            {

            }
            else
            {
                if (EndPoint.SelectedItem != null)
                {
                    MessageBox.Show("请先选择起点");
                    EndPoint.SelectedItem = null;
                }
            }
        }

        private void StartPoint_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (StartPoint.SelectedItem is EquipMessage startEquip)
            {
                foreach (var item in endEquips)
                {
                    if (item.Id == startEquip.Id)
                    {
                        item.IsEnabled = false;
                    }
                    else
                    {
                        item.IsEnabled = true;
                    }
                }
                EndPoint.ItemsSource = endEquips;
                EndPoint.Items.Refresh();
            }
            else
            {
                EndPoint.SelectedItem = null;
                MessageBox.Show("请先选择起点");
            }
        }
    }

    public class EquipMessage
    {
        public long? Id { get; set; }
        public string equipName { get; set; }
        public string equipNo { get; set; }
        public int? equipType { get; set; }
        public int? equipStatus { get; set; }
        public int? floorNo { get; set; }
        public bool IsEnabled { get; set; } = true;
    }
}
