using ConsoleApp;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HslCommunication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SlnMesnac.Business.business;
using SlnMesnac.Common;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository.service.Impl;
using SlnMesnac.WPF.Views;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;

namespace SlnMesnac.WPF.ViewModel
{
    public class EmployeeLoginViewModel : INotifyPropertyChanged
    {
        private readonly ILogger<EmployeeLoginViewModel> _logger;
        private readonly DatabaseHandleBusniess _databaseHandleBusniess;
        private readonly RfidHandleBusniess _rfidHandleBusniess;
        private IBaseStaffService baseStaffService;
        private IRecordStaffAttendanceService _recordStaffAttendanceService;
        private IRecordStaffCommuteService _recordStaffCommuteService;
        private string _checkInButtonText = "上班打卡";
        private string _checkOutButtonText = "下班打卡";
        public string _isCheckInButtonEnabled;
        public string _isRemoveButtonEnabled;
        private string _isCheckOutButtonEnabled;
        private string _checkInButtonColor;
        private string _checkOutButtonColor = "#009999";
        private int isCheckOn = 0;
        private bool isUse = false;//是否正在使用打卡机
        private bool isSelectedStationCode = false;//是否已选择工位，上班打卡前选择，下班时恢复
        private int status = 0;//0是上班，1是下班
        private string StationCodes;
        public static string stationCode = "";
        public static string stationName = "";
        public static HidUtils hidUtils;
        public static bool isOnDuty = false;//是否有班组当班
        private List<string> uniqueStrings = new List<string>();
        private List<DateTime> timestamps = new List<DateTime>();
        private BaseStaffInfo user;

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

        #region 定义命令
        /// <summary>
        /// 上班命令
        /// </summary>
        public ICommand CheckInCommand { get; private set; }

        /// <summary>
        /// 下班命令
        /// </summary>
        public ICommand CheckOutCommand { get; private set; }

        /// <summary>
        /// 结束命令
        /// </summary>
        public ICommand OverCommand { get; private set; }

        /// <summary>
        /// 删除命令
        /// </summary>
        public ICommand RemoveCommand { get; private set; }

        /// <summary>
        /// 确认命令
        /// </summary>
        public ICommand ConfirmCommand { get; private set; }

        
        #endregion

        #region 绑定参数
        /// <summary>
        /// 上班打卡文本
        /// </summary>
        public string CheckInButtonText
        {
            get { return _checkInButtonText; }
            set
            {
                _checkInButtonText = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheckInButtonText)));
            }
        }

        /// <summary>
        /// 上班打卡
        /// </summary>
        public string IsCheckInButtonEnabled
        {
            get { return _isCheckInButtonEnabled; }
            set
            {
                _isCheckInButtonEnabled = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsCheckInButtonEnabled)));
            }
        }

        /// <summary>
        ///下班打卡文本
        /// </summary>
        public string CheckOutButtonText
        {
            get { return _checkOutButtonText; }
            set
            {
                _checkOutButtonText = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheckOutButtonText)));
            }
        }

        /// <summary>
        /// 下班打卡
        /// </summary>
        public string IsCheckOutButtonEnabled
        {
            get { return _isCheckOutButtonEnabled; }
            set
            {
                _isCheckOutButtonEnabled = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsCheckOutButtonEnabled)));
            }
        }

        /// <summary>
        /// 上班打卡按钮颜色
        /// </summary>
        public string CheckInButtonColor
        {
            get { return _checkInButtonColor; }
            set
            {
                _checkInButtonColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheckInButtonColor)));
            }
        }

        /// <summary>
        /// 下班打卡按钮颜色
        /// </summary>
        public string CheckOutButtonColor
        {
            get { return _checkOutButtonColor; }
            set
            {
                _checkOutButtonColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CheckOutButtonColor)));
            }
        }

        /// <summary>
        /// 员工id
        /// </summary>
        private string staffId;
        public string StaffIdText
        {
            get { return staffId; }
            set { staffId = value; OnPropertyChanged("StaffIdText"); }
        }

        /// <summary>
        /// 打卡状态
        /// </summary>
        private string checkStatus;
        public string CheckStatus
        {
            get { return checkStatus; }
            set { checkStatus = value; OnPropertyChanged("CheckStatus"); }
        }

        //Status
        /// <summary>
        /// 状态
        /// </summary>
        private string statusText;
        public string StatusText
        {
            get { return statusText; }
            set { statusText = value; OnPropertyChanged("StatusText"); }
        }

        private ObservableCollection<RecordStaffAttendance> item = new ObservableCollection<RecordStaffAttendance>();

        /// <summary>
        /// DataGrid
        /// </summary>
        private ObservableCollection<RecordStaffRealTime> recordStaffRealTimeDataGrid = new ObservableCollection<RecordStaffRealTime>();

        public ObservableCollection<RecordStaffRealTime> RecordStaffRealTimeDataGrid
        {
            get { return recordStaffRealTimeDataGrid; }
            set { recordStaffRealTimeDataGrid = value; OnPropertyChanged("RecordStaffRealTimeDataGrid"); }

        }

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

        /// <summary>
        /// 选中工位
        /// </summary>
        private string selectedItem;
        public string SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                OnPropertyChanged(nameof(SelectedItem));
            }
        }
        #endregion

        #region 定义委托
        public static Action<String>? TransmitStationNameAction;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="staffInfo"></param>
        public delegate void TransmitUser();
        public static event TransmitUser TransmitUserDelegateEvent;

        public static Action<String>? _transmitToRemoveConfigAction;
        #endregion

        public EmployeeLoginViewModel()
        {
            hidUtils = new HidUtils();
            CheckInCommand = new RelayCommand(CheckIn);
            CheckOutCommand = new RelayCommand(CheckOut);
            RemoveCommand = new RelayCommand<string>(Remove);   
            OverCommand = new RelayCommand(Over);
            ConfirmCommand = new RelayCommand(Confirm);
            baseStaffService = App.ServiceProvider.GetService<IBaseStaffService>();
            _recordStaffAttendanceService = App.ServiceProvider.GetService<IRecordStaffAttendanceService>();
            _recordStaffCommuteService = App.ServiceProvider.GetService<IRecordStaffCommuteService>();
            _databaseHandleBusniess = App.ServiceProvider.GetService<DatabaseHandleBusniess>();
            _rfidHandleBusniess = App.ServiceProvider.GetService<RfidHandleBusniess>();
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(System.AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            IConfigurationRoot configuration = configurationBuilder.Build();
            //_rfidHandleBusniess.InstructionInfoDataGridEvent += RefreshRfidInfo;
            StationCodes = configuration.GetSection("AppConfig")["StationCode"];            
            List<string> stationCodeList = ConvertStringToList(StationCodes);
            StationList = stationCodeList;
            RfidHandleBusniess.stationList = GetStationCodes(stationCodeList);
            IsCheckInButtonEnabled = "True";
            IsCheckOutButtonEnabled = "True";
            CheckInButtonColor = "#009999";
            CheckOutButtonColor = "#009999";
            Init();
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Confirm()
        {
            if (!isOnDuty)
            {
                //stationCode = SelectedItem;
                var result = ExtractStrings(SelectedItem);
                RfidHandleBusniess.stationCode = result.Item1;
                stationName = result.Item2;
                //ExecuteViewModel.stationTextBlock = stationName;
                TransmitStationNameAction?.Invoke(stationName);
                isSelectedStationCode = true;
                TransmitUserDelegateEvent?.Invoke();
                ShowStaffAttendances(null, isCheckOn);
                MessageBox.Show("已确认工位：" + stationName);
            }
            else
            {
                MessageBox.Show("已上班不能再选择工位！");
            }
        }

        /// <summary>
        /// 主动移除
        /// </summary>
        private void Remove(string staffId)
        {
            MainWindowViewModel.wins = 2;
            if (isUse == false)
            {               
                var removeConfirmWin = new RemoveConfirmWin();
                removeConfirmWin.Owner = Application.Current.MainWindow;
                removeConfirmWin.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                removeConfirmWin.ShowDialog();
                if (RemoveConfirmViewModel.times == 1)
                {
                    var theUser = baseStaffService.GetStaffInfoByStaffId(staffId);
                    _rfidHandleBusniess.HandleAndInsertRemove(theUser, 2);//在打卡记录表里记录强退
                    var list = _rfidHandleBusniess.HandleAndInsertStaffRealTime(theUser, 2);
                    if (list.Count>=0)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                        {
                            RecordStaffRealTimeDataGrid.Clear();
                            list.ForEach(item => { RecordStaffRealTimeDataGrid.Add(item); });
                        }));
                        _rfidHandleBusniess.HandleStaffCommute(user, 1);
                    }
                    if(list.Count == 0)
                    {
                        isOnDuty = false;
                        isSelectedStationCode = false;
                    }
                }
                TransmitUserDelegateEvent?.Invoke();
                EmployeeLoginViewModel._transmitToRemoveConfigAction -= _transmitToRemoveConfigAction;
            }
            else
            {
                MessageBox.Show("正在打卡不能强退！");
            }
        }

        private void Init()
        {
            hidUtils.Initial();
            hidUtils.pushReceiveDataEvent += (bytes, str) =>
            {
                if (MainWindowViewModel.wins == 1)
                {
                    string cleanStr = str.ToString().Replace(" ", "");
                    StatusText = StaffIdText = CheckStatus = null;
                    if (!IsDuplicate(cleanStr))//过滤重复str
                    {
                        uniqueStrings.Add(cleanStr);
                        timestamps.Add(DateTime.Now);
                        // Additional logic for processing the unique string goes here
                        if (isUse)
                        {
                            user = baseStaffService.GetStaffInfoByCardId(cleanStr);
                            if (user != null)
                            {
                                RecordStaffAttendance recordStaffAttendance = _recordStaffAttendanceService.GetRecordStaffAttendanceByStaffId(user.StaffId, RfidHandleBusniess.stationCode);
                                if (recordStaffAttendance != null)
                                {
                                    //判断与上次打卡类型是否重复（主要为上班）
                                    if (recordStaffAttendance.AttendanceType != status.ToString())
                                    {
                                        StaffIdText = user.StaffId;
                                        CheckStatus = user.StaffName + " " + user.TeamCode + " 打卡成功！";
                                        _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                        ShowStaffAttendances(user, isCheckOn);
                                        _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                    }
                                    else
                                    {
                                        StatusText = "请勿重复打卡！";
                                    }
                                    //var createTime = recordStaffAttendance.CreateTime;
                                    //var nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    //TimeSpan timeDiff = DateTime.Parse(nowTime) - DateTime.Parse(createTime);
                                    //if (timeDiff.TotalHours >= 10)//
                                    //{
                                    //    if (recordStaffAttendance.AttendanceType == "1") //下班卡
                                    //    {
                                    //        if (recordStaffAttendance.AttendanceType == status.ToString() || recordStaffAttendance.AttendanceType == "2")
                                    //        {
                                    //            StatusText = "未打上班卡，请联系管理员！";
                                    //        }
                                    //    }
                                    //    else if (recordStaffAttendance.AttendanceType == "0")
                                    //    {
                                    //        if (recordStaffAttendance.AttendanceType == status.ToString())
                                    //        {
                                    //            StatusText = "未打下班卡，请联系管理员！";
                                    //        }
                                    //    }
                                    //    StaffIdText = user.StaffId;
                                    //    CheckStatus = user.StaffName + " " + user.TeamCode + " 打卡成功！";
                                    //    _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                    //    ShowStaffAttendances(user, isCheckOn);
                                    //    _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                    //}
                                    //else
                                    //{
                                    //    if (recordStaffAttendance.AttendanceType != status.ToString())
                                    //    {
                                    //        StaffIdText = user.StaffId;
                                    //        CheckStatus = user.StaffName + " " + user.TeamCode + " 打卡成功！";
                                    //        _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                    //        ShowStaffAttendances(user, isCheckOn);
                                    //        _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                    //    }
                                    //    else
                                    //    {
                                    //        StatusText = "请勿重复打卡！";
                                    //    }
                                    //}
                                }
                                else
                                {
                                    StaffIdText = user.StaffId;
                                    CheckStatus = "打卡成功！";
                                    _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                    ShowStaffAttendances(user, isCheckOn);
                                    _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                }
                            }
                            else
                            {
                                StaffIdText = "未配置";
                                CheckStatus = "没有匹配的员工，打卡失败！";
                            }
                        }
                    }
                    else
                    {
                        StaffIdText = "已打卡，请勿重复！";
                    }
                }
                else if (MainWindowViewModel.wins == 2)
                {
                    _transmitToRemoveConfigAction(str);
                    MainWindowViewModel.wins = 1;
                }
                else if (MainWindowViewModel.wins == 3)
                {

                }               
            };                      
        }

        public HidUtils getHidUtil()
        {
            return hidUtils;
        }

        

        /// <summary>
        /// 上班打卡事件
        /// </summary>
        private void CheckIn()
        {
            if (isSelectedStationCode)
            {
                isOnDuty = true;
                if (CheckInButtonText == "上班打卡")
                {
                    // 执行上班打卡逻辑
                    isCheckOn = 0;
                    status = 0;
                    isUse = true;
                    CheckInButtonText = "结束打卡";
                    IsCheckOutButtonEnabled = "False"; // Disable CheckOutButton
                    CheckOutButtonColor = "Gray";
                    hidUtils.StartScan();
                }
                else
                {
                    // 执行结束打卡逻辑
                    CheckInButtonText = "上班打卡";
                    IsCheckOutButtonEnabled = "True"; // Enable CheckOutButton
                    CheckOutButtonColor = "#009999";
                    TransmitUserDelegateEvent?.Invoke();
                    hidUtils.StopScan();
                    ShowStaffAttendances(null, isCheckOn);
                    isCheckOn = 1;
                    isUse = false;
                }
            }
            else
            {
                MessageBox.Show("请先选择工位！");
            }
        }

        /// <summary>
        /// 下班打卡事件
        /// </summary>
        private void CheckOut()
        {
            isOnDuty = false;
            if (CheckOutButtonText == "下班打卡")
            {
                // 执行下班打卡逻辑
                isCheckOn = 1;
                isUse = true;
                status = 1;
                CheckOutButtonText = "结束打卡";            
                IsCheckInButtonEnabled = "False"; // Disable CheckInButton
                CheckInButtonColor = "Gray";
                hidUtils.StartScan();
            }
            else
            {
                // 执行结束打卡逻辑
                CheckOutButtonText = "下班打卡";
                IsCheckInButtonEnabled = "True"; // Enable CheckInButton
                CheckInButtonColor = "#009999";
                TransmitUserDelegateEvent?.Invoke();
                hidUtils.StopScan();
                ShowStaffAttendances(null, isCheckOn);
                isCheckOn = 0;
                isSelectedStationCode = false;
                isUse = false;
            }
        }

        /// <summary>
        /// 结束打卡事件
        /// </summary>
        private void Over()
        {
            // 执行结束打卡的逻辑
            CheckInButtonText = "上班打卡";
            CheckOutButtonText = "下班打卡";
        }

        /// <summary>
        /// 5秒内过滤重复str
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsDuplicate(string str)
        {
            for (int i = 0; i < uniqueStrings.Count; i++)
            {
                if (uniqueStrings[i] == str && (DateTime.Now - timestamps[i]).TotalSeconds < 5)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 显示人员登录信息
        /// </summary>
        /// <param name="theUser"></param>
        /// <param name="theIsCheckOn"></param>
        private void ShowStaffAttendances(BaseStaffInfo? theUser, int theIsCheckOn)
        {
            var list = _rfidHandleBusniess.HandleAndInsertStaffRealTime(theUser, theIsCheckOn);
            System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
            {
                RecordStaffRealTimeDataGrid.Clear();
                list.ForEach(item => { RecordStaffRealTimeDataGrid.Add(item); });
            }));
        }

        /// <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;
        }

        /// <summary>
        /// 提取字符串中的数字和描述
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public (string, string) ExtractStrings(string input)
        {
            // 根据 '-' 分隔字符串
            var parts = input.Split('-');
            // 返回元组，包含数字和描述
            return (parts[0], parts.Length > 1 ? parts[1] : string.Empty);
        }

        /// <summary>
        /// 提取工位编码列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<string> GetStationCodes(List<string> list)
        {
            List<string> stationCodes = new List<string>();
            foreach (var item in list) 
            {
                stationCodes.Add(ExtractStrings(item).Item1);
            }
            return stationCodes;
        }

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