using HKLib.Dto;
using HKLib.Interfaces;
using HKLib.SQLHelper;
using Snowflake.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using UHFHelper;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace HKCardManager.UserPages
{
    public partial class CarMangerPage : UserControl
    {
        //List<string> OrgList = new List<string>();
        List<OrgDto> orgTables = new List<OrgDto>();
        List<string> Personnels = new List<string>();
        public CarMangerPage()
        {
            InitializeComponent();
            this.SizeChanged += CarMangerPage_SizeChanged;
            radioButton1.CheckedChanged += RadioButton1_CheckedChanged;
            radioButton2.CheckedChanged += RadioButton1_CheckedChanged;
            comboBox2.MouseDown += ComboBox2_MouseDown;
            comboBox2.TextUpdate += ComboBox2_TextUpdate;
            comboBox2.SelectedValueChanged += ComboBox2_SelectedValueChanged;
            comboBox4.DataSource = HKLib.Configer.Admin;

            radioButton1.Checked = true;
            comboBox2.Visible = false;
            Init();
        }

        private async void Init()
        {
            orgTables = await HKLibHelper.GetOrg();
            Global.UserListDtos.ForEach(item => { if (!string.IsNullOrEmpty(item.UserName)) Personnels.Add(item.UserName); });
            comboBox2.DataSource = Personnels;
            comboBox1.DataSource = Global.OrgList;

            //新加列表
            List<string> datalist = new List<string>();
            datalist.Add("全部");
            datalist.AddRange(Global.OrgList);
            comboBox_jglb.DataSource = datalist;
            comboBox_jglb.TextChanged += ComboBox_jglb_TextChanged;
            dataGridView1_全部.AllowUserToResizeColumns = false;// 禁止用户改变所有列的列宽 
            dataGridView1_全部.AllowUserToResizeRows = false; //禁止用户改变所有行的行高   
            dataGridView1_全部.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;  // 禁止用户改变列头的高度   
            dataGridView1_全部.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; // 禁止用户改变列头的宽度   
            dataGridView1_全部.AutoGenerateColumns = false;//禁用自动添加列
            dataGridView_No.AllowUserToResizeColumns = false;// 禁止用户改变所有列的列宽 
            dataGridView_No.AllowUserToResizeRows = false; //禁止用户改变所有行的行高   
            dataGridView_No.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;  // 禁止用户改变列头的高度   
            dataGridView_No.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; // 禁止用户改变列头的宽度   
            dataGridView_No.AutoGenerateColumns = false;//禁用自动添加列
            ComboBox_jglb_TextChanged(null, null);
        }

        private void ComboBox2_SelectedValueChanged(object? sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                var user = Global.UserListDtos.FirstOrDefault(p => !string.IsNullOrEmpty(comboBox2.Text.Trim()) && !string.IsNullOrEmpty(p.UserName) && p.UserName == comboBox2.Text.Trim());
                if (user != null && !string.IsNullOrEmpty(user.Phone))
                {
                    //textBox4.Text = user.Phone;
                    if (!string.IsNullOrEmpty(user.OrgName) && Global.OrgList.Contains(user.OrgName))
                    {
                        comboBox1.Text = user.OrgName;
                    }
                    else
                    {
                        comboBox1.SelectedIndex = -1;
                    }
                }
            }
        }

        private void ComboBox2_TextUpdate(object? sender, EventArgs e)
        {
            string name = comboBox2.Text.Trim();
            if (string.IsNullOrEmpty(name))
            {
                Personnels.Clear();
                Global.UserListDtos.ForEach(item => { if (!string.IsNullOrEmpty(item.UserName)) Personnels.Add(item.UserName); });
                comboBox2.DataSource = null;
                comboBox2.DataSource = Personnels;
                comboBox2.DroppedDown = true;
                comboBox2.SelectedIndex = -1;
                return;
            }
            comboBox2.DroppedDown = true;
            var res = Global.UserListDtos.Where(p => !string.IsNullOrEmpty(p.UserName) && !string.IsNullOrEmpty(comboBox2.Text.Trim()) && p.UserName.Contains(comboBox2.Text.Trim())).ToList();
            if (res != null)
            {
                Personnels.Clear();
                res.ForEach(p => Personnels.Add(p.UserName));
                comboBox2.DataSource = null;
                comboBox2.DataSource = Personnels;
                comboBox2.SelectedIndex = -1;
                comboBox2.Text = name;
                comboBox2.SelectionStart = name.Length;
            }
        }

        private void ComboBox2_MouseDown(object? sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                comboBox2.DroppedDown = true;
            }
        }

        private void RadioButton1_CheckedChanged(object? sender, EventArgs e)
        {
            var obj = (RadioButton)sender;
            if (obj != null)
            {
                if (obj.Name == "radioButton1")
                {
                    if (obj.Checked)
                    {
                        textBox2.Visible = true;
                        textBox2.Enabled = true;
                        comboBox2.Visible = false;
                        comboBox2.Enabled = false;
                        //textBox4.Enabled = true;
                        //comboBox1.Enabled = true;
                    }
                }
                else if (obj.Name == "radioButton2")//人员已录入进行发卡
                {
                    if (obj.Checked)
                    {
                        textBox2.Visible = false;
                        textBox2.Enabled = false;
                        comboBox2.Visible = true;
                        comboBox2.Enabled = true;
                        //textBox4.Enabled = false;
                        comboBox1.Enabled = false;
                        var user = Global.UserListDtos.FirstOrDefault(p => !string.IsNullOrEmpty(comboBox2.Text.Trim()) && !string.IsNullOrEmpty(p.UserName) && p.UserName == comboBox2.Text.Trim());
                        if (user != null && !string.IsNullOrEmpty(user.Phone))
                        {
                            //textBox4.Text = user.Phone;
                            if (!string.IsNullOrEmpty(user.OrgName) && Global.OrgList.Contains(user.OrgName))
                            {
                                comboBox1.Text = user.OrgName;
                            }
                            else
                            {
                                comboBox1.SelectedIndex = -1;
                            }
                        }
                    }
                }
            }
        }

        private void CarMangerPage_SizeChanged(object? sender, EventArgs e)
        {
            panel1.Left = (this.Width - panel1.Width) / 2;
            panel1.Top = (this.Height - panel1.Height) / 2;
        }

        //写卡
        private async void button2_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {
                string Name = string.Empty;

                if (radioButton2.Checked)
                {
                    Name = comboBox2.SelectedItem.ToString();
                }
                else
                {
                    if (string.IsNullOrEmpty(textBox2.Text.Trim()))
                    {
                        MessageBox.Show("提示！！！\n 请输入姓名...");
                        MessageLogNotify.GetInstance.ShowWarning("请输入姓名");
                        return;
                    }
                    var res1 = await HKLibHelper.GetUserList(textBox2.Text.Trim());
                    if (res1?.Count > 0)
                    {
                        MessageBox.Show("提示！！！\n 用户已经存在，请勿重复添加...");
                        MessageLogNotify.GetInstance.ShowWarning("用户已经存在，请勿重复添加");
                        return;
                    }
                    Name = textBox2.Text.Trim();
                }

                string OrgName = comboBox1.Text;
                string worker = new IdWorker(1, 1).NextId().ToString();// ID生成
                UserDto userDto = new UserDto()
                {
                    Name = Name,
                    OrgId = orgTables.FirstOrDefault(p => p.Name == comboBox1.Text)?.SId,
                    CardNo = worker,
                    Num=  HKLibHelper.GetUserMaxNumSync()
                };
                //Task.Factory.StartNew(() =>
                //{
                //写卡
                var res = UHFCardHelper.GetInstance().WriteCard(userDto.CardNo);
                if (res != null && res.Res)
                {
                    MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 写卡成功...");
                    textBox2.Text = String.Empty;
                    button2.Enabled = false;
                }
                else
                {
                    MessageBox.Show($"用户 【{userDto.Name}】 写卡失败，原因：{res?.ResMes}");
                    MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 写卡失败，原因：{res?.ResMes}");
                }
                var result = await HKLibHelper.AddUserAndBindCard(userDto);
                if (result)
                {
                    MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 写卡成功,卡号：{userDto.CardNo}");
                    MessageBox.Show($"用户 【{userDto.Name}】 写卡成功,卡号：{userDto.CardNo}");
                }
                else
                {
                    MessageBox.Show($"用户 【{userDto.Name}】 添加失败，请重试！");
                    MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 添加失败，请重试！");
                }
                //});
            }
            else
            {
                MessageBox.Show("提示！！！\n 设备未连接...");
                MessageLogNotify.GetInstance.ShowWarning("设备未连接");
            }
        }

        //读卡
        private async void button1_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {
                var res = UHFCardHelper.GetInstance().ReadCard();
                if (string.IsNullOrEmpty(res))
                {
                    MessageBox.Show("提示！！！\n 请放入卡片...");
                    MessageLogNotify.GetInstance.Show("请放入卡片");
                    return;
                }
                if (Regex.IsMatch(res, "\\d{19}"))
                {
                    var result = await HKLibHelper.GetUserList("");
                    UserListDto users = null;
                    result.ForEach(item =>
                    {
                        if (item.Cards.FirstOrDefault(t => t.CardNum.Equals(res)) != null)
                        {
                            users = item;
                            return;
                        }
                    });

                    if (users != null)
                    {
                        textBox2.Text = users.Name;
                        if (users.OrgInfo != null && users.OrgInfo.Count > 0)
                        {
                            comboBox1.Text = users.OrgInfo.ElementAt(0).Name;
                        }
                        MessageLogNotify.GetInstance.Show($"读卡成功，当前卡号【{res}】，当前用户【{users.Name}】，详细信息请在页面查看");
                        return;
                    }
                }
                this.Invoke(() => { button2.Enabled = true; });
                MessageLogNotify.GetInstance.Show("读卡成功，该卡是新卡");

            }
            else
            {
                MessageBox.Show("提示！！！\n 设备未连接...");
                MessageLogNotify.GetInstance.ShowWarning("设备未连接");
            }
        }

        #region 批量操作
        /// <summary>
        /// 批量读卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button_pl_read_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {
                var res = UHFCardHelper.GetInstance().ReadCard();
                if (string.IsNullOrEmpty(res))
                {
                    MessageBox.Show("提示！！！\n 请放入卡片,再读卡...");
                    MessageLogNotify.GetInstance.Show("请放入卡片");
                    return;
                }
                if (res.Equals("000"))
                {
                    MessageBox.Show("提示！！！\n 这是一张新卡...");
                }

                if (FirstUser == null)
                {
                    MessageBox.Show("提示！！！\n 没有可以制卡的成员...");
                    MessageLogNotify.GetInstance.ShowWarning("没有可以制卡的成员！");
                    return;
                }

                if (Regex.IsMatch(res, "\\d{19}"))
                {
                    var result = await HKLibHelper.GetUserList("");
                    var users = result.Where(m => m.Cards.Select(x => x.CardNum).Contains(res)).ToList().FirstOrDefault();
                    if (users != null)
                    {
                        MessageLogNotify.GetInstance.Show($"读卡成功，当前卡号【{res}】，当前用户【{users.Name}】，详细信息请在页面查看");
                        return;
                    }
                }
                this.Invoke(() => { button_pl_write.Enabled = true; });
                MessageLogNotify.GetInstance.Show("读卡成功，该卡是新卡");
            }
            else
            {
                MessageBox.Show("提示！！！\n 设备未连接...");
                MessageLogNotify.GetInstance.ShowWarning("设备未连接");
            }
        }
        /// <summary>
        /// 批量写卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button_pl_write_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {

                if (FirstUser == null)
                {
                    MessageBox.Show("提示！！！\n 没有可以制卡的成员...");
                    MessageLogNotify.GetInstance.ShowWarning("没有可以制卡的成员！");
                    return;
                }
                string Name = FirstUser.UserName;
                string OrgName = comboBox1.Text;
                string worker = new IdWorker(1, 1).NextId().ToString();// ID生成
                UserDto userDto = new UserDto()
                {
                    Name = Name,
                    OrgId = orgTables.FirstOrDefault(p => p.Name == FirstUser.OrgName)?.SId,
                    CardNo = worker,
                };
                var res = UHFCardHelper.GetInstance().WriteCard(userDto.CardNo);
                if (res.Res == false)
                {
                    MessageBox.Show("提示！！！\n "+ $"用户 【{userDto.Name}】 写卡失败!");
                    MessageBox.Show($"用户 【{userDto.Name}】 写卡失败!");
                    return;
                }
                var result = await HKLibHelper.AddUserAndBindCard(userDto);
                if (result)
                {
                    MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 写卡成功,卡号：{userDto.CardNo}");
                    MessageBox.Show($"用户 【{userDto.Name}】 写卡成功,卡号：{userDto.CardNo}");
                    RefreshTheData(comboBox_jglb.Text);
                    this.Invoke(() => { button_pl_write.Enabled = false; });
                }
                else {
                    MessageBox.Show($"用户 【{userDto.Name}】 添加失败，请重试！");
                    MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 添加失败，请重试！");
                }
            }
            else
            {
                MessageBox.Show("提示！！！\n 设备未连接...");
                MessageLogNotify.GetInstance.ShowWarning("设备未连接");
            }
        }
        /// <summary>
        /// 文本该
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboBox_jglb_TextChanged(object? sender, EventArgs e)
        {
            try
            {
                RefreshTheData(comboBox_jglb.Text);
            }
            catch (Exception ex)
            {
                MessageLogNotify.GetInstance.ShowWarning(ex.Message);
            }
        }
        /// <summary>
        /// 当前正在插入的用户数据
        /// </summary>
        public UserInfoModel FirstUser { get; set; }
        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="Name"></param>
        public void RefreshTheData(string Name)
        {
            try
            {
                var res = HKLibHelper.GetUserListSync("");
                Global.UserListDtos.Clear();
                res?.ToList()?.ForEach(item =>
                {
                    string status = "";
                    string cardNum = "";
                    if (item.Cards != null && item.Cards.Count > 0)
                    {
                        cardNum = item.Cards.ElementAt(0).CardNum;
                        status = ((CarStatus)item.Cards.ElementAt(0).State).ToString();
                    }
                    Global.UserListDtos.Add(new UserInfoModel()
                    {
                        Num = item.Num,
                        UserName = item.Name,
                        Phone = item.Phone,
                        OrgName = item.OrgInfo?.Count > 0 ? item.OrgInfo.ElementAt(0).Name : "",
                        CardNum = cardNum,
                        State = status
                    });
                });

                List<UserInfoModel> data = Global.UserListDtos?.FindAll(par => string.IsNullOrEmpty(par.CardNum));
                List<UserInfoModel> dataYes = Global.UserListDtos?.FindAll(par => !string.IsNullOrEmpty(par.CardNum));
                if (Name != "全部")
                {
                    data = Global.UserListDtos?.FindAll(par => string.IsNullOrEmpty(par.CardNum) && par.OrgName == Name);
                    dataYes = Global.UserListDtos?.FindAll(par => !string.IsNullOrEmpty(par.CardNum) && par.OrgName == Name);
                }
                dataGridView_No.DataSource = null;
                dataGridView_No.DataSource = data;
                dataGridView1_全部.DataSource = null;
                dataGridView1_全部.DataSource = dataYes;
                if (data != null && data.Count > 0)
                {
                    FirstUser = data.FirstOrDefault();
                    labelName.Text = FirstUser.UserName;
                }
                else
                {
                    FirstUser = null;
                    labelName.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageLogNotify.GetInstance.ShowWarning(ex.Message);
            }
        }
        #endregion

        private async void button6_Click(object sender, EventArgs e)
        {
            if (SqlLogic.GetAdmin() > 3)
            {
                MessageBox.Show("管理员卡制作上限");
                return;
            }

            var CardNo = comboBox4.SelectedValue.ToString();

            var temp = SqlLogic.GetAdmin(CardNo);

            if (temp != null)
            {
                MessageBox.Show("卡号已被使用,请勿重复制作");
                return;
            }

            if (UHFCardHelper.GetInstance().ComOpen)
            {
                string sid = string.Empty;
                var data = (await HKLibHelper.GetOrg()).Where(t => t.Name.Equals("管理员")).FirstOrDefault();
                if (data == null)
                    sid = await HKLibHelper.SetOrg("管理员");
                else
                    sid = data.SId;


                var res = UHFCardHelper.GetInstance().ReadCard();
                if (string.IsNullOrEmpty(res))
                {
                    MessageBox.Show("请放入卡片");
                    MessageLogNotify.GetInstance.Show("请放入卡片");
                    return;
                }
                SqlLogic.AddAmin(CardNo);
                HKLibHelper.AddUserAndBindCardSync(new UserDto
                {
                    Name = "管理员"+CardNo.FirstOrDefault(),
                    CardNo = CardNo,
                    OrgId = sid,
                    Num = HKLibHelper.GetUserMaxNumSync()
                });
                var rr=  UHFCardHelper.GetInstance().WriteCard(CardNo);
                this.Invoke(() =>
                {
                    textBox1.Text = CardNo;
                });


            }
        }

        /// <summary>
        /// 文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox2_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (radioButton1.Checked)
                {
                    if (!string.IsNullOrEmpty(textBox2.Text))
                    {
                        comboBox1.Enabled = true;
                    }
                    else
                        comboBox1.Enabled = false;
                }
                else
                {
                    comboBox1.Enabled = false;
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
