using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraTreeList.Nodes;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmRoleEdit : ToolbarForm
    {
        private RoleModel CurrentRole = null;
        private string OperationType = "新增";

        public frmRoleEdit(RoleModel currentRole = null)
        {
            InitializeComponent();
            CurrentRole = currentRole;
            if (currentRole != null) { OperationType = "修改"; }
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmRoleEdit_Load(object sender, EventArgs e)
        {
            tvAuths.BeforeCheckNode += TvAuths_BeforeCheckNode;
            tvAuths.AfterCheckNode += TvAuths_AfterCheckNode;

            #region 加载窗体数据

            splashScreenManager1.ShowWaitForm();

            try
            {
                APIResponseData apiResponseData = RoleManger.Instance.GetAuthList();
                if (apiResponseData.Code != 1)
                {
                    splashScreenManager1.CloseWaitForm();
                    XtraMessageBoxHelper.Error(apiResponseData.Message);
                    return;
                }
                List<AuthModel> auths = apiResponseData.ToDeserializeObject<List<AuthModel>>();

                tvAuths.DataSource = auths;
                tvAuths.KeyFieldName = "AuthCode";
                tvAuths.ParentFieldName = "FatherAuthCode";
                tvAuths.ExpandAll();


                apiResponseData = UserManager.Instance.GetAllUsers();
                if (!apiResponseData.IsSuccess)
                {
                    throw new Exception(apiResponseData.Message);
                }

                List<UserInfoModel> userLst = apiResponseData.ToDeserializeObject<List<UserInfoModel>>();
                dgvUsers.DataSource = userLst;

                if (CurrentRole != null)
                {
                    txtRoleCode.Tag = CurrentRole.AutoID;
                    txtRoleCode.Text = CurrentRole.RoleCode;
                    txtRoleName.Text = CurrentRole.RoleName;
                    txtRoleDesc.Text = CurrentRole.RoleDescription;
                    txtNote.Text = CurrentRole.RoleNote;
                    SelectCurrentRoleAuths();
                    SelectCurrentRoleUsers();
                    txtRoleCode.Enabled = false;
                    txtRoleName.SelectAll();
                    txtRoleName.Focus();
                }
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }


            #endregion
        }

        private void SelectCurrentRoleAuths()
        {
            APIResponseData result = RoleManger.Instance.GetRoleAuths(CurrentRole.AutoID, CurrentRole.RoleStatus);
            if (result.Code == 1)
            {
                List<AuthModel> lst = result.ToDeserializeObject<List<AuthModel>>();
                if (lst.Count > 0)
                    SelectTreeviewAuths(tvAuths.Nodes, lst);
            }
        }

        private void SelectTreeviewAuths(TreeListNodes tvds, List<AuthModel> auths)
        {
            foreach (TreeListNode item in tvds)
            {
                var drv = tvAuths.GetDataRecordByNode(item) as AuthModel;
                if (drv != null)
                {
                    int authID = drv.AutoID;
                    if (auths.Exists((A) => { return A.AutoID == authID; }))
                    {
                        item.Checked = true;
                    }
                    else
                    {
                        item.Checked = false;
                    }
                }
                else
                {
                    item.Checked = false;
                }
                if (item.HasChildren)
                {
                    item.CheckState = CheckState.Indeterminate;
                    SelectTreeviewAuths(item.Nodes, auths);

                    var vFindUnChecked = item.Nodes.Where(A =>
                    {
                        return A.CheckState == CheckState.Unchecked;
                    });
                    if (vFindUnChecked != null)
                    {
                        if (vFindUnChecked.Count() == 0)
                        {
                            item.CheckState = CheckState.Checked;
                        }
                        else
                        {
                            if (vFindUnChecked.Count() == item.Nodes.Count)
                            {
                                item.CheckState = CheckState.Unchecked;
                            }
                            else
                            {
                                item.CheckState = CheckState.Indeterminate;
                            }
                        }
                    }
                    else
                    {
                        item.CheckState = CheckState.Checked;
                    }
                }
            }
        }

        private void SelectCurrentRoleUsers()
        {
            APIResponseData result = RoleManger.Instance.GetRoleUsers(CurrentRole.AutoID);
            if (result.Code == 1)
            {
                List<UserInfoModel> lst = result.ToDeserializeObject<List<UserInfoModel>>();
                if (lst.Count > 0)
                    SetUserRowSelected(lst);
            }
        }

        private void SetUserRowSelected(List<UserInfoModel> lstUsers)
        {
            if (gridView1.DataSource == null || gridView1.RowCount < 1)
            {
                return;
            }
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                var AutoID = gridView1.GetRowCellValue(i, "AutoID")?.ToString().Trim();
                if (lstUsers.Exists((A) => { return A.AutoID.ToString().Equals(AutoID); }))
                {
                    gridView1.SelectRow(i);
                }
                else
                {
                    gridView1.UnselectRow(i);
                }
            }
        }

        private void TvAuths_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
        }

        private void TvAuths_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
        }

        /// <summary>
        /// 设置子节点的状态
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        /// <summary>
        /// 设置父节点的状态
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool bCheck = false;
                CheckState state;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    state = node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(state))
                    {
                        bCheck = !bCheck;
                        break;
                    }
                }
                node.ParentNode.CheckState = bCheck ? CheckState.Indeterminate : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }

        /// <summary>
        /// 筛选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEdit1_Properties_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var iIndex = comboBoxEdit1.SelectedIndex;
                string cFilterString = "";
                if (iIndex == 0)
                {
                    cFilterString = string.Empty;
                }
                else if (iIndex == 1)
                {
                    cFilterString = "[Status] = true";
                }
                else if (iIndex == 2)
                {
                    cFilterString = "[Status] = false";
                }
                gridView1.ActiveFilterString = cFilterString;
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            try
            {
                if (ValidateData())
                {
                    RoleEditSubmitModel submitModel = new RoleEditSubmitModel();
                    submitModel.Role = CurrentRole;

                    // 权限列表选中项
                    authLst.Clear();
                    if (tvAuths.Nodes.Count > 0)
                    {
                        foreach (TreeListNode root in tvAuths.Nodes)
                        {
                            GetCheckedAuthorizatioId(root);
                        }
                    }
                    if (authLst.Count > 0)
                    {
                        foreach (int item in authLst)
                        {
                            submitModel.RoleAuths.Add(new RoleAuthModel
                            {
                                AuthID = item,
                                CreateBy = GlobalInfo.CurrentUser.AutoID,
                                RoleID = CurrentRole.AutoID,
                                Status = true,
                            });
                        }
                    }

                    List<UserInfoModel> vUsers = GetSelectedUsers();
                    if (vUsers.Count > 0)
                    {
                        submitModel.Users.AddRange(vUsers);
                    }

                    APIResponseData apiResponseData = RoleManger.Instance.InsertOrEdit(submitModel);
                    if (apiResponseData.Code != 1)
                    {
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Error(apiResponseData.Message);
                        return;
                    }
                    splashScreenManager1.TryCloseWait();
                    this.DialogResult = DialogResult.OK;
                }
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据验证
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            bool issuccess = false;

            try
            {
                string roleCode = txtRoleCode.Text;
                if (CurrentRole == null || CurrentRole.AutoID == 0)
                {
                    if (string.IsNullOrWhiteSpace(roleCode))
                    {
                        dxErrorProvider1.SetError(txtRoleCode, "角色编号不能为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (roleCode.Trim().Length > 50)
                    {
                        dxErrorProvider1.SetError(txtRoleCode, "角色编号长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else
                    {
                        APIResponseData apiResponseData = RoleManger.Instance.CheckRoleCodeExists(roleCode.Trim());
                        if (!apiResponseData.IsSuccess)
                        {
                            splashScreenManager1.TryCloseWait();
                            XtraMessageBoxHelper.Error(apiResponseData.Message);
                            return false;
                        }
                        else
                        {
                            if (apiResponseData.ToBool())
                            {
                                dxErrorProvider1.SetError(txtRoleCode, "角色编号已存在！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                                return false;
                            }
                            else
                            {
                                dxErrorProvider1.SetError(txtRoleCode, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                            }
                        }
                    }
                }

                string roleName = txtRoleName.Text;
                if (string.IsNullOrWhiteSpace(roleName))
                {
                    dxErrorProvider1.SetError(txtRoleName, "角色名称不能为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (roleName.Trim().Length > 50)
                {
                    dxErrorProvider1.SetError(txtRoleName, "角色名称长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txtRoleName, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                }

                string roleDesc = txtRoleDesc.Text;
                if (roleDesc.Trim().Length > 500)
                {
                    dxErrorProvider1.SetError(txtRoleDesc, "角色描述长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txtRoleDesc, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                }

                string note = txtNote.Text;
                if (note.Trim().Length > 500)
                {
                    dxErrorProvider1.SetError(txtNote, "备注长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txtNote, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                }

                CurrentRole = new RoleModel
                {
                    AutoID = CurrentRole == null ? 0 : CurrentRole.AutoID,
                    RoleStatus = true,
                    RoleNote = note.Trim(),
                    RoleName = roleName.Trim(),
                    RoleCode = roleCode.Trim(),
                    RoleDescription = roleDesc.Trim(),
                    CreateBy = GlobalInfo.CurrentUser.AutoID,
                    ModifyBy = GlobalInfo.CurrentUser.AutoID
                };
                return true;
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }

            return issuccess;
        }

        private List<int> authLst = new List<int>();//所选择的权限的ID集合
        private void GetCheckedAuthorizatioId(TreeListNode parentNode)
        {
            if (parentNode.Nodes.Count == 0)
            {
                return;//递归终止
            }
            foreach (TreeListNode node in parentNode.Nodes)
            {
                if (node.CheckState == CheckState.Checked || node.CheckState == CheckState.Indeterminate)
                {
                    var drv = tvAuths.GetDataRecordByNode(node) as AuthModel;
                    if (drv != null)
                    {
                        authLst.Add(drv.AutoID);
                    }
                }
                GetCheckedAuthorizatioId(node);
            }
        }

        /// <summary>
        /// 选择用户
        /// </summary>
        /// <returns></returns>
        private List<UserInfoModel> GetSelectedUsers()
        {
            int[] ia = gridView1.GetSelectedRows();
            List<UserInfoModel> lstSelectedUsers = new List<UserInfoModel>();
            for (int i = 0; i < ia.Length; i++)
            {
                var vUser = gridView1.GetRow(ia[i]) as UserInfoModel;
                lstSelectedUsers.Add(vUser);
            }
            return lstSelectedUsers;
        }
    }
}
