using CasunCommon.BaseUI;
using Pms.Common.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PMSUI
{
    public partial class UserSettingForm : CasunForm
    {
        public UserSettingForm()
        {
            InitializeComponent();
        }

        private void Init()
        {
            dgvUserInfo.Columns.Clear();
            dgvUserInfo.DataSource = null;
       
            dgvUserInfo.DataSource = CFormColumnManager.GetDGVDataSource(this.Name, "PMS_sys_UserInfo");


            List<string> PermissionList = PmsCoreDB.DBHost.Instance.PermissionSetting.GetPermission();
            cbPermission.Items.Clear();
            cbPermission.Items.Add("");
            cbPermission.Items.AddRange(PermissionList.ToArray());


            dtpStarttime.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dtpEndtime.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            if (!EntryCheck())
            {
                return;
            }

            if (!CheckPWD())
            {
                return;
            }

            //PMS_sys_UserInfoVo sUserInfo = new PMS_sys_UserInfoVo();
            PmsCoreDB.Model.PMS_sys_UserInfo sUserInfo = new PmsCoreDB.Model.PMS_sys_UserInfo();
            // 内置账号
            if (tbUserID.Text.Trim() == "CasunAdmin")
            {
                MessageBox.Show("不能添加此账户");
                return;
            }
            sUserInfo.UserID = tbUserID.Text.Trim();
            sUserInfo.UserName = tbUserName.Text.Trim();
            sUserInfo.Passwd = tbPassWd.Text.Trim();
            sUserInfo.Permission = cbPermission.Text.ToString();
            sUserInfo.StartTime = dtpStarttime.Value;
            sUserInfo.EndTime = dtpEndtime.Value;
            sUserInfo.AuditPassword = CasunUILib.AuditUserPwd(
                sUserInfo.UserID,
                sUserInfo.Passwd,
                sUserInfo.Permission,
                sUserInfo.StartTime,
                sUserInfo.EndTime);

            //if (CasunModelDB.CDBManager.Instance.PMS_sys_UserInfo.Add(sUserInfo) > 0)
            if(PmsCoreDB.DBHost.Instance.UserInfo.Add(sUserInfo) > 0)
            {
                Init();
                string strOptLog = string.Format("【AddUser】:UserName={0}", tbUserName.Text.Trim());
                strOptLog += "、UserID=" + tbUserID.Text.Trim();
                strOptLog += "、Permission=" + "admin";
                strOptLog += "、Starttime=" + dtpStarttime.Value.ToShortDateString();
                strOptLog += "、Endtime=" + dtpEndtime.Value.ToShortDateString();
                COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                MessageBox.Show(CLanguageManager.LanguageChange("增加成功") + "！", CLanguageManager.LanguageChange("提示信息"));
                tbPassWd.Text = "";
            }
            else
            {
                MessageBox.Show(CLanguageManager.LanguageChange("增加失败") + "！", CLanguageManager.LanguageChange("提示信息"));
            }
        }

        /// <summary>
        /// 输入内容验证
        /// </summary>
        /// <returns></returns>
        private bool EntryCheck()
        {
            bool bResult = true;
            string strMsg = "";

            if (tbUserName.Text == "" && tbUserName.Visible)
            {
                strMsg += "【" + CLanguageManager.LanguageChange("用户名不能为空") + "】\r\n";
                bResult = false;
            }
            if (tbUserID.Text == "" && tbUserID.Visible)
            {
                strMsg += "【" + CLanguageManager.LanguageChange("账号不能为空") + "】\r\n";
                bResult = false;
            }
            if (tbPassWd.Text == "" && tbPassWd.Visible)
            {
                strMsg += "【" + CLanguageManager.LanguageChange("密码不能为空") + "】\r\n";
                bResult = false;
            }
            if (cbPermission.Text == "" && cbPermission.Visible)
            {
                strMsg += "【" + CLanguageManager.LanguageChange("权限不能为空") + "】\r\n";
                bResult = false;
            }

            if (dtpStarttime.Visible && dtpEndtime.Visible)
            {
                int a = dtpStarttime.Value.CompareTo(dtpEndtime.Value);
                if (a > 0)
                {
                    strMsg += "【"
                        + CLanguageManager.LanguageChange("授权结束时间")
                        + CLanguageManager.LanguageChange("不能早于")
                        + CLanguageManager.LanguageChange("授权开始时间")
                        + "】\r\n";
                    bResult = false;
                }
            }
            if (!bResult)
            {
                MessageBox.Show(CLanguageManager.LanguageChange("以下项目输入有误") + "：\r\n" + strMsg, CLanguageManager.LanguageChange("提示信息"));
            }
            return bResult;
        }

        /// <summary>
        /// 密码强度验证
        /// </summary>
        /// <returns></returns>
        private bool CheckPWD()
        {
            string strPwd = tbPassWd.Text;

            // 大小写 特殊字符
            //            var regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=([\x21-\x7e]+)[^a-zA-Z0-9]).{8,30}
            //", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

            var regex = new Regex(@"(?=.*[0-9])(?=.*[a-zA-Z]).{6,30}
", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

            Match m = regex.Match(strPwd);

            if (!m.Success)
            {
                //MessageBox.Show("密码必须包含大小写字母、数字且长度不低于8位");
                string strMsg = string.Format("{0}{1}、{2},{3},"
                    , CLanguageManager.LanguageChange("密码必须包含")
                    , CLanguageManager.LanguageChange("字母")
                    , CLanguageManager.LanguageChange("数字")
                    , CLanguageManager.LanguageChange("长度不低于6位")
                    );

                MessageBox.Show(strMsg);
                return false;
            }
            return true;
        }

        private void btModify_Click(object sender, EventArgs e)
        {
            if (!EntryCheck())
            {
                return;
            }

            if (!CheckPWD())
            {
                return;
            }

            if (dgvUserInfo.CurrentRow == null)
            {
                return;
            }
            int DGVCurrentRow = dgvUserInfo.CurrentRow.Index;
            if (DGVCurrentRow < 0 || dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["UserID"]].Value == null)
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请选择需要处理的信息") + "！");
                return;
            }

            PmsCoreDB.Model.PMS_sys_UserInfo sUserInfo = new PmsCoreDB.Model.PMS_sys_UserInfo();
            sUserInfo.AutoID = (int)dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["AutoID"]].Value;
            // 内置账号
            if (tbUserID.Text.Trim() == "CasunAdmin")
            {
                MessageBox.Show("不能修改为此账户ID");
                return;
            }
            sUserInfo.UserID = tbUserID.Text.Trim();
            sUserInfo.UserName = tbUserName.Text.Trim();
            sUserInfo.Passwd = tbPassWd.Text.Trim();
            sUserInfo.Permission = cbPermission.Text.ToString();
            sUserInfo.StartTime = dtpStarttime.Value;
            sUserInfo.EndTime = dtpEndtime.Value;

            sUserInfo.AuditPassword = CasunUILib.AuditUserPwd(
                sUserInfo.UserID,
                sUserInfo.Passwd,
                sUserInfo.Permission,
                sUserInfo.StartTime,
                sUserInfo.EndTime);
            //if (CasunModelDB.CDBManager.Instance.PMS_sys_UserInfo.Update(sUserInfo))
            if(PmsCoreDB.DBHost.Instance.UserInfo.Update(sUserInfo))
            {
                Init();
                string strOptLog = string.Format("【ModifyUser】:UserName={0}", tbUserName.Text.Trim());
                strOptLog += "、UserID=" + tbUserID.Text.Trim();
                strOptLog += "、Permission=" + "admin";
                strOptLog += "、StartTime=" + dtpStarttime.Value.ToShortDateString();
                strOptLog += "、EndTime=" + dtpEndtime.Value.ToShortDateString();
                COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);
                MessageBox.Show(CLanguageManager.LanguageChange("修改成功") + "！", CLanguageManager.LanguageChange("提示信息"));
                tbPassWd.Text = "";
            }
            else
            {
                MessageBox.Show(CLanguageManager.LanguageChange("修改失败") + "！", CLanguageManager.LanguageChange("提示信息"));
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {

            int DGVCurrentRow = dgvUserInfo.CurrentRow.Index;
            if (DGVCurrentRow != -1)
            {
                int autoid = Convert.ToInt32(dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["AutoID"]].Value);
                string userid = dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["UserID"]].Value.ToString();

                if (userid == "admin")
                {
                    MessageBox.Show(CLanguageManager.LanguageChange("默认管理员用户") + "," + CLanguageManager.LanguageChange("不允许删除") + "！");
                    return;
                }

                string strMsg = CLanguageManager.LanguageChange("删除用户") + "【" + userid + "】，" + CLanguageManager.LanguageChange("是否继续") + "！";
                if (MessageBox.Show(strMsg, CLanguageManager.LanguageChange("删除用户"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                {
                    return;
                }

                //if (CasunModelDB.CDBManager.Instance.PMS_sys_UserInfo.Delete(autoid))
                if(PmsCoreDB.DBHost.Instance.UserInfo.Delete(autoid))
                {
                    string strOptLog = string.Format("【DeleteUser】:UserID={0}", userid);
                    COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                    dgvUserInfo.Rows.RemoveAt(DGVCurrentRow);
                    MessageBox.Show(strOptLog + "，" + CLanguageManager.LanguageChange("成功") + "！", CLanguageManager.LanguageChange("提示信息"));
                }
                else
                {
                    MessageBox.Show(CLanguageManager.LanguageChange("删除失败") + "！", CLanguageManager.LanguageChange("提示信息"));
                }
            }
            else
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请选择需要处理的信息") + "！");
            }
        }

        private void btSee_Click(object sender, EventArgs e)
        {

            int DGVCurrentRow = dgvUserInfo.CurrentRow.Index;
            if (DGVCurrentRow != -1)
            {
                int autoid = Convert.ToInt32(dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic["AutoID"]].Value);

                //CasunModelDB.Model.PMS_sys_UserInfoVo smodel = CasunModelDB.CDBManager.Instance.PMS_sys_UserInfo.GetModel(autoid);

                PmsCoreDB.Model.PMS_sys_UserInfo smodel = PmsCoreDB.DBHost.Instance.UserInfo.GetModel(autoid);

                string strMsg = "UserID：" + smodel.UserID + "\r\n Password：" + smodel.Passwd;
                MessageBox.Show(strMsg);
            }
            else
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请选择需要处理的信息") + "！");
            }
        }

        private void dgvUserInfo_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int DGVCurrentRow = e.RowIndex;
            if (DGVCurrentRow != -1 && dgvUserInfo.Rows[DGVCurrentRow] != null)
            {
                ShowText(tbUserName, "UserName", DGVCurrentRow);
                ShowText(tbUserID, "UserID", DGVCurrentRow);
                ShowText(cbPermission, "Permission", DGVCurrentRow);
                ShowText(dtpStarttime, "StartTime", DGVCurrentRow);
                ShowText(dtpEndtime, "EndTime", DGVCurrentRow);
            }
        }

        private void ShowText(Control sControl, string strKey, int DGVCurrentRow)
        {
            if (DBNameToShowNameDic.ContainsKey(strKey) && dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic[strKey]].Value != null)
            {
                sControl.Text = dgvUserInfo.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic[strKey]].Value.ToString();
            }
        }

        private void UserSettingForm_Load(object sender, EventArgs e)
        {
            if (!InitDBNameToShowNameDic())
            {
                this.Close();
                return;
            }
            CasunUILib.ButtonHelps(btHelps);

            gp_Opt.Location = new Point(btHelps.Location.X, gp_Opt.Location.Y);
            //CasunUILib.GroupBoxReadModel(gp_Read, PermissionLevel);
            CasunUILib.GroupBoxReadWriteModel(gp_Opt, PermissionLevel);

            CasunUILib.splitContainerModel(splitContainer1);
            CasunUILib.DgvModel(dgvUserInfo);
            InitFormShow();
            InitLabelShow();
            Init();
        }

        /// <summary>
        /// 用于事件重复使用
        /// </summary>
        private Dictionary<string, string> DBNameToShowNameDic = new Dictionary<string, string>();

        private bool InitDBNameToShowNameDic()
        {
            if (!CFormColumnManager.GetDBNameToShowNameDic(this.Name, out DBNameToShowNameDic))
            {
                MessageBox.Show("加载界面配置失败，请重启尝试恢复。");
                return false;
            }
            return true;
        }

        private void InitFormShow()
        {
            foreach (Control con in gp_Opt.Controls)
            {
                if (!(con is Button))
                {
                    con.Visible = false;
                }
            }
            //主键显示
            label1.Visible = true;
            tbUserID.Visible = true;
            label2.Visible = true;
            tbPassWd.Visible = true;

            List<string> InitControlList = CFormColumnManager.GetNeedShowDBList(this.Name);
            foreach (string str in InitControlList)
            {
                switch (str)
                {
                    case "UserName":
                        label6.Visible = true;
                        tbUserName.Visible = true;
                        break;
                    case "StartTime":
                        label4.Visible = true;
                        dtpStarttime.Visible = true;
                        break;
                    case "EndTime":
                        label5.Visible = true;
                        dtpEndtime.Visible = true;
                        break;
                    case "Permission":
                        label3.Visible = true;
                        cbPermission.Visible = true;
                        break;
                    default:
                        break;
                }
            }

        }
        private void InitLabelShow()
        {
            if (DBNameToShowNameDic.ContainsKey("UserID"))
                label1.Text = DBNameToShowNameDic["UserID"];
            if (DBNameToShowNameDic.ContainsKey("Passwd"))
                label2.Text = DBNameToShowNameDic["Passwd"];
            if (DBNameToShowNameDic.ContainsKey("UserName"))
                label6.Text = DBNameToShowNameDic["UserName"];
            if (DBNameToShowNameDic.ContainsKey("StartTime"))
                label4.Text = DBNameToShowNameDic["StartTime"];
            if (DBNameToShowNameDic.ContainsKey("EndTime"))
                label5.Text = DBNameToShowNameDic["EndTime"];
            if (DBNameToShowNameDic.ContainsKey("Permission"))
                label3.Text = DBNameToShowNameDic["Permission"];
        }

        private void btHelps_Click(object sender, EventArgs e)
        {
            MessageBox.Show(PMSUI.Config.CConfigManager.gs_FormHelpConfig.GetFormHelp(this.Name));
        }
    }
}
