using HKLib.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XExten.Advance.LinqFramework;

namespace HKCardManager.UserPages
{
    public partial class InstitutionalEntryPage : UserControl
    {
        public InstitutionalEntryPage()
        {
            InitializeComponent();
            DataGridViewInit();
            dataGridView1.DataSource = Global.OrgTables;
            this.SizeChanged += InstitutionalEntryPage_SizeChanged;
        }

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

        private async void DataGridView1_CellContentClick(object? sender, DataGridViewCellEventArgs e)
        {
            try
            {
                {
                    int index = dataGridView1.CurrentRow.Index;
                    if (index >= 0 && index < dataGridView1.Rows.Count)
                    {
                        dataGridView1.Columns[2].ReadOnly = true;
                        dataGridView1.Columns[3].ReadOnly = true;
                        if (dataGridView1.CurrentCell.Value?.ToString() == "删除")
                        {
                            var res = Global.OrgTables.FirstOrDefault(p => p.Name == dataGridView1.Rows[index].Cells[0].Value?.ToString())?.SId;
                            if (string.IsNullOrEmpty(res))
                            {
                                MessageBox.Show("错误！！！\n 获取机构ID失败...");
                                MessageLogNotify.GetInstance.ShowError("获取机构ID失败");
                                return;
                            }
                            try
                            {
                                var tempname = dataGridView1.Rows[index].Cells[0].Value?.ToString();
                                if (MessageBox.Show($"确认是否删除[{tempname}]!", "操作", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    if (await HKLibHelper.DelOrg(res))
                                    {
                                        //Global.OrgTables.Clear();
                                        //Global.OrgTables = HKLibHelper.GetOrg();
                                        var result = await HKLibHelper.GetOrg();
                                        if (result != null)
                                        {
                                            dataGridView1.DataSource = null;
                                            Global.OrgTables.Clear();
                                            Global.OrgTables = result;
                                            dataGridView1.DataSource = Global.OrgTables;
                                        }
                                        MessageBox.Show($"{tempname} 机构删除成功!");
                                        MessageLogNotify.GetInstance.Show($"机构：【{tempname}】 删除成功");
                                    }
                                    else
                                    {
                                        MessageBox.Show($"{tempname} 机构删除失败,请稍后重试...");
                                        MessageLogNotify.GetInstance.ShowError($"机构：【{tempname}】 删除失败");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"机构删除失败,错误原因：" + ex.Message);
                                MessageLogNotify.GetInstance.ShowEx(ex.ToString());
                            }
                            finally
                            {
                                dataGridView1.Columns[2].ReadOnly = false;
                                dataGridView1.Columns[3].ReadOnly = false;
                            }
                        }
                        else if (dataGridView1.CurrentCell.Value?.ToString() == "修改")
                        {
                            var name = dataGridView1.Rows[index].Cells[0].Value?.ToString();//原名称
                            var changeName = dataGridView1.Rows[index].Cells[1].Value?.ToString();//修改后名称
                            if (string.IsNullOrEmpty(name))
                            {
                                MessageBox.Show("错误！！！\n原机构名称无效...");
                                MessageLogNotify.GetInstance.ShowError("原机构名称无效");
                                return;
                            }
                            if (string.IsNullOrEmpty(changeName))
                            {
                                MessageBox.Show("错误！！！\n请输入新机构名称...");
                                MessageLogNotify.GetInstance.ShowError("请输入新机构名称");
                                return;
                            }
                            if (name == changeName)
                            {
                                MessageBox.Show("错误！！！\n新名称和旧名称一致...");
                                MessageLogNotify.GetInstance.ShowError("新名称和旧名称一致，无法修改");
                                return;
                            }
                            var id = Global.OrgTables.FirstOrDefault(p => p.Name == name)?.SId;
                            if (string.IsNullOrEmpty(id))
                            {
                                MessageBox.Show("未找到对应ID.请稍后重试...");
                                MessageLogNotify.GetInstance.ShowError("未找到对应ID");
                                return;
                            }
                            //Task.Factory.StartNew(async () =>
                            //{
                            try
                            {

                                if (await HKLibHelper.AlterOrg(changeName, id))
                                {
                                    var result = await HKLibHelper.GetOrg();
                                    if (result != null)
                                    {
                                        dataGridView1.DataSource = null;
                                        Global.OrgTables.Clear();
                                        Global.OrgTables = result;
                                        dataGridView1.DataSource = Global.OrgTables;
                                    }
                                    MessageBox.Show($"{name} 机构修改成功...");
                                    MessageLogNotify.GetInstance.Show($"{name} 机构修改成功");
                                }
                                else
                                {
                                    MessageBox.Show($"{name} 机构修改失败,请稍后重试...");
                                    MessageLogNotify.GetInstance.ShowError($"{name} 机构修改失败");
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"{name} 机构修改失败,请稍后重试...,错误原因：" + ex.Message);
                                MessageLogNotify.GetInstance.ShowEx(ex.ToString());
                            }
                            finally
                            {
                                this.Invoke(() =>
                                {
                                    dataGridView1.Rows[index].Cells[1].Value = string.Empty;
                                    dataGridView1.Columns[2].ReadOnly = false;
                                    dataGridView1.Columns[3].ReadOnly = false;
                                });
                            }
                            //});

                        }

                    }
                }
                   
            }
            catch (Exception ex)
            {
                MessageLogNotify.GetInstance.ShowEx(ex.ToString());
            }

        }

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

        private async void button2_Click(object sender, EventArgs e)
        {
            string name = this.textBox1.Text.Trim();
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请输入机构名称,在尝试添加...");
                MessageLogNotify.GetInstance.ShowWarning("请输入机构名称");
                return;
            }
            var res = await HKLibHelper.GetOrg();
            if (res?.FirstOrDefault(t => t.Name == name) != null)
            {
                MessageBox.Show("机构已存在请勿重复添加...");
                MessageLogNotify.GetInstance.ShowWarning("机构已存在请勿重复添加");
                return;
            }
       
            this.Invoke(() => { button2.Enabled = false; });
            var result = await HKLibHelper.SetOrg(name);
            if (!string.IsNullOrEmpty(result))
            {
                Global.OrgList.Add(name);
                Global.OrgTables.Add(new HKLib.Dto.OrgDto()
                {
                    Name = name,
                    SId = result
                });
                MessageBox.Show($"【{name}】 机构添加成功...");
                MessageLogNotify.GetInstance.Show($"【{name}】 机构添加成功");
                this.Invoke(() =>
                {
                    dataGridView1.DataSource = null;
                    dataGridView1.DataSource = Global.OrgTables;
                });
            }
            else
            {
                MessageBox.Show($"【{name}】 机构添加失败，请稍后重试...");
                MessageLogNotify.GetInstance.ShowError($"【{name}】 机构添加失败，请重试");
            }
            this.Invoke(() => { button2.Enabled = true; });
        }
    }
}
