using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraGrid.Localization;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using DeviceRepair.Utils.Security;
using DeviceRepairAndOptimization.Biz;

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmUsers : DevExpress.XtraBars.ToolbarForm.ToolbarForm
    {
        private UserInfoModel CurrentUser;

        public frmUsers()
        {
            Dictionary<GridStringId, string> gridLocalizer = SetGridLocalizer();

            MyGridLocalizer Localizer = new MyGridLocalizer(gridLocalizer);
            GridLocalizer.Active = Localizer;

            InitializeComponent();
        }

        public Dictionary<GridStringId, string> SetGridLocalizer()
        {
            Dictionary<GridStringId, string> LocalizedKeyValue = new Dictionary<GridStringId, string>();
            LocalizedKeyValue.Add(GridStringId.FindControlFindButton, "查找");
            return LocalizedKeyValue;
        }

        private int m_SelectedCurrentRowIndex;
        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 = "[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 bBtnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_USER_ADD"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                frmUserAdd view = new frmUserAdd(null, false, "用户新增");
                if (view.ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("操作成功！");
                }
                LoadingDatas();
            }
            catch (Exception ex)
            {
                LoadingDatas();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 获取选择的目标,并且更改状态按钮的图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle >= 0)
                {
                    m_SelectedCurrentRowIndex = e.FocusedRowHandle;
                    CurrentUser = gridView1.GetRow(e.FocusedRowHandle) as UserInfoModel;
                    if (CurrentUser != null && CurrentUser.Status)
                    {
                        reposBtnStatus.Buttons[0].ImageOptions.Image = Properties.Resources.LOCK;// (System.Drawing.Image)resources.GetObject("bBtnRoleUsers.ImageOptions.Image");
                        reposBtnStatus.Buttons[0].ToolTip = "锁定用户";
                    }
                    else
                    {
                        reposBtnStatus.Buttons[0].ImageOptions.Image = Properties.Resources.UNLOCK;
                        reposBtnStatus.Buttons[0].ToolTip = "解锁用户";
                    }
                }
                else
                {
                    CurrentUser = null;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }


        private void bBtnModify_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void bBtnRoleAuths_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void bBtnRoleUsers_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void reposBtnUserCode_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reposBtnPwd_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_USER_PWD_RESET"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                m_SelectedCurrentRowIndex = gridView1.FocusedRowHandle;
                if (!gridView1.IsValidRowHandle(m_SelectedCurrentRowIndex))
                {
                    throw new Exception("请先选择用户所在行！");
                }

                CurrentUser = gridView1.GetRow(m_SelectedCurrentRowIndex) as UserInfoModel;
                if (CurrentUser == null)
                {
                    throw new Exception("请先选择用户所在行！");
                }

                if (e.Button.Caption.Contains("密码重置"))
                {
                    if (!CurrentUser.Status)
                    {
                        XtraMessageBoxHelper.Warn("用户已锁定，不可操作！");
                        return;
                    }


                    if (CurrentUser.LoginCode?.Equals(GlobalInfo.CurrentUser.LoginCode) ?? false)
                    {
                        XtraMessageBoxHelper.Warn("不可重置自己！");
                        return;
                    }

                    if (XtraMessageBox.Show($"确认重置用户{CurrentUser.LoginCode}-{CurrentUser.RealName}的密码吗?{Environment.NewLine}<size=16><b><color=red>{e.Button.Caption.Substring(0, 2)}</color><color=blue>密码重置</color></b></size>",
                       "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, allowHtmlText: DevExpress.Utils.DefaultBoolean.True) == DialogResult.OK)
                    {
                        try
                        {
                            splashScreenManager1.ShowWaitForm();
                            splashScreenManager1.SetWaitFormDescription("正在重置用户密码...");
                            var vPwdReset = string.Empty;

                            if (e.Button.Caption.Contains("随机密码重置"))
                            {
                                GenRandomPassword:
                                vPwdReset = PasswordStrategy.Instance.GenRandomPassword();
                                if (EncryptionHelper.EncryptByMD5(vPwdReset) == CurrentUser.PassWord.ToUpper())
                                    goto GenRandomPassword;
                            }
                            else
                            {
                                vPwdReset = ServiceRouteConstValue.USER_DEFAULT_PASSWORD_RESET;
                            }

                            APIResponseData apiResponseData = UserManager.Instance.UpdateUserPassword(CurrentUser.LoginCode, EncryptionHelper.EncryptByMD5(vPwdReset));

                            if (apiResponseData.IsSuccess)
                            {
                                string OperationType = e.Button.Caption.Contains("随机密码重置") ? "随机密码重置" : "默认密码重置";

                                splashScreenManager1.TryCloseWait();
                                LoadingDatas();
                                gridView1.RefreshData();
                                Clipboard.SetDataObject(vPwdReset, true);
                                XtraMessageBox.Show($"用户密码重置成功！<size=16><b><color=red>{vPwdReset}</color></b></size>", "成功", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information, allowHtmlText: DevExpress.Utils.DefaultBoolean.True);
                            }
                            else
                            {
                                throw new Exception(apiResponseData.Message);
                            }
                            splashScreenManager1.TryCloseWait();
                        }
                        catch (Exception ex)
                        {
                            splashScreenManager1.TryCloseWait();
                            XtraMessageBoxHelper.Error(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 用户信息变更/用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reposBtnUserCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_USER_ALTER"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                m_SelectedCurrentRowIndex = gridView1.FocusedRowHandle;
                if (!gridView1.IsValidRowHandle(m_SelectedCurrentRowIndex))
                {
                    throw new Exception("请先选择用户所在行！");
                }

                CurrentUser = gridView1.GetRow(m_SelectedCurrentRowIndex) as UserInfoModel;
                if (CurrentUser == null)
                {
                    throw new Exception("请先选择用户所在行！");
                }

                if (!CurrentUser.Status)
                {
                    throw new Exception("用户已锁定，不可操作！");
                }

                if (e.Button.Caption.Contains("修改"))
                {
                    frmUserAdd view = new frmUserAdd(CurrentUser, false, "用户信息修改");
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                    LoadingDatas();
                }
                else if (e.Button.Caption.Contains("用户角色分配"))
                {
                    frmUserAdd view = new frmUserAdd(CurrentUser, true, "用户角色分配");
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                    LoadingDatas();
                }
            }
            catch (Exception ex)
            {
                LoadingDatas();
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 更新用户状态 锁定/解锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reposBtnStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BASE_USER_LOCK"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                m_SelectedCurrentRowIndex = gridView1.FocusedRowHandle;
                if (!gridView1.IsValidRowHandle(m_SelectedCurrentRowIndex))
                {
                    throw new Exception("请先选择用户所在行！");
                }

                CurrentUser = gridView1.GetRow(m_SelectedCurrentRowIndex) as UserInfoModel;
                if (CurrentUser == null)
                {
                    throw new Exception("请先选择用户所在行！");
                }

                if (CurrentUser.LoginCode?.Equals(GlobalInfo.CurrentUser.LoginCode) ?? false)
                {
                    XtraMessageBoxHelper.Warn("不可锁定/解锁自己！");
                    return;
                }

                getRemark:
                if (XtraMessageBox.Show($"<size=16>确认<b>{(CurrentUser.Status ? "<color=red>锁定<color/>" : "<color=LimeGreen>解锁<color/>")}<b/>用户{CurrentUser.LoginCode}-{CurrentUser.RealName}?<size/>",
                    "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, allowHtmlText: DevExpress.Utils.DefaultBoolean.True) == DialogResult.OK)
                {
                    // 录入原因
                    string result = XtraInputBox.Show("原因录入:", $"请录入用户{(CurrentUser.Status ? "锁定" : "解锁")}原因", "");
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        if (XtraMessageBoxHelper.AskYesNo("原因不能为空，是否继续操作？") == DialogResult.Yes)
                            goto getRemark;
                        return;
                    }

                    CurrentUser.Status = !CurrentUser.Status;
                    CurrentUser.Description = result;
                    APIResponseData apiResponseData = UserManager.Instance.Update(CurrentUser);

                    if (apiResponseData.IsSuccess)
                    {
                        LoadingDatas();
                        gridView1.RefreshData();
                        splashScreenManager1.TryCloseWait();
                        gridView1.FocusedRowHandle = m_SelectedCurrentRowIndex > 0 ? 0 : m_SelectedCurrentRowIndex + 1;
                        XtraMessageBoxHelper.Info("用户更新成功！");
                    }
                    else
                    {
                        throw new Exception(apiResponseData.Message);
                    }

                    //if (apiResult.Code == 1)
                    //{
                    //    HistoryManager.Instance.UserLockHistoryWrite(CurrentUser.AutoID, CurrentUser.Status ? "锁定" : "解锁");

                    //    LoadingDatas();
                    //    gridView1.RefreshData();
                    //    splashScreenManager1.TryCloseWait();
                    //    gridView1.FocusedRowHandle = m_SelectedCurrentRowIndex > 0 ? 0 : m_SelectedCurrentRowIndex + 1;
                    //    XtraMessageBoxHelper.Info("用户更新成功！");
                    //}
                    //else
                    //{
                    //    throw new Exception(apiResult.Message);
                    //}
                }
            }
            catch (Exception ex)
            {
                LoadingDatas();
                gridView1.RefreshData();
                splashScreenManager1.TryCloseWait();
                gridView1.FocusedRowHandle = m_SelectedCurrentRowIndex > 0 ? 0 : m_SelectedCurrentRowIndex + 1;
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void bBtnImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void frmUsers_Load(object sender, EventArgs e)
        {
            gridView1.IndicatorWidth = 40;
            try
            {
                splashScreenManager1.ShowWaitForm();
                LoadingDatas();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        void LoadingDatas()
        {
            try
            {
                APIResponseData apiResponseData = RoleManger.Instance.GetAllRole();
                if (apiResponseData.IsSuccess)
                {
                    List<RoleModel> roles = JsonConvert.DeserializeObject<List<RoleModel>>(apiResponseData.Data + "");
                    Dictionary<int, string> rls = roles.ToDictionary(p => p.AutoID, p => p.RoleName);

                    apiResponseData = UserManager.Instance.GetAllUsers();
                    if (apiResponseData.IsSuccess)
                    {
                        List<UserInfoModel> lst = apiResponseData.ToDeserializeObject<List<UserInfoModel>>();
                        Dictionary<int, UserInfoModel> dict = lst.ToDictionary(x => x.AutoID, x => x);
                        foreach (UserInfoModel item in lst)
                        {
                            if (item.RoleGroup != 0)
                                item.RoleName = rls[item.RoleGroup];

                            item.CreateByName = dict.ContainsKey(item.CreateBy) ? dict[item.CreateBy]?.RealName : "";
                            item.ModifyByName = dict.ContainsKey(item.ModifyBy) ? dict[item.ModifyBy]?.RealName : "";
                        }

                        dgvDatas.DataSource = lst;
                        gridView1.BestFitColumns();
                    }
                }
                else
                {
                    XtraMessageBoxHelper.Error(apiResponseData.Message);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        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();
                e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
            }
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "ModifyDate" || e.Column.FieldName == "LastLoginTime" || e.Column.FieldName == "CreateDate" || e.Column.FieldName == "LastPwdAlterTime")
            {
                if (e.Value == null || e.Value == DBNull.Value || (DateTime)e.Value == DateTime.Parse("1753-01-01"))
                {
                    e.DisplayText = "";
                }
            }
        }
    }
}
