using HKLib.DB.Model.Entity;
using HKLib.Dto;
using HKLib.Interfaces;
using HKLib.Logic;
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;

namespace HKCardManager.UserPages
{
    public partial class CarMangerPage : UserControl
    {
        //List<string> OrgList = new List<string>();
        List<OrgTable> orgTables = new List<OrgTable>();
        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;


            radioButton1.Checked = true;
            comboBox2.Visible = false;
            orgTables = ServiceHandler.GetOrgList();
            Global.UserListDtos.ForEach(item => { if (!string.IsNullOrEmpty(item.UserName)) Personnels.Add(item.UserName); });
            comboBox2.DataSource = Personnels;
            comboBox1.DataSource = Global.OrgList;
        }

        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 void button2_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {
                if (string.IsNullOrEmpty(textBox2.Text.Trim()))
                {
                    MessageLogNotify.GetInstance.ShowWarning("请输入姓名");
                    return;
                }
                if (!textBox4.Text.Trim().IsMobile())
                {
                    MessageLogNotify.GetInstance.ShowWarning("手机号格式不正确");
                    return;
                }
                string OrgName = comboBox1.Text;
                string worker = new IdWorker(1, 1).NextId().ToString();// ID生成
                UserDto userDto = new UserDto()
                {
                    Name = textBox2.Text.Trim(),
                    Phone = textBox4.Text.Trim(),
                    OrgId = orgTables.FirstOrDefault(p => p.Name == comboBox1.Text)?.SId,
                    CardNo = worker
                };
                Task.Factory.StartNew(() =>
                {
                    this.Invoke(() => { button2.Enabled = false; });
                    //写卡
                    var res = UHFCardHelper.GetInstance().WriteCard(userDto.CardNo);
                    if (res != null && res.Res)
                    {
                        MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 写卡成功");
                    }
                    else
                    {
                        MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 写卡失败，原因：{res?.ResMes}");
                    }

                    if (HKLibHelper.AddUserAndBindCard(userDto))
                    {
                        MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 添加成功");
                    }
                    else
                        MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 添加失败，请重试！");
                    this.Invoke(() => { button2.Enabled = true; });
                });
            }
            else
            {
                MessageLogNotify.GetInstance.ShowError("设备未连接");
            }
        }

        //读卡
        private void button1_Click(object sender, EventArgs e)
        {
            if (UHFCardHelper.GetInstance().ComOpen)
            {
                Task.Factory.StartNew(() =>
                {
                    this.Invoke(() => { button1.Enabled = false; });
                    var res = UHFCardHelper.GetInstance().ReadCard();
                    if (Regex.IsMatch(res, "\\d{19}"))
                    {
                        var users = HKLibHelper.GetUserList("")?.FirstOrDefault(p => p.Cards?.FirstOrDefault(s => s.CardNum == res) != null);
                        if (users != null)
                        {
                            this.Invoke(() =>
                            {
                                textBox2.Text = users.Name;
                                textBox4.Text = users.Phone;
                                if (users.OrgInfo != null && users.OrgInfo.Count > 0)
                                {
                                    comboBox1.Text = users.OrgInfo.ElementAt(0).Name;
                                }
                            });
                            MessageLogNotify.GetInstance.Show("读卡成功，详细信息请在页面查看");
                        }
                    }
                    else
                    {
                        MessageLogNotify.GetInstance.Show("读卡成功，该卡是新卡");
                    }
                    this.Invoke(() => { button1.Enabled = true; });
                });
            }
            else
            {
                MessageLogNotify.GetInstance.ShowWarning("设备未连接");
            }
        }
    }
}
