using DevExpress.XtraBars.ToolbarForm;
using DeviceRepair.Models;
using DeviceRepair.Utils.Security;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmUserAdd : ToolbarForm
    {
        /// <summary>
        /// 是否设定用户角色
        /// </summary>
        public bool IsSetUserRoles = false;

        private UserInfoModel CurrentEntity;
        private string OperationType = "新增";

        public frmUserAdd(UserInfoModel entity = null, bool AllocationRole = false, string title = "用户新增")
        {
            InitializeComponent();

            this.Text = title;

            // 关闭右键Customize Layout菜单
            Root.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;

            #region 选项框多选改单选

            // 设置 全选框改为标题
            gridView1.CustomDrawColumnHeader += (s, e) =>
            {
                if (e.Column != null && e.Column.Caption == "Selection")
                {
                    e.Info.Caption = "选择";
                }
            };

            // 选项框多选改单选
            gridView1.RowCellClick += (s, e) =>
            {
                if (e.Column.Caption == "Selection")
                {
                    if (gridView1.SelectedRowsCount > 0)
                    {
                        for (int i = 0; i < this.gridView1.RowCount; i++)
                        {
                            if (e.Clicks == 1 && this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false)
                            {
                                this.gridView1.UnselectRow(i);
                            }
                        }
                    }
                }
            };

            #endregion

            this.Load += FrmRoleAdd_Load;
            if (entity != null)
            {
                OperationType = "修改";
                CurrentEntity = entity;
                bBtnSaveClose.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                txtUserCode.Enabled = false;

                if (AllocationRole)
                {
                    txtEMail.Enabled = false;
                    txtTel.Enabled = false;
                    txtNote.Enabled = false;
                }
            }

            IsSetUserRoles = AllocationRole;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmRoleAdd_Load(object sender, EventArgs e)
        {
            try
            {
                #region 加载角色列表
                if (IsSetUserRoles)
                {
                    txtUserName.Enabled = false;
                    txtTel.Enabled = false;
                    txtPassword.Enabled = false;
                    txtEMail.Enabled = false;
                    txtNote.Enabled = false;
                }

                splashScreenManager1.ShowWaitForm();

                APIResponseData apiResponseData = RoleManger.Instance.GetAllRole();
                if (apiResponseData.IsSuccess)
                {
                    List<RoleModel> lst = apiResponseData.ToDeserializeObject<List<RoleModel>>();
                    dgvRoles.DataSource = lst.Where(x => x.RoleStatus).ToList();

                    if (CurrentEntity != null)
                    {
                        txtUserCode.Text = CurrentEntity.LoginCode;
                        txtUserCode.Tag = CurrentEntity.AutoID;
                        txtUserName.Text = CurrentEntity.RealName;
                        txtTel.Text = CurrentEntity.Phone;
                        txtEMail.Text = CurrentEntity.Email;
                        txtNote.Text = CurrentEntity.Description;
                        txtPassword.Text = string.IsNullOrEmpty(CurrentEntity.PassWord) ? string.Empty : "******";

                        #region 如果修改用户，则不允许修改密码，只能重置密码 Myl20210115

                        txtPassword.Enabled = false;

                        #endregion

                        txtUserCode.Enabled = false;
                        txtUserName.SelectAll();
                        txtUserName.Focus();
                    }

                }
                else
                {
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Error(apiResponseData.Message);
                }

                #endregion

                #region 角色选择

                if (CurrentEntity != null && CurrentEntity.RoleGroup != 0)
                {
                    // 遍历每一行，找到符合条件的行并选择
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        int v = 0;

                        if (int.TryParse(gridView1.GetRowCellValue(i, "AutoID") + "", out v) && v == CurrentEntity.RoleGroup)
                        {
                            gridView1.SelectRow(i);
                            break; // 可以选择中断循环，如果只需要选择第一行
                        }
                    }
                }

                #endregion

                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                if (ValidateData())
                {
                    if (CurrentEntity.AutoID > 0)
                    {
                        CurrentEntity.ModifyBy = GlobalInfo.CurrentUser.AutoID;
                    }
                    else
                    {
                        CurrentEntity.CreateBy = GlobalInfo.CurrentUser.AutoID;
                    }

                    APIResponseData apiResponseData = UserManager.Instance.InsertOrEdit(CurrentEntity);
                    if (apiResponseData.IsSuccess)
                    {
                        if (CurrentEntity.AutoID != 0)
                        {
                            splashScreenManager1.TryCloseWait();
                            DialogResult = System.Windows.Forms.DialogResult.OK;
                            return;
                        }

                        CurrentEntity = null;
                        txtEMail.Text = "";
                        txtNote.Text = "";
                        txtPassword.Text = "";
                        txtTel.Text = "";
                        txtUserCode.Text = "";
                        txtUserName.Text = "";
                        gridView1.ClearSelection();
                        splashScreenManager1.TryCloseWait();
                    }
                    else
                    {
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Error(apiResponseData.Message);
                    }
                }
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 保存并且关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnSaveClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                if (ValidateData())
                {
                    if (CurrentEntity.AutoID > 0)
                    {
                        CurrentEntity.ModifyBy = GlobalInfo.CurrentUser.AutoID;
                    }
                    else
                    {
                        CurrentEntity.CreateBy = GlobalInfo.CurrentUser.AutoID;
                    }

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

                    DialogResult = System.Windows.Forms.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 userCode = string.Empty;
                if (CurrentEntity == null || CurrentEntity.AutoID == 0)
                {
                    userCode = txtUserCode.Text;
                    if (string.IsNullOrWhiteSpace(userCode))
                    {
                        dxErrorProvider1.SetError(txtUserCode, "账号不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (userCode.Trim().Length > 50)
                    {
                        dxErrorProvider1.SetError(txtUserCode, "账号长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else
                    {
                        APIResponseData apiResponseData = UserManager.Instance.ExistLoginCode(userCode);

                        if (!apiResponseData.IsSuccess)
                        {
                            dxErrorProvider1.SetError(txtUserCode, apiResponseData.Message, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                            return false;
                        }
                        else if (apiResponseData.ToBool())
                        {
                            dxErrorProvider1.SetError(txtUserCode, "账号已经存在！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                            return false;
                        }
                        else
                        {
                            dxErrorProvider1.SetError(txtUserCode, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        }
                    }
                }


                string RealName = txtUserName.Text;
                if (string.IsNullOrWhiteSpace(RealName))
                {
                    dxErrorProvider1.SetError(txtUserName, "姓名不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (RealName.Trim().Length > 50)
                {
                    dxErrorProvider1.SetError(txtUserName, "姓名长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txtUserName, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                }

                #region 新密码校验

                string Password = string.Empty;
                if (CurrentEntity == null || CurrentEntity.AutoID == 0)
                {
                    Password = txtPassword.Text;
                    int MinPasswordStrategyTypeCounts = PassWordValidata.Instance.GetTrueNumber(Password);
                    if (string.IsNullOrWhiteSpace(Password))
                    {
                        dxErrorProvider1.SetError(txtPassword, "新密码不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (EncryptionHelper.EncryptByMD5(Password).Length > 50)
                    {
                        dxErrorProvider1.SetError(txtPassword, "新密码长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (EncryptionHelper.EncryptByMD5(Password).Length > 50)
                    {
                        dxErrorProvider1.SetError(txtPassword, "密码长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (PassWordValidata.Instance.PasswordMinLength != 0 && Password.Length < PassWordValidata.Instance.PasswordMinLength)
                    {
                        dxErrorProvider1.SetError(txtPassword, PassWordValidata.Instance.PasswordMinLengthText, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else if (MinPasswordStrategyTypeCounts < 3)
                    {
                        dxErrorProvider1.SetError(txtPassword, $"密码不合符密码强度策略（大写字母/小写字母/数字/特殊字符中最好满足其中3种）！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else
                    {
                        dxErrorProvider1.SetError(txtPassword, $"", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    }
                }

                #endregion

                string Phone = txtTel.Text;
                if (!string.IsNullOrWhiteSpace(Phone))
                {
                    if (!RexEX.TaxMatch(Phone.Trim()) || Phone.Length != 11)
                    {
                        dxErrorProvider1.SetError(txtTel, "手机号码格式不正确！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else
                    {
                        dxErrorProvider1.SetError(txtTel, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    }
                }

                string Email = txtEMail.Text;
                if (!string.IsNullOrWhiteSpace(Email) || Email.Length > 200)
                {
                    if (!RexEX.EmailMatch(Email.Trim()))
                    {
                        dxErrorProvider1.SetError(txtEMail, "邮箱格式不正确！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                        return false;
                    }
                    else
                    {
                        dxErrorProvider1.SetError(txtEMail, "", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    }
                }

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

                CurrentEntity = new UserInfoModel
                {
                    AutoID = CurrentEntity?.AutoID ?? 0,
                    LoginCode = userCode.Trim(),
                    RealName = RealName.Trim(),
                    PassWord = EncryptionHelper.EncryptByMD5(Password),
                    Phone = Phone.Trim(),
                    Email = Email.Trim(),
                    Status = true,
                    Description = description.Trim()
                };

                int[] roles = gridView1.GetSelectedRows();
                if (roles.Length > 0)
                {
                    RoleModel role = (RoleModel)gridView1.GetRow(roles[0]);
                    CurrentEntity.RoleCode = role.RoleCode;
                    CurrentEntity.RoleName = role.RoleName;
                    CurrentEntity.RoleGroup = role.AutoID;
                }

                return true;
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }

            return isSuccess;
        }

        /// <summary>
        /// 查看密码或随机密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPassword_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (!e.Button.Caption.Equals("WATCHPWD"))
                {
                    txtPassword.Text = PasswordStrategy.Instance.GenRandomPassword();
                }
                else
                {
                    txtPassword.Properties.UseSystemPasswordChar = !txtPassword.Properties.UseSystemPasswordChar;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }

        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "DX$CheckboxSelectorColumn")
            {
                if (gridView1.SelectedRowsCount > 0)
                {
                    for (int i = 0; i < this.gridView1.RowCount; i++)
                    {
                        if (e.Clicks == 1 && this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false)
                        {
                            this.gridView1.UnselectRow(i);
                        }
                    }
                }
            }
        }

        private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "DX$CheckboxSelectorColumn")
            {
                e.Info.Caption = "选择";
            }
        }
    }
}
