using ConsoleApp;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HslCommunication;
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 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.Input;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;

namespace SlnMesnac.WPF.ViewModel
{
    public class EmployeeLoginViewModel : INotifyPropertyChanged
    {
        private readonly ILogger<EmployeeLoginViewModel> _logger;
        private readonly RfidHandleBusniess _rfidHandleBusniess;
        private IBaseStaffService baseStaffService;
        private IRecordStaffAttendanceService _recordStaffAttendanceService;
        private IRecordStaffCommuteService _recordStaffCommuteService;
        private string _checkInButtonText = "上班打卡";
        private string _checkOutButtonText = "下班打卡";
        public string _isCheckInButtonEnabled;
        private string _isCheckOutButtonEnabled;
        private string _checkInButtonColor;
        private string _checkOutButtonColor = "#009999";
        private int isCheckOn = 0;
        private bool isUse = false;
        private int status = 0;//0是上班，1是下班
        public static HidUtils hidUtils;
        public static bool isOnDuty = false;//是否有班组当班
        private List<string> uniqueStrings = new List<string>();
        private List<DateTime> timestamps = new List<DateTime>();

        /// <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>
        /// <param name="staffInfo"></param>
        public delegate void TransmitUser(BaseStaffInfo staffInfo);
        public static event TransmitUser TransmitUserDelegateEvent;
        #endregion

        public EmployeeLoginViewModel()
        {
            hidUtils = new HidUtils();
            CheckInCommand = new RelayCommand(CheckIn);
            CheckOutCommand = new RelayCommand(CheckOut);
            OverCommand = new RelayCommand(Over);
            baseStaffService = App.ServiceProvider.GetService<IBaseStaffService>();
            _recordStaffAttendanceService = App.ServiceProvider.GetService<IRecordStaffAttendanceService>();
            _recordStaffCommuteService = App.ServiceProvider.GetService<IRecordStaffCommuteService>();
            _rfidHandleBusniess = App.ServiceProvider.GetService<RfidHandleBusniess>();
            //_rfidHandleBusniess.InstructionInfoDataGridEvent += RefreshRfidInfo;
            IsCheckInButtonEnabled = "True";
            IsCheckOutButtonEnabled = "True";
            CheckInButtonColor = "#009999";
            CheckOutButtonColor = "#009999";
            Init();

        }

        private void Init()
        {
            hidUtils.Initial();
            hidUtils.pushReceiveDataEvent += (bytes, str) =>
            {
                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)
                    {
                        BaseStaffInfo user = baseStaffService.GetStaffInfoByCardId(cleanStr);
                        if (user != null)
                        {
                            RecordStaffAttendance recordStaffAttendance = _recordStaffAttendanceService.GetRecordStaffAttendanceByStaffId(user.StaffId);
                            if (recordStaffAttendance != null)
                            {
                                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())
                                        {
                                            StatusText = "未打上班卡，请联系管理员！";
                                        }
                                    }
                                    else if (recordStaffAttendance.AttendanceType == "0")
                                    {
                                        if (recordStaffAttendance.AttendanceType == status.ToString())
                                        {
                                            StatusText = "未打下班卡，请联系管理员！";
                                        }
                                    }
                                    StaffIdText = user.StaffId;
                                    CheckStatus = user.StaffName + " " + user.TeamCode + " 打卡成功！";
                                    var list = _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                    System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                                    {
                                        RecordStaffAttendanceDataGrid.Clear();
                                        list.ForEach(item => { RecordStaffAttendanceDataGrid.Add(item); });
                                    }));
                                    _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                }
                                else
                                {
                                    if (recordStaffAttendance.AttendanceType != status.ToString())
                                    {
                                        StaffIdText = user.StaffId;
                                        CheckStatus = user.StaffName + " " + user.TeamCode + " 打卡成功！";
                                        var list = _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                        System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                                        {
                                            RecordStaffAttendanceDataGrid.Clear();
                                            list.ForEach(item => { RecordStaffAttendanceDataGrid.Add(item); });
                                        }));
                                        _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                                    }
                                    else
                                    {
                                        StatusText = "请勿重复打卡！";
                                    }
                                }                      
                            }
                            else
                            {
                                StaffIdText = user.StaffId;
                                CheckStatus = "打卡成功！";
                                var list = _rfidHandleBusniess.HandleAndInsertStaffAttendance(user, isCheckOn);
                                System.Windows.Application.Current.Dispatcher.Invoke((Action)(async () =>
                                {
                                    RecordStaffAttendanceDataGrid.Clear();
                                    list.ForEach(item => { RecordStaffAttendanceDataGrid.Add(item); });
                                }));
                                _rfidHandleBusniess.HandleStaffCommute(user, isCheckOn);
                            }
                        }
                        else
                        {
                            StaffIdText = "未配置";
                            CheckStatus = "没有匹配的员工，打卡失败！";
                        }
                        TransmitUserDelegateEvent?.Invoke(user);
                    }
                }
                else
                {
                    StaffIdText = "已打卡，请勿重复！";
                }
            };
        }

        public HidUtils getHidUtil()
        {
            return hidUtils;
        }

        #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<RecordStaffAttendance> recordStaffAttendanceDataGrid = new ObservableCollection<RecordStaffAttendance>();

        public ObservableCollection<RecordStaffAttendance> RecordStaffAttendanceDataGrid
        {
            get { return recordStaffAttendanceDataGrid; }
            set { recordStaffAttendanceDataGrid = value; OnPropertyChanged("RecordStaffAttendanceDataGrid"); }

        }
        #endregion

        /// <summary>
        /// 上班打卡事件
        /// </summary>
        private void CheckIn()
        {
            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";
                hidUtils.StopScan();
                isCheckOn = 1;
                isUse = false;
            }
        }

        /// <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";
                hidUtils.StopScan();
                isCheckOn = 0;
                isUse = false;
            }
        }

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

        /// <summary>
        /// 30分钟内过滤重复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 < 30)
                {
                    return true;
                }
            }
            return false;
        }

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