using HKCardManager.Message;
using HKCardManager.Servers;
using HKHelper;
using HKLib.Dto;
using HKLib.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HKCardManager.UserPages
{
    public partial class PersonnelEntryPage : UserControl
    {
        //List<OrgDto> orgTables = new List<OrgDto>();

        public PersonnelEntryPage()
        {
            InitializeComponent();
            DataGridViewInit();
            EventInit();
            this.SizeChanged += PersonnelEntryPage_SizeChanged;
            Init();
        }

        private async void Init()
        {
            try
            {
                Global.OrgTables.Clear();
                Global.OrgTables = await HKLibHelper.GetOrg();
                Global.OrgList.Clear();
                Global.OrgTables?.ForEach(item => { Global.OrgList.Add(item.Name); });
                comboBox2.DataSource = Global.OrgList;
                GetUser();

                
            }
            catch (Exception)
            {

            }

            //Task.Factory.StartNew(() => { GetUser(); });
        }

        private void PersonnelEntryPage_SizeChanged(object? sender, EventArgs e)
        {
            this.splitContainer1.SplitterDistance = this.Height - 100;
        }

        private void DataGridViewInit()
        {
            dataGridView1.AllowUserToResizeColumns = false;// 禁止用户改变所有列的列宽 
            dataGridView1.AllowUserToResizeRows = false; //禁止用户改变所有行的行高   
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;  // 禁止用户改变列头的高度   
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; // 禁止用户改变列头的宽度   
            dataGridView1.AutoGenerateColumns = false;//禁用自动添加列
        }

        //获取所有用户信息
        private async void GetUser()
        {
            var res = await HKLibHelper.GetUserList("");
            Global.UserListDtos.Clear();
            var userinfo = new List<UserInfoModel>();
            //Global.PagUserListDtos.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
                });
            });

            for (int i = (currentPageIndex - 1) * pageSize; i < Global.UserListDtos.Count; i++)
            {
                if (userinfo.Count < pageSize)
                    userinfo.Add(Global.UserListDtos.ElementAt(i));
                else
                    break;
            }

            this.Invoke(() =>
            {
                dataGridView1.DataSource = null;
                Global.PagUserListDtos.Clear();
                Global.PagUserListDtos = userinfo;
                dataGridView1.DataSource = Global.PagUserListDtos;
                totalCount = Global.UserListDtos.Count;
                comboBoxNum();
                showDataGirdView();
            });

        }

        //获取单页面用户信息
        private void GetPag()
        {
            Global.PagUserListDtos.Clear();
            for (int i = (currentPageIndex - 1) * pageSize; i < Global.UserListDtos.Count; i++)
            {
                if (Global.PagUserListDtos.Count < pageSize && i >= 0)
                    Global.PagUserListDtos.Add(Global.UserListDtos.ElementAt(i));
                else
                    break;
            }
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = Global.PagUserListDtos;
        }

        //添加用户
        private async void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                MessageBox.Show("请输入姓名,在尝试添加...");
                MessageLogNotify.GetInstance.ShowWarning("请输入姓名");
                return;
            }

            if (Global.UserListDtos.FirstOrDefault(p => p.UserName == textBox1.Text.Trim()) != null)
            {
                MessageBox.Show("用户已经存在，请勿重复添加！");
                MessageLogNotify.GetInstance.ShowWarning("用户已经存在，请勿重复添加");
                return;
            }


            //if (!string.IsNullOrEmpty(textBox2.Text.Trim()))
            //{
            //    if (!textBox2.Text.Trim().IsMobile())
            //    {
            //        MessageLogNotify.GetInstance.ShowWarning("手机号格式不正确");
            //        return;
            //    }
            //}
            UserDto userDto = new UserDto()
            {
                Num = await HKLibHelper.GetUserMaxNum(),
                Name = textBox1.Text.Trim(),
                //Phone = textBox2.Text.Trim(),
                OrgId = Global.OrgTables.FirstOrDefault(p => p.Name == comboBox2.Text)?.SId
            };
            string OrgName = comboBox2.Text;

            this.Invoke(() => { button2.Enabled = false; });
            var res = await HKLibHelper.AddUser(userDto);
            if (res)
            {
                GetUser();
                //this.Invoke(() =>
                //{
                textBox1.Text = string.Empty;
                //textBox2.Text = string.Empty;
                //});
                MessageBox.Show($"用户 【{userDto.Name}】 添加成功");
                MessageLogNotify.GetInstance.Show($"用户 【{userDto.Name}】 添加成功");
            }
            else
            {
                MessageBox.Show($"用户 【{userDto.Name}】 添加失败，请重试！");
                MessageLogNotify.GetInstance.ShowError($"用户 【{userDto.Name}】 添加失败，请重试！");
            }
            //this.Invoke(() => { button2.Enabled = true; });
            button2.Enabled = true;


        }

        //数据表列点击事件
        private async void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                {
                    int index = dataGridView1.CurrentRow.Index;
                    if (index >= 0 && index < dataGridView1.Rows.Count)
                    {
                        if (dataGridView1.CurrentCell.Value?.ToString() == "删除")
                        {
                            var res = dataGridView1.Rows[index].Cells[1].Value?.ToString();
                            if (string.IsNullOrEmpty(res))
                            {
                                MessageBox.Show("用户名无效.请重试!");
                                MessageLogNotify.GetInstance.ShowError("用户名无效");
                                return;
                            }
                            if (MessageBox.Show($"确认是否删除[{res}]!", "操作", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                var result = await HKLibHelper.DisableUser(res);
                                if (result)
                                {
                                    GetUser();
                                    MessageBox.Show($"用户：【{res}】 删除成功");
                                    MessageLogNotify.GetInstance.Show($"用户：【{res}】 删除成功");
                                }
                                else
                                {
                                    MessageBox.Show($"用户：【{res}】 删除失败");
                                    MessageLogNotify.GetInstance.ShowError($"用户：【{res}】 删除失败");
                                }
                            }
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show($"用户删除失败,错误原因：" + ex.Message);
                MessageLogNotify.GetInstance.ShowEx(ex.ToString());
            }

        }

        #region 分页显示

        private int totalCount = 0;//总数据个数
        private int pageCount = 0;//总页数
        private int currentPageIndex = 1;//当前页索引
        private int pageSize = 10;//每页分页大小
        private int remainder = 0;//最后一页剩余个数
        private bool isAutoUpdateLabelTip = true;//获取或设置是否自动更新分页标签内容提示，默认为true

        //事件初始化
        private void EventInit()
        {
            label_first.Click += label_first_Click; //首页
            label_end.Click += label_end_Click;//末页
            label_up.Click += label_up_Click;//上一页
            label_down.Click += label_down_Click;//下一页
            comboBox_page.DropDownClosed += comboBox_page_DropDownClosed;//下拉列表切换页面
            comboBox_num.DropDownClosed += comboBox_num_DropDownClosed;//设置分页大小
            button_go.Click += button_go_Click;//跳转指定页
        }

        //首页
        private void label_first_Click(object? sender, EventArgs e)
        {
            currentPageIndex = 1;
            showDataGirdView();
        }

        //末页
        private void label_end_Click(object? sender, EventArgs e)
        {
            currentPageIndex = pageCount;
            showDataGirdView();
        }

        //上一页
        private void label_up_Click(object? sender, EventArgs e)
        {
            if (currentPageIndex <= pageCount && currentPageIndex != 1)
            {
                currentPageIndex--;
                showDataGirdView();
            }
            if (isAutoUpdateLabelTip) updateSplitPageLabelTip();
        }

        //下一页
        private void label_down_Click(object? sender, EventArgs e)
        {
            if (currentPageIndex < pageCount && currentPageIndex != pageCount)
            {
                currentPageIndex++;
                showDataGirdView();
            }
            if (isAutoUpdateLabelTip) updateSplitPageLabelTip();
        }

        //第几页
        private void comboBox_page_DropDownClosed(object? sender, EventArgs e)
        {
            if (int.TryParse(comboBox_page.Text.Trim(), out int index))
            {
                if (index > 0)
                {
                    currentPageIndex = index;
                    updateSplitPageLabelTip();
                    showDataGirdView();
                }
            }
        }

        //每页条数
        private void comboBox_num_DropDownClosed(object? sender, EventArgs e)
        {
            if (int.TryParse(comboBox_num.Text.Trim(), out int res))
            {
                pageSize = res;
                currentPageIndex = 1; //初始化页码为1
                updateSplitPageLabelTip();
                showDataGirdView();
            }
        }

        //跳转指定页
        private void button_go_Click(object? sender, EventArgs e)
        {
            if (int.TryParse(textBox_num.Text.Trim(), out int num))
            {
                if (num > 0 && num <= pageCount)
                {
                    currentPageIndex = num;
                    currentPageIndex = currentPageIndex > pageCount ? pageCount : currentPageIndex;
                    updateSplitPageLabelTip();
                    showDataGirdView();
                }
                else
                {
                    currentPageIndex = 1;
                    MessageLogNotify.GetInstance.ShowWarning("超出页面范围！");
                }
            }
            else MessageLogNotify.GetInstance.ShowError("请输入指定页面！");
        }

        //修改显示数据
        public void updateSplitPageLabelTip()
        {
            try
            {
                pagingShow();
                comboBoxPage();
                comboBoxNum();
            }
            catch
            {
            }
        }

        //判断显示状状况
        private void pagingShow()
        {
            //共多少页
            pageCount = totalCount / pageSize;
            remainder = totalCount % pageSize;
            pageCount = remainder == 0 ? pageCount : pageCount + 1;
            if (pageCount <= 1)
            {
                label_first.Enabled = false;
                label_end.Enabled = false;
                label_up.Enabled = false;
                label_down.Enabled = false;
                comboBox_page.Enabled = false;
                textBox_num.Enabled = false;
                button_go.Enabled = false;
            }
            else
            {
                label_first.Enabled = true;
                label_end.Enabled = true;
                label_up.Enabled = true;
                label_down.Enabled = true;
                comboBox_page.Enabled = true;
                textBox_num.Enabled = true;
                button_go.Enabled = true;
            }
            //首页关闭首页，上一页
            if (currentPageIndex == 1)
            {
                label_first.Enabled = false;
                label_up.Enabled = false;
            }
            else
            {
                label_first.Enabled = true;
                label_up.Enabled = true;
            }
            //末页关闭末页，下一页
            if (currentPageIndex == pageCount)
            {
                label_end.Enabled = false;
                label_down.Enabled = false;
            }
            else
            {
                label_end.Enabled = true;
                label_down.Enabled = true;
            }
            //共多少条
            label_count.Text = "总" + totalCount + "条/" + pageCount + "页";
            textBox_num.Text = currentPageIndex.ToString();
        }

        //多少页
        private void comboBoxPage()
        {
            comboBox_page.Items.Clear();
            for (int i = 1; i <= pageCount; i++) comboBox_page.Items.Add(i.ToString());
            comboBox_page.SelectedIndex = -1;
            comboBox_page.SelectedIndex = pageCount == 1 ? 0 : currentPageIndex - 1; //当为一页，就设置设置为0
        }

        //每页多少条
        private void comboBoxNum()
        {
            comboBox_num.Items.Clear();
            comboBox_num.Items.Add("10");
            comboBox_num.Items.Add("20");
            comboBox_num.Items.Add("50");
            comboBox_num.Items.Add("100");
            comboBox_num.Items.Add("500");
            comboBox_num.Items.Add("1000");
            comboBox_num.SelectedIndex = 0;
            int i = 0;
            switch (pageSize)
            {
                case 10:
                    i = 0;
                    break;
                case 20:
                    i = 1;
                    break;
                case 50:
                    i = 2;
                    break;
                case 100:
                    i = 3;
                    break;
                case 500:
                    i = 4;
                    break;
                case 1000:
                    i = 5;
                    break;
                default:
                    break;
            }
            comboBox_num.SelectedIndex = i;
        }

        //数据显示
        private void showDataGirdView()
        {
            GetPag();
            updateSplitPageLabelTip();
        }
        #endregion


        #region Excel
        OpaqueCommand cmd = new OpaqueCommand();
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void 导入Excel_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "人员录入|*.xls";
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                cmd.ShowOpaqueLayer(dataGridView1, 125, true);
                var importer = new ExcelImporter();
                IEnumerable<UserDtoModel> result = null;
                //1.添加所有机构名称
                List<string> jg = new List<string>();
                try
                {
                    result = importer.ExcelToObject<UserDtoModel>(openFile.FileName);
                    result?.ToList().ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.OrgId) && !jg.Contains(x.OrgId))
                        {
                            var find = Global.OrgTables.Find(p => p.Name == x.OrgId);
                            if (find == null)
                                jg.Add(x.OrgId);
                        }
                    });
                }
                catch (Exception ex)
                {
                    
                    MessageBox.Show($"导入失败，请先关闭Excel！");
                    cmd.HideOpaqueLayer();
                    return;
                }

                try
                {
                    jg?.ForEach(x =>
                    {
                        HKLibHelper.SetOrgSync(x);
                    });
                    Global.OrgTables = await HKLibHelper.GetOrg();

                    //2.添加用户
                    Dictionary<string, List<UserDtoModel>> RrrorUser = new Dictionary<string, List<UserDtoModel>>();
                    RrrorUser["名字重复"] = new List<UserDtoModel>();
                    RrrorUser["机构不存在"] = new List<UserDtoModel>();
                    RrrorUser["添加出错"] = new List<UserDtoModel>();
                    RrrorUser["成功"] = new List<UserDtoModel>();

                    List<string> name = Global.UserListDtos.Select(o => o.UserName).Distinct().ToList();
                    result?.ToList().ForEach(x =>
                    {
                        if (name.Contains(x.Name))
                        {
                            RrrorUser["名字重复"].Add(x);
                        }
                        else
                        {
                            var find = Global.OrgTables.Find(p =>!string.IsNullOrEmpty(x.OrgId) && p.Name == x.OrgId);
                            if (find == null)
                                RrrorUser["机构不存在"].Add(x);
                            else
                            {
                                var res = HKLibHelper.AddUserSync(new UserDto
                                {
                                    Num = HKLibHelper.GetUserMaxNumSync(),
                                    Name = x.Name,
                                    OrgId = find.SId,
                                });
                                if (!res)
                                {
                                    RrrorUser["添加出错"].Add(x);
                                }
                                else
                                {
                                    RrrorUser["成功"].Add(x);
                                    name.Add(x.Name);
                                }
                            }
                        }
                    });

                    GetUser();

                    string message = string.Empty;
                    foreach (var item in RrrorUser)
                    {
                        if (item.Value.Count > 0)
                        {
                            message += "\n" + item.Key + "列表：\n";
                            (item.Value as List<UserDtoModel>)?.ForEach(par =>
                            {
                                message += par.Name + "[" + par.OrgId + "]  ";
                            });
                        }
                    }
                    MessageLogNotify.GetInstance.Show($"批量录入成功！\n成功{RrrorUser["成功"].Count}条\n失败{(RrrorUser["名字重复"].Count + RrrorUser["机构不存在"].Count + RrrorUser["添加出错"].Count)}条\n");
                    MessageLogNotify.GetInstance.Show($"{message}\n");
                    cmd.HideOpaqueLayer();

                    MessageShow  messageShow = new MessageShow(RrrorUser);
                    messageShow.Show();

                }
                catch (Exception ex)
                {
                    cmd.HideOpaqueLayer();
                    MessageBox.Show($"导入失败，请重试！" + ex.Message);
                    MessageLogNotify.GetInstance.ShowError($"导入失败，请重试！" + ex.Message);
                }
            }
        }
        /// <summary>
        /// 生成Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 生成Excel_Click(object sender, EventArgs e)
        {
            try
            {
                var models = new List<UserDtoModel>
                {
                    new UserDtoModel{OrgId="组织机构1",Name="张三"},
                    new UserDtoModel{OrgId="组织机构2",Name="李四"},
                    new UserDtoModel{OrgId="组织机构2",Name="王麻子"}
                };
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Filter = "人员录入|*.xls";
                string path = string.Empty;
                if (savefile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    path = savefile.FileName;
                    savefile.Dispose();
                    if (!File.Exists(path))
                        File.Create(path).Close();

                    var exporter = new ExcelExporter();
                    var bytes = exporter.ObjectToExcelBytes(models);
                    File.WriteAllBytes(path, bytes);
                    MessageLogNotify.GetInstance.Show("模板生成成功,路径：" + path);
                    MessageLogNotify.GetInstance.Show("尝试打开文件...");
                    //打开文件
                    ProcessStartInfo processStartInfo = new ProcessStartInfo(path);
                    Process process = new Process();
                    process.StartInfo = processStartInfo;
                    process.StartInfo.UseShellExecute = true;
                    process.Start();
                    MessageLogNotify.GetInstance.Show("模板生成成功并打开,请编辑后导入系统！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"模板生成失败，请重试！" + ex.Message);
                MessageLogNotify.GetInstance.ShowError($"模板生成失败，请重试！" + ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var res =  HKLibHelper.GetUserListSync(textBox1.Text);

                Global.UserListDtos.Clear();
                var userinfo = new List<UserInfoModel>();
                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
                    });
                });

                for (int i = (currentPageIndex - 1) * pageSize; i < Global.UserListDtos.Count; i++)
                {
                    if (userinfo.Count < pageSize)
                        userinfo.Add(Global.UserListDtos.ElementAt(i));
                    else
                        break;
                }

                dataGridView1.DataSource = userinfo;
            }
            catch (Exception ex)
            {

            }
        }
    }
}
