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

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmRoleUsers : ToolbarForm
    {
        private RoleModel CurrentRole;

        public frmRoleUsers(RoleModel roleModel, bool IsEdit = false)
        {
            InitializeComponent();
            CurrentRole = roleModel;
            bBtnSave.Enabled = IsEdit;
            this.Load += FrmRoleUsers_Load;
        }

        private void FrmRoleUsers_Load(object sender, EventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = UserManager.Instance.GetAllUsers();
                if (!apiResponseData.IsSuccess)
                {
                    throw new Exception(apiResponseData.Message);
                }

                List<UserInfoModel> userLst = apiResponseData.ToDeserializeObject<List<UserInfoModel>>();
                if (!bBtnSave.Enabled && CurrentRole != null)
                    userLst.RemoveAll(x => x.RoleGroup != CurrentRole.AutoID);

                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;
                    SelectCurrentRoleUsers();
                }

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

        private void SelectCurrentRoleUsers()
        {
            APIResponseData apiResponseData = RoleManger.Instance.GetRoleUsers(CurrentRole.AutoID);
            if (apiResponseData.IsSuccess)
            {
                List<UserInfoModel> lst = apiResponseData.ToDeserializeObject<List<UserInfoModel>>();
                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 bBtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                List<int> vUsers = GetSelectedUsers();
                if (vUsers.Count == 0)
                {
                    splashScreenManager1.SetWaitFormDescription("正在更新角色对应用户数据...");
                    splashScreenManager1.TryCloseWait();
                    if (XtraMessageBoxHelper.Ask($"没有选择任何用户，是否清空角色 {CurrentRole.RoleName} 下的所有用户？") == DialogResult.OK)
                    {
                        //清空角色下的用户
                        APIResponseData apiResponseData = RoleManger.Instance.ClearRoleUsers(CurrentRole.AutoID);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                    }
                }
                else
                {
                    splashScreenManager1.SetWaitFormDescription("正在更新角色对应用户数据...");
                    RoleEditSubmitModel submitModel = new RoleEditSubmitModel();
                    submitModel.Role = CurrentRole;

                    // 用户列表选中项目
                    foreach (int item in vUsers)
                    {
                        submitModel.Users.Add(new UserInfoModel
                        {
                            AutoID = item,
                            ModifyBy = GlobalInfo.CurrentUser.AutoID,
                        });
                    }

                    APIResponseData apiResponseData = RoleManger.Instance.InsertOrEdit(submitModel);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);
                }

                splashScreenManager1.TryCloseWait();
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        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);
            }
        }


        private List<int> GetSelectedUsers()
        {
            int[] ia = gridView1.GetSelectedRows();
            List<int> lstSelectedUsers = new List<int>();
            for (int i = 0; i < ia.Length; i++)
            {
                var vUser = gridView1.GetRow(ia[i]) as UserInfoModel;
                if (!vUser.Status)
                {
                    throw new Exception($"用户{vUser.LoginCode}已锁定，不可以分配角色！");
                }
                var AutoID = gridView1.GetRowCellValue(ia[i], "AutoID")?.ToString().Trim();
                int intAutoID = 0;
                if (int.TryParse(AutoID, out intAutoID))
                {
                    lstSelectedUsers.Add(intAutoID);
                }
            }
            return lstSelectedUsers;
        }
    }
}
