using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;
using WinformDevFramework.Services.System;

namespace WinformDevFramework
{
    public partial class FrmsysDept : BaseForm1
    {
        private IsysDeptServices _sysDeptServices;
        private ISysUserServices _sysUserServices;
        public FrmsysDept(IsysDeptServices sysDeptServices, ISysUserServices sysUserServices)
        {
            _sysDeptServices= sysDeptServices;
            _sysUserServices= sysUserServices;
            InitializeComponent();
        }

        private void InitUI()
        {

        }
        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();
           
            // 设置隐藏列
            this.dataGridViewList.Columns["DeptName"].HeaderText = "机构名称";
            this.dataGridViewList.Columns["PDeptID"].Visible = false;
            this.dataGridViewList.Columns["LeaderID"].Visible = false;
            this.dataGridViewList.Columns["PDeptName"].HeaderText = "上级部门";
            this.dataGridViewList.Columns["LeaderName"].HeaderText="负责人";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";

            LeaderID.DataSource = _sysUserServices.Query();
            LeaderID.DisplayMember = "Fullname";
            LeaderID.ValueMember = "ID";
            LeaderID.DropDownStyle = ComboBoxStyle.DropDownList;
            PDeptID.CanSelectRootNode = true;
            SetParentMenu(_sysDeptServices.Query());
            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);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as sysDept;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();           
            this.DeptName.Text = model.DeptName.ToString();  
            this.LeaderID.SelectedValue = model.LeaderID;  
            this.Remark.Text = model.Remark;

            var pmenu = _sysDeptServices.QueryById(model.PDeptID);
            if (pmenu != null)
            {
                TreeNode node = new TreeNode(pmenu.DeptName);
                node.Name = pmenu.ID.ToString();
                node.Tag = pmenu;
                this.PDeptID.TreeView.SelectedNode = this.PDeptID.TreeView.Nodes.Find(pmenu.ID.ToString(), true).FirstOrDefault();
                this.PDeptID.Text = pmenu.DeptName;
                this.PDeptID.Tag = pmenu.ID;
            }

            
            //初始化 数据列表 列名称
            this.dataGridViewUser.DataSource = GetAllUsers(model.ID);
            this.dataGridViewUser.Columns["Username"]!.HeaderText = "登录名";
            this.dataGridViewUser.Columns["FullName"]!.HeaderText = "呢称";
            this.dataGridViewUser.Columns["Sex"]!.HeaderText = "性别";
            this.dataGridViewUser.Columns["Email"]!.HeaderText = "邮箱";
            this.dataGridViewUser.Columns["PhoneNumber"]!.HeaderText = "手机号码";
            this.dataGridViewUser.Columns["CreateTime"]!.HeaderText = "创建时间";
            this.dataGridViewUser.Columns["LastLoginTime"]!.HeaderText = "最后登录时间";
            this.dataGridViewUser.Columns["Status"]!.HeaderText = "状态";

            this.dataGridViewUser.Columns["Password"].Visible = false;
            this.dataGridViewUser.Columns["ID"].Visible = false;
            this.dataGridViewUser.Columns["DeptID"].Visible = false;
            this.dataGridViewUser.Columns["DeptName"].Visible = false;

            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 (string.IsNullOrEmpty(txtID.Text))
                {
                    sysDept model = new sysDept();
                    // TODO获取界面的数据
                    model.DeptName=this.DeptName.Text;
                    if (PDeptID.TreeView.SelectedNode == null)
                    {
                        model.PDeptID = int.Parse(PDeptID.Tag.ToString());
                    }
                    else
                    {
                        model.PDeptID = ((sysDept)PDeptID.TreeView.SelectedNode.Tag).ID;
                    }
                    model.LeaderID=this.LeaderID.SelectedValue.ToInt32();
                    model.Remark=this.Remark.Text;
                    var id = _sysDeptServices.Insert(model);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    sysDept model = _sysDeptServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.DeptName = this.DeptName.Text;
                    if (PDeptID.TreeView.SelectedNode == null)
                    {
                        model.PDeptID = int.Parse(PDeptID.Tag.ToString());
                    }
                    else
                    {
                        model.PDeptID = ((sysDept)PDeptID.TreeView.SelectedNode.Tag).ID;
                    }
                    model.LeaderID = this.LeaderID.SelectedValue.ToInt32();
                    model.Remark = this.Remark.Text;
                    if (_sysDeptServices.Update(model))
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        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);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _sysDeptServices.DeleteById(Int32.Parse(txtID.Text));
                formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(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()
        {
            if (string.IsNullOrEmpty(DeptName.Text))
            {
                MessageBox.Show("机构名称不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(PDeptID.Text))
            {
                MessageBox.Show("上级机构不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(LeaderID.Text))
            {
                MessageBox.Show("负责人不能为空！");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<sysDept> GetData()
        {
            List<sysDept> data = new List<sysDept>();
            data = _sysDeptServices.QueryMuch<sysDept,sysDept,sysUser,sysDept>((d1,d2,u)=>new object[]
            {
                JoinType.Left,d1.PDeptID==d2.ID,
                JoinType.Left,d1.LeaderID==u.ID
            }, (d1, d2, u) =>
            new sysDept()
            {
                DeptName = d1.DeptName,
                PDeptID = d1.PDeptID,
                LeaderID = d1.LeaderID,
                Remark = d1.Remark,
                PDeptName = d2.DeptName,
                LeaderName = u.Fullname,
                ID=d1.ID,
            });
            return data;
        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        private List<sysUser> GetAllUsers(int id)
        {
            List<sysUser> users = new List<sysUser>();
            GetDeptUser(users, id);
            return users;
        }
        /// <summary>
        /// 上级部门设置
        /// </summary>
        private void SetParentMenu(List<sysDept> menus)
        {
            PDeptID.Nodes.Clear();
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (var menu in menus)
            {
                TreeNode node = new TreeNode(menu.DeptName);
                node.Tag = menu;
                node.Name = menu.ID.ToString();
                nodes.Add(node);
            }

            foreach (var treeNode in nodes)
            {
                var menu = (sysDept)treeNode.Tag;
                treeNode.Nodes.AddRange(nodes.Where(p => menu.ID == ((sysDept)p.Tag).PDeptID).ToArray());
            }

            PDeptID.Nodes.Add(nodes.Where(p => ((sysDept)p.Tag).PDeptID == 0).FirstOrDefault());
        }

        private void GetDeptUser(List<sysUser> users,int id)
        {
            users.AddRange(_sysUserServices.QueryListByClause(p => p.DeptID == id));
            if (_sysDeptServices.Exists(p => p.PDeptID == id))
            {
                List<sysDept> depts= new List<sysDept>();
                depts = _sysDeptServices.QueryListByClause(p => p.PDeptID == id);
                depts.ForEach(p =>
                {
                    GetDeptUser(users, p.ID);
                });
            }
        }
    }
}
