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 SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;

using WinformDevFramework.Services.System;
using DbType = SqlSugar.DbType;

namespace WinformDevFramework
{
    public partial class FrmDataSource : BaseForm1
    {
        private ISysDataSourceServices _dataSourceServices;
        public FrmDataSource(ISysDataSourceServices sysDataSourceServices)
        {
            _dataSourceServices = sysDataSourceServices;
            InitializeComponent();
        }

        public override void Init()
        {
            base.Init();
            //初始化 数据列表 列名称
            this.dataGridViewList.DataSource = GetAllDataSources();
            this.dataGridViewList.Columns["ConnectName"]!.HeaderText = "连接名";
            this.dataGridViewList.Columns["Host"]!.HeaderText = "主机";
            this.dataGridViewList.Columns["DataBaseName"]!.HeaderText = "数据库";
            this.dataGridViewList.Columns["Username"]!.HeaderText = "用户名";

            this.dataGridViewList.Columns["Password"].Visible = false;

            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as sysDataSource;
            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.txtConnectName.Text = model.ConnectName;
            this.txtHost.Text = model.Host;
            this.txtDataBaseName.Text = model.DataBaseName;
            this.txtUsername.Text = model.Username;
            this.txtPW.Text = model.Password;
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            //if (ValidateData())
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    sysDataSource newDataSource = new sysDataSource();
                    newDataSource.Username= txtUsername.Text;
                    newDataSource.ConnectName= txtConnectName.Text;
                    newDataSource.Host= txtHost.Text;
                    newDataSource.DataBaseName= txtDataBaseName.Text;
                    newDataSource.Password = txtPW.Text;
                    var id = _dataSourceServices.Insert(newDataSource);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    sysDataSource dataSource = _dataSourceServices.QueryById(int.Parse(txtID.Text));
                    dataSource.Username = txtUsername.Text;
                    dataSource.ConnectName = txtConnectName.Text;
                    dataSource.Host = txtHost.Text;
                    dataSource.DataBaseName = txtDataBaseName.Text;
                    dataSource.Password = txtPW.Text;
                    if (_dataSourceServices.Update(dataSource))
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                SetToolButtonStatus(formStatus);
                var menus = GetAllDataSources();
                this.dataGridViewList.DataSource = menus;
            }
            
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;

        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _dataSourceServices.DeleteById(Int32.Parse(txtID.Text));
                SetToolButtonStatus(formStatus);
                var menus = GetAllDataSources();
                this.dataGridViewList.DataSource = menus;
            }
        }

        public override void CloseFunction(object sender, EventArgs e)
        {
            base.CloseFunction(sender, e);
        }

        private List<sysDataSource> GetAllDataSources()
        {
            return _dataSourceServices.Query();
        }
        /// <summary>
        /// 设置功能按钮状态
        /// </summary>
        public override void SetToolButtonStatus(FormStatus status)
        {
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }
        //验证数据
        public override bool ValidateData()
        {
            bool result = false;
            if (string.IsNullOrEmpty(txtConnectName.Text))
            {
                MessageBox.Show("连接名不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtHost.Text))
            {
                MessageBox.Show("主机不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtDataBaseName.Text))
            {
                MessageBox.Show("数据库不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("用户名不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtPW.Text))
            {
                MessageBox.Show("密码不能为空！");
                return result;
            }
            result = true;
            return result;
        }

        /// <summary>
        /// 测试链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                var connectionString =
                    $"Server={txtHost.Text};Database={txtDataBaseName.Text};User Id = {txtUsername.Text}; Password={txtPW.Text}";
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = connectionString
                       ,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });
                try
                {
                    db.Open();
                    MessageBox.Show("连接成功！");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }
    }
}
