using DevExpress.XtraBars.ToolbarForm;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmRoles : ToolbarForm
    {
        private int SelectedCurrentRowIndex
        {
            get
            {
                return gridView1.FocusedRowHandle;
            }
        }

        private RoleModel CurrentRole
        {
            get
            {
                if (!gridView1.IsValidRowHandle(SelectedCurrentRowIndex))
                    return null;
                return gridView1.GetRow(SelectedCurrentRowIndex) as RoleModel;
            }
        }

        public frmRoles()
        {
            InitializeComponent();
            gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;
            this.Load += FrmRoles_Load;
            gridView1.IndicatorWidth = 40;
        }

        private void GridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void FrmRoles_Load(object sender, EventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            GetDatas();
            splashScreenManager1.TryCloseWait();
        }

        private void GetDatas()
        {
            try
            {
                APIResponseData result = RoleManger.Instance.GetAllRole();
                if (result.Code == 1)
                {
                    List<RoleModel> lst = JsonConvert.DeserializeObject<List<RoleModel>>(result.Data + "");
                    dgvDatas.DataSource = lst;
                    splashScreenManager1.TryCloseWait();
                }
                else
                {
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Error(result.Message);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle >= 0)
                {
                    var resources = new System.ComponentModel.ComponentResourceManager(typeof(frmRoles));
                    if (CurrentRole.RoleStatus)
                    {
                        bBtnModify.Enabled = true;
                        bBtnRoleAuths.Enabled = true;
                        bBtnRoleUsers.Enabled = true;
                        bBtnStop.Enabled = true;
                        this.bBtnStop.Caption = "锁定";
                        this.bBtnStop.ImageOptions.Image = (System.Drawing.Image)resources.GetObject("barButtonItem1.ImageOptions.Image");
                        this.bBtnStop.ImageOptions.LargeImage = (System.Drawing.Image)resources.GetObject("barButtonItem1.ImageOptions.LargeImage");
                    }
                    else
                    {
                        bBtnStop.Enabled = true;
                        bBtnModify.Enabled = false;
                        bBtnRoleAuths.Enabled = false;
                        bBtnRoleUsers.Enabled = false;
                        this.bBtnStop.Caption = "解锁";
                        this.bBtnStop.ImageOptions.Image = (System.Drawing.Image)resources.GetObject("bBtnStop.ImageOptions.Image");
                        this.bBtnStop.ImageOptions.LargeImage = (System.Drawing.Image)resources.GetObject("bBtnStop.ImageOptions.Image");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnModify_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_ROLE_ALTER"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                if (CurrentRole == null)
                {
                    throw new Exception("请先选择角色所在行！");
                }

                frmRoleEdit view = new frmRoleEdit(CurrentRole);
                if (view.ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("操作成功！");
                }
                GetDatas();
            }
            catch (Exception ex)
            {
                GetDatas();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 角色用户查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            new frmRoleUsers(CurrentRole, false).ShowDialog();
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_ROLE_ADD"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                frmRoleEdit view = new frmRoleEdit();
                if (view.ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("操作成功！");
                }
                GetDatas();
            }
            catch (Exception ex)
            {
                GetDatas();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnRoleAuths_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_ROLE_AUTH_ASSIGN"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                frmRoleAuths view = new frmRoleAuths(CurrentRole);
                if (view.ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("权限分配成功！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 用户分配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnRoleUsers_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_ROLE_USER_ASSIGN"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                frmRoleUsers view = new frmRoleUsers(CurrentRole, true);
                if (view.ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("用户分配成功！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 锁定/解除锁定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnStop_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_ROLE_LOCK"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                if (CurrentRole == null)
                    return;

                APIResponseData apiResponseData = RoleManger.Instance.GetRoleAuths(CurrentRole.AutoID, CurrentRole.RoleStatus);
                if (!apiResponseData.IsSuccess)
                {
                    throw new Exception(apiResponseData.Message);
                }

                if ((apiResponseData.ToDeserializeObject<List<AuthModel>>())?.Count > 0)
                {
                    throw new Exception($"角色【{CurrentRole.RoleCode}-{CurrentRole.RoleName}】已绑定权限，不可以锁定！");
                }

                apiResponseData = RoleManger.Instance.GetRoleUsers(CurrentRole.AutoID);
                if (!apiResponseData.IsSuccess)
                {
                    throw new Exception(apiResponseData.Message);
                }

                if (apiResponseData.ToDeserializeObject<List<UserInfoModel>>()?.Count > 0)
                {
                    throw new Exception($"角色【{CurrentRole.RoleCode}-{CurrentRole.RoleName}】已绑定用户，不可以锁定！");
                }

                if (XtraMessageBoxHelper.Ask($"<size=16>确认{bBtnStop.Caption}角色{CurrentRole.RoleCode}-{CurrentRole.RoleName}?<size/>") == DialogResult.OK)
                {
                    splashScreenManager1.ShowWaitForm();

                    CurrentRole.RoleStatus = !CurrentRole.RoleStatus;
                    CurrentRole.ModifyBy = GlobalInfo.CurrentUser.AutoID;

                    apiResponseData = RoleManger.Instance.Update(CurrentRole);
                    if (apiResponseData.Code == -1)
                    {
                        throw new Exception(apiResponseData.Message);
                    }

                    gridView1.RefreshData();
                    splashScreenManager1.TryCloseWait();
                    gridView1.FocusedRowHandle = SelectedCurrentRowIndex > 0 ? 0 : SelectedCurrentRowIndex + 1;
                    XtraMessageBoxHelper.Info("角色更新成功！");
                }
            }
            catch (Exception ex)
            {
                gridView1.RefreshData();
                splashScreenManager1.TryCloseWait();
                gridView1.FocusedRowHandle = SelectedCurrentRowIndex > 0 ? 0 : SelectedCurrentRowIndex + 1;
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var iIndex = comboBoxEdit1.SelectedIndex;
                string cFilterString = "";
                if (iIndex == 0)
                {
                    cFilterString = string.Empty;
                }
                else if (iIndex == 1)
                {
                    cFilterString = "[RoleStatus] = true";
                }
                else if (iIndex == 2)
                {
                    cFilterString = "[RoleStatus] = false";
                }
                gridView1.ActiveFilterString = cFilterString;
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}
