using GalaSoft.MvvmLight.Command;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols;
using NVelocity.Util.Introspection;
using SlnMesnac.Business;
using SlnMesnac.Business.business;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Repository.service;
using SlnMesnac.WPF.Page;
using SlnMesnac.WPF.Views;
using SqlSugar;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace SlnMesnac.WPF.ViewModel
{
    public class ExecuteViewModel : INotifyPropertyChanged
    {
        private readonly ILogger<ExecuteViewModel> _logger;
        public ObservableCollection<string> OrderCodeComboBoxItems { get; set; }
        public ObservableCollection<string> PlanCodeComboBoxItems { get; set; }
        public ObservableCollection<string> MaterialNameComboBoxItems { get; set; }
        private RfidHandleBusniess _RfidHandleBusniess;
        private DatabaseHandleBusniess _databaseHandleBusniess;
        private ProdPlanInfoService _prodPlanInfoService;
        private ProdOrderInfoService _prodOrderInfoService;
        private List<ProdPLanInfo> prodPlanInfos;
        private ProdPlanDetailService _prodPlanDetailService;
        private IRecordStaffAttendanceService _recordStaffAttendanceService;
        private IRecordStaffRealTimeService _recordStaffRealTimeService;
        private IBaseStaffService _baseStaffService;
        //private string StationCode;
        private string DeviceCode;
        private string ProcessCode;
        public static bool isComplete = true;
        public static string theStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//记录每个明细的开始时间
        //public static string intervalvalTime = "2023-11-11 00:00:00";
        public static int stations = 0;
        private string theOrderCode = "";
        private ProdPLanInfo pLanInfo;
        private ProdPLanInfo haveInfo;
        private SerialPortBusiness _serialPortBusiness;
        private string executeText = "待执行";
        private int isSearch = 0;
        public static string lastReportTime;
        private int refreshOrNot = 1;//是否刷新
        //public static string batchNums = "";//批次

        #region 定义命令
        /// <summary>
        /// 检索命令
        /// </summary>
        public ICommand SearchCommand { get; private set; }

        /// <summary>
        /// 换班命令
        /// </summary>
        public ICommand HandoverCommand { get; private set; }

        /// <summary>
        /// 报工命令
        /// </summary>
        public ICommand ProductionReportCommand { get; private set; }

        /// <summary>
        /// 工艺信息命令
        /// </summary>
        public ICommand TechnologicalInformationCommand { get; private set; }

        /// <summary>
        /// 执行命令
        /// </summary>
        public ICommand ExecuteCommand { get; private set; }

        /// <summary>
        /// 撤回命令
        /// </summary>
        public ICommand WithdrawCommand { get; private set; }
        #endregion

        #region 定义委托
        public delegate void RefreshDelegate(ProdPLanInfo pLanInfo);
        public static event RefreshDelegate? RefreshEvent;

        public static Action ClearOrderCodeAction;

        /// <summary>
        /// 按钮文字转换事件
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        #endregion

        #region 定义属性
        /// <summary>
        /// 班组成员
        /// </summary>
        private string teamMember;
        public string TeamMember
        {
            get { return teamMember; }
            set { teamMember = value; OnPropertyChanged("TeamMember"); }
        }

        /// <summary>
        /// 订单
        /// </summary>
        private string orderCodeTextBox;
        public string OrderCodeTextBox
        {
            get { return orderCodeTextBox; }
            set { orderCodeTextBox = value; OnPropertyChanged("OrderCodeTextBox"); }
        }

        /// <summary>
        /// 工单
        /// </summary>
        private string planCodeTextBox;
        public string PlanCodeTextBox
        {
            get { return planCodeTextBox; }
            set { planCodeTextBox = value; OnPropertyChanged("PlanCodeTextBox"); }
        }

        /// <summary>
        /// 原料
        /// </summary>
        private string materialCodeTextBox;
        public string MaterialCodeTextBox
        {
            get { return materialCodeTextBox; }
            set { materialCodeTextBox = value; OnPropertyChanged("MaterialCodeTextBox"); }
        }

        //private string materialNameTextBox;
        //public string MaterialNameTextBox
        //{
        //    get { return materialNameTextBox; }
        //    set { materialNameTextBox = value; OnPropertyChanged("MaterialNameTextBox"); }
        //}

        /// <summary>
        /// 工位
        /// </summary>
        private string stationTextBlock;
        public  string StationTextBox
        {
            get { return stationTextBlock; }
            set { stationTextBlock = value; OnPropertyChanged("StationTextBox"); }
        }

        /// <summary>
        /// PlanDataGrid
        /// </summary>
        private ObservableCollection<ProdPLanInfo> prodPLanInfoDataGrid = new ObservableCollection<ProdPLanInfo>();
        public ObservableCollection<ProdPLanInfo> ProdPLanInfoDataGrid
        {
            get { return prodPLanInfoDataGrid; }
            set { prodPLanInfoDataGrid = value; OnPropertyChanged("ProdPLanInfoDataGrid"); }
        }

        /// <summary>
        /// 工单计划选中行
        /// </summary>
        public ProdPLanInfo _selectedRow;
        public ProdPLanInfo SelectedRow
        {
            get { return _selectedRow; }
            set
            {
                _selectedRow = value; OnPropertyChanged(nameof(SelectedRow));
            }
        }

        /// <summary>
        /// DetailDataGrid
        /// </summary>
        private ObservableCollection<ProdPlanDetail> prodPLanDetailDataGrid = new ObservableCollection<ProdPlanDetail>();
        public ObservableCollection<ProdPlanDetail> ProdPLanDetailDataGrid
        {
            get { return prodPLanDetailDataGrid; }
            set { ProdPLanDetailDataGrid = value; OnPropertyChanged("ProdPLanDetailDataGrid"); }
        }

        /// <summary>
        /// 工单明细选中行
        /// </summary>
        public ProdPlanDetail _selectedDetialRow;
        public ProdPlanDetail SelectedDetailRow
        {
            get { return _selectedDetialRow; }
            set
            {
                _selectedDetialRow = value; OnPropertyChanged(nameof(SelectedDetailRow));
            }
        }

        /// <summary>
        /// 订单Text
        /// </summary>
        private string orderCodeText = string.Empty;
        public string OrderCodeText
        {
            get { return orderCodeText; }
            set { orderCodeText = value; OnPropertyChanged("OrderCodeText"); }
        }

        /// <summary>
        /// 工单Text
        /// </summary>
        private string planCodeText;
        public string PlanCodeText
        {
            get { return planCodeText; }
            set { planCodeText = value; OnPropertyChanged("PlanCodeText"); }
        }

        /// <summary>
        /// 原料Text
        /// </summary>
        private string materialNameText;
        public string MaterialNameText
        {
            get { return materialNameText; }
            set { materialNameText = value; OnPropertyChanged("MaterialNameText"); }
        }

        /// <summary>
        /// 工位列表
        /// </summary>
        private List<string> stationList;
        public List<string> StationList
        {
            get { return stationList; }
            set { stationList = value; OnPropertyChanged("StationList");}
        }

        /// <summary>
        /// 订单
        /// </summary>
        private string stationCodeText;
        public string StationCodeText
        {
            get { return stationCodeText; }
            set { stationCodeText = value; OnPropertyChanged("StationCodeText"); }
        }

        /// <summary>
        /// 批次号
        /// </summary>
        private string batchNumbers;
        public string BatchNumbers
        {
            get { return batchNumbers; }
            set { batchNumbers = value; OnPropertyChanged("BatchNumbers"); }
        }

        /// <summary>
        /// 班长名
        /// </summary>
        private string currentMonitorName;
        public string CurrentMonitorName
        {
            get { return currentMonitorName; }
            set { currentMonitorName = value; OnPropertyChanged("CurrentMonitorName"); }
        }
        #endregion

        public ExecuteViewModel()
        {

            _logger = App.ServiceProvider.GetService<ILogger<ExecuteViewModel>>();
            _prodPlanInfoService = App.ServiceProvider.GetService<ProdPlanInfoService>();
            _prodOrderInfoService = App.ServiceProvider.GetService<ProdOrderInfoService>();
            _prodPlanDetailService = App.ServiceProvider.GetService<ProdPlanDetailService>();
            _recordStaffAttendanceService = App.ServiceProvider.GetService<IRecordStaffAttendanceService>();
            _recordStaffRealTimeService = App.ServiceProvider.GetService<IRecordStaffRealTimeService>();
            _RfidHandleBusniess = App.ServiceProvider.GetService<RfidHandleBusniess>();
            _baseStaffService = App.ServiceProvider.GetService<IBaseStaffService>();
            _serialPortBusiness = App.ServiceProvider.GetService<SerialPortBusiness>();
            _databaseHandleBusniess = App.ServiceProvider.GetService<DatabaseHandleBusniess>();
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(System.AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            IConfigurationRoot configuration = configurationBuilder.Build();
            pLanInfo = _prodPlanInfoService.GetPlanInfoByConditions("", "", "", "", "1").FirstOrDefault();
            Refresh(pLanInfo);
            havePlanOnDuty();
            // 从配置文件中获取ProductLineNameTextBlock的值
            //stationTextBlock = configuration.GetSection("AppConfig")["ProductLineName"];
            //StationCodes = configuration.GetSection("AppConfig")["StationCode"];
            //EmployeeLoginViewModel.TransmitStationNameAction += info => {
            //    stationTextBlock = info;
            //};
            //StationList = ConvertStringToList(StationCodes);
            //RfidHandleBusniess.stationCode = StationCodes;
            EmployeeLoginViewModel.TransmitStationNameAction += stationName =>
            {
                updateStationName(stationName);
            };
            ProductionReportViewModel.RefrashClearAction += num => 
            {
                refreshOrNot = num;
                Clear();
            }
            ;
            DeviceCode = configuration.GetSection("AppConfig")["DeviceCode"];
            ProcessCode = configuration.GetSection("AppConfig")["ProcessCode"];
            HandoverCommand = new RelayCommand(Handover);
            ProductionReportCommand = new RelayCommand(ProductionReport);
            TechnologicalInformationCommand = new RelayCommand(TechnologicalInformation);
            SearchCommand = new RelayCommand(Search);
            ExecuteCommand = new RelayCommand(Execute);
            WithdrawCommand = new RelayCommand(Withdraw);
            ProductionReportViewModel.RefreshDelegateEvent += Refresh;
            EmployeeLoginViewModel.TransmitUserDelegateEvent += ShowTeamMember;
            //SerialPortBusiness.ReceivedBarcodeInfoEvent += HandleOrderCode;
            MainWindowViewModel.TransferOrderCodeEvent += HandleOrderCode;
        }

        /// <summary>
        /// 撤回
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Withdraw()
        {
            //BatchNumbers = batchNums;
            MainWindowViewModel.wins = 2;
            var removeConfirmWin = new RemoveConfirmWin();
            removeConfirmWin.Owner = Application.Current.MainWindow;
            removeConfirmWin.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            removeConfirmWin.ShowDialog();
            if (RemoveConfirmViewModel.times == 1)
            {
                //当前正在执行的工单的单号和产量
                string planCode = pLanInfo.PlanCode;
                int batch = _selectedDetialRow.BatchNumber;
                //删除planInfo对应产量
                pLanInfo = _prodPlanInfoService.GetPlanInfoByConditions("", "", "", "", "1").FirstOrDefault();
                double planNum = double.Parse(pLanInfo.CompleteAmount);
                double detailNum = double.Parse(_selectedDetialRow.CompleteAmount);
                pLanInfo.CompleteAmount = (planNum - detailNum).ToString();
                _prodPlanInfoService.Update(pLanInfo);
                //删除对应批次的明细和执行人信息
                _databaseHandleBusniess.DeleteTheBatchDetailAndExecuter(planCode, batch);
                //刷新
                Refresh(pLanInfo);
            }
            MainWindowViewModel.wins = 1;
        }

        /// <summary>
        /// 是否有计划正在执行
        /// </summary>
        private void havePlanOnDuty()
        {
            haveInfo = _prodPlanInfoService.GetPlanInfoByConditions("", "", "", "", "1").FirstOrDefault();
            if (haveInfo != null)
            {
                isComplete = false;
            }else
            {
                isComplete = true;
            }
        }

        /// <summary>
        /// 更新工位名称
        /// </summary>
        /// <param name="stationName"></param>
        private void updateStationName(string stationName)
        {
            StationTextBox = EmployeeLoginViewModel.stationName;
        }

        /// <summary>
        /// 换班弹窗
        /// </summary>
        private void Handover()
        {
            var handOverWin = new HandOverWin();
            handOverWin.Owner = Application.Current.MainWindow;  //  设置父窗口为当前主窗口
            handOverWin.WindowStartupLocation = WindowStartupLocation.CenterScreen; // 让窗体出现在屏幕中央
            handOverWin.ShowDialog();//窗体出现后禁止后面的用户控件            
        }

        /// <summary>
        /// 报工弹窗
        /// </summary>
        private void ProductionReport()
        {
            if (RfidHandleBusniess.stationCode != "")
            {
                pLanInfo = _prodPlanInfoService.GetPlanInfoByConditions("", "", "", RfidHandleBusniess.stationCode, "1").FirstOrDefault();
                if (pLanInfo != null)
                {
                    MainWindowViewModel.wins = 3;
                    var reportWin = new ProductionReportWin();
                    reportWin.Owner = Application.Current.MainWindow;  //  设置父窗口为当前主窗口
                    reportWin.WindowStartupLocation = WindowStartupLocation.CenterScreen; // 让窗体出现在屏幕中央
                    reportWin.ShowDialog();//窗体出现后禁止后面的用户控件
                    Search();
                    if (refreshOrNot == 1)
                    {
                        Refresh(pLanInfo);
                    }
                    refreshOrNot = 1;
                    ShowTeamMember();
                    if (stations >= 3)
                    {
                        _databaseHandleBusniess.UpdateOrderInfoStatus(theOrderCode, "2");
                    }
                    MainWindowViewModel.wins = 1;
                }
                else
                {
                    MessageBox.Show("没有待执行或执行中的工单！");
                }
            }
            else
            {
                MessageBox.Show("未选择工位没有班组上班！");
            }            
        }

        /// <summary>
        /// 工艺信息弹窗,单例模式保证只显示一个
        /// </summary>
        private static TechnologicalWin instance;
        private void TechnologicalInformation()
        {
            if (instance == null)
            {
                instance = new TechnologicalWin();
                instance.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                instance.Closed += (sender, e) => { instance = null; }; // 窗口关闭时重置instance为null，以便下次可以重新打开窗口
                instance.Show();
            }
            else
            {
                instance.Focus(); // 如果窗口已经存在，则将焦点放在该窗口上
            }
        }


        /// <summary>
        /// 检索事件
        /// </summary>
        private void Search()
        {
            var staffList = _recordStaffRealTimeService.Query().ToList();
            if (staffList.Count > 0)
            {
                //在这里执行其他操作，可以通过InputText获取用户输入的信息
                //Console.WriteLine("用户输入的信息：" + OrderCodeTextBox + PlanCodeTextBox + MaterialCodeTextBox);
                //ProductLineNameTextBlock = ConfigurationManager.AppSettings["ProductLineNameTextBlock"];
                List<ProdPLanInfo> list = _prodPlanInfoService.GetRecordStaffAttendancesByConditions(OrderCodeTextBox, PlanCodeTextBox, MaterialCodeTextBox, RfidHandleBusniess.stationCode, "0");
                System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                {
                    ProdPLanInfoDataGrid.Clear();
                    list.ForEach(item =>
                    {
                        ProdPLanInfoDataGrid.Add(item);
                    });
                }));
                isSearch = 1;
            }
            else
            {
                MessageBox.Show("没有班组上班，请先打卡上班！");
            }
        }

        /// <summary>
        /// 根据订单单号判断是否存在，
        /// </summary>
        private void HandleOrderCode(string orderCode)
        {
            if (isComplete)
            {
                var order = _prodOrderInfoService.GetProdOrderInfoByOrderCode(orderCode);
                if (order != null)
                {
                    if (isSearch == 1)
                    {
                        ClearOrderCodeAction?.Invoke();
                        //更新当前工单状态
                        _databaseHandleBusniess.UpdateOrderInfoStatus(order.OrderCode, "1");
                        //判断当前工位的工单编号是否存在
                        var plan = _prodPlanInfoService.GetProdPLanInfoByOrderCode(RfidHandleBusniess.stationCode, order.OrderCode);
                        if (plan == null)//不存在，就在生产工单表中新增一条当前工位的订单，且执行状态改为4,重新检索，并高亮这条工单，执行按钮可用
                        {
                            foreach (var item in RfidHandleBusniess.stationList)
                            {
                                //现扫描一个订单码，同时插入三张（出布包胶成型）工单表
                                _databaseHandleBusniess.AddNewPlanInfo(order.OrderCode, item, DeviceCode, ProcessCode, "0");
                            }
                        }
                        else//存在，将本条数据的执行状态改为4高亮这条工单，执行按钮可用
                        {
                            //判断这条工单状态是否为待执行或未执行
                            //var info = _databaseHandleBusniess.SelectPlanStatus(orderCode, RfidHandleBusniess.stationCode, DeviceCode, ProcessCode, "0");
                            if (plan.PlanStatus != "2")
                            {
                                _databaseHandleBusniess.UpdatePlanStatus(order.OrderCode, RfidHandleBusniess.stationCode, DeviceCode, ProcessCode, "4");
                            }
                            else
                            {
                                MessageBox.Show("此工单已完成");
                            }
                        }
                        Search();
                    }
                }
                else
                {
                    MessageBox.Show("此订单不存在，请联系管理员！");
                }
            }
            else
            {
                MessageBox.Show("请先完成当前工单！");
            }
        }
        

        /// <summary>
        /// 新增的执行事件
        /// </summary>
        private void Execute()
        {
            //判断是否有班组当班,查询打卡记录表，4小时内最后一次打卡类型为上班的班组
            if(EmployeeLoginViewModel.isOnDuty == true)
            {
                if (isComplete)//判断是否完成，未完成不能执行其他工单
                {
                    try
                    {

                        var Info = OrderCodeText.GetHashCode();

                        // 将当前记录存为实体，可以通过parameter获取当前记录的信息
                        string orderCode = _selectedRow.OrderCode.ToString();
                        string planCode = _selectedRow.PlanCode.ToString();
                        pLanInfo = _prodPlanInfoService.GetRecordStaffAttendancesByConditions(orderCode, planCode, "", "", "0").First();
                        //RecordStaffAttendance currentRecord = _recordStaffAttendanceService.GetLastestOnRecord();
                        //BaseStaffInfo staffInfo = _baseStaffService.GetMonitorByTeamCode(currentRecord.TeamCode);
                        RecordStaffAttendance nextRecord = _recordStaffAttendanceService.GetLastestOffRecord();
                        // 向detail表里插入一条数据
                        //当前班长
                        var monitor = _databaseHandleBusniess.GetMonitor(RfidHandleBusniess.stationCode);
                        if (pLanInfo.CompleteAmount == "0.00")
                        {
                            ProdPlanDetail prodPlanDetail = new ProdPlanDetail
                            {
                                PlanCode = pLanInfo.PlanCode,
                                MaterialCode = pLanInfo.MaterialCode,
                                PlanAmount = pLanInfo.PlanAmount,
                                CompleteAmount = pLanInfo.CompleteAmount,
                                BeginTime = theStartTime,
                                CreatedBy = monitor.staffName
                                //CurrentStaffId = staffInfo.StaffId
                                //NextStaffId = nextRecord.StaffId,
                            };
                            _prodPlanDetailService.Insert(prodPlanDetail);
                        }
                        //按钮文字变成执行中并锁定，其他的订单执行按钮也禁用
                        //pLanInfo.BeginTime = DateTime.Now.ToString();
                        pLanInfo.PlanStatus = "1";
                        _prodPlanInfoService.Update(pLanInfo);
                        Search();
                        //查明细表显示出来
                        Refresh(pLanInfo);
                        isComplete = false;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("执行异常", ex);
                    }
                }
                else
                {
                    MessageBox.Show("请先完成当前工单！");
                }
            }  
        }

        //刷新明细
        private void Refresh(ProdPLanInfo pLanInfo)
        {
            if(pLanInfo != null)
            {
                List<ProdPlanDetail> planDetails = _prodPlanDetailService.GetPlanDetailsByPlanCode(pLanInfo.PlanCode);
                if (planDetails.Count != 0)
                {
                    var planDetail = planDetails.FirstOrDefault();
                    PlanCodeText = planDetail.PlanCode;
                    OrderCodeText = pLanInfo.OrderCode;
                    MaterialNameText = pLanInfo.MaterialName;
                    StationCodeText = pLanInfo.StationCode;
                    //CurrentMonitorName = _baseStaffService.GetStaffInfoByStaffId(RfidHandleBusniess.staffId).StaffName;
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                    {
                        ProdPLanDetailDataGrid.Clear();
                        planDetails.ForEach(item => { ProdPLanDetailDataGrid.Add(item); });
                        //ProdPLanDetailDataGrid.Add(planDetail);
                    }));
                }
            }
            //else
            //{
            //    PlanCodeText = "";
            //    OrderCodeText = "";
            //    MaterialCodeText = "";
            //    StationCodeText = "";
            //    System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
            //    {
            //        ProdPLanDetailDataGrid.Clear();
            //    }));
            //}     
        }

        /// <summary>
        /// 清空右边信息和明细
        /// </summary>
        private void Clear()
        {
            PlanCodeText = "";
            OrderCodeText = "";
            MaterialNameText = "";
            ProdPLanDetailDataGrid.Clear();
            
        }

        /// <summary>
        /// 显示班组成员
        /// </summary>
        /// <param name="baseStaffInfo"></param>
        private void ShowTeamMember()
        {
            TeamMember = _RfidHandleBusniess.SpliceTeamMember();
        }

        /// <summary>
        /// 将字符串转换为列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private List<string> ConvertStringToList(string input)
        {
            // 使用逗号分隔字符串并转换为列表
            List<string> list = new List<string>(input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
            return list;
        }

        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
