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

namespace PMSUI
{
    public partial class PermissionSettingForm : CasunForm
    {
        private enum EPermissionShow
        {
            Permission,
            CNFormName,
            PermissionLevel,
            //AuditPermissionLevel,
            Remark,
            Reserved1,
            Reserved2,
            Reserved3
        }

        private int selectRowIndexOfordersDataGridView;         // 记录选中的行号
        private int selectColumnIndexOfordersDataGridView;      // 记录选中的列号
        private int scrollingRowIndexOfordersDataGridView;      // 记录垂直滚动条位置
        private int scrollingColumnIndexOfordersDataGridView;   // 记录水平滚动条的位置
        /// <summary>
        /// 用于事件重复使用
        /// </summary>
        private Dictionary<string, string> DBNameToShowNameDic = new Dictionary<string, string>();

        /// <summary>
        /// 界面名称 对应 显示名称
        /// </summary>
        private Dictionary<string, string> AllFormNameToShowNameDic = new Dictionary<string, string>();
        /// <summary>
        /// 显示名称 对应 界面名称 与 AllFormNameToShowNameDic 存储内容 的key 和Value 相反
        /// </summary>
        private Dictionary<string, string> AllShowNameToFormNameDic = new Dictionary<string, string>();

        public PermissionSettingForm()
        {
            InitializeComponent();
        }

        private void Init()
        {
            cbFormName.Items.Clear();
            cbFormName.Items.Add("");
            foreach (CasunUILib.EForms EForm in Enum.GetValues(typeof(CasunUILib.EForms)))
            {
                if (EForm >= CasunUILib.EForms.UserSetting)
                {
                    if(AllFormNameToShowNameDic.ContainsKey(EForm.ToString()))
                    {
                        cbFormName.Items.Add(AllFormNameToShowNameDic[EForm.ToString()]);
                    }
                    else
                    {
                        string name = CLanguageManager.LanguageChange(EForm.ToString());
                        if(name == "")
                        {
                            cbFormName.Items.Add(EForm.ToString());
                            AllFormNameToShowNameDic.Add(EForm.ToString(), EForm.ToString());
                            AllShowNameToFormNameDic.Add(EForm.ToString(), EForm.ToString());
                        }
                        else
                        {
                            cbFormName.Items.Add(name);
                            AllFormNameToShowNameDic.Add(name, EForm.ToString());
                            AllShowNameToFormNameDic.Add(EForm.ToString(), name);
                        }
                    }
                }
            }

            cbPermissionLevel.Items.Clear();
            cbPermissionLevel.Items.Add("");
            foreach (EPermissionLevel PermissionLev in Enum.GetValues(typeof(EPermissionLevel)))
            {
                cbPermissionLevel.Items.Add(PermissionLev.ToString());
            }

            List<string> PermissionList = PmsCoreDB.DBHost.Instance.PermissionSetting.GetPermission();

            cbPermission.Items.AddRange(PermissionList.ToArray());
            if (PermissionList.Count > 0)
            {
                cbPermission.SelectedIndex = 0;
            }
        }

        private void cbPermission_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadTable();
        }

        private void ResetControl()
        {
            tbPermission.Text = "";
            cbFormName.Text = "";
            cbPermissionLevel.Text = "";
            tbRemark.Text = "";
            tbReserved1.Text = "";
            tbReserved2.Text = "";
            tbReserved3.Text = "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ColumnName"></param>
        /// <returns></returns>
        public static bool GetColumnsIndex(DataTable dt ,string ColumnName,out int Index)
        {
            Index = 0;
            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if(dt.Columns[i].ColumnName == ColumnName)
                    {
                        Index = i;
                        return true;
                    }
                }
            }
            return false;
        }

        private void loadTable()
        {
            ResetControl();
            string strWhere = string.Format( "Permission = '{0}'", cbPermission.Text.ToString());

            if (DGVPermission.CurrentCell != null && DGVPermission.RowCount != 0 && DGVPermission.ColumnCount != 0)
            {
                selectRowIndexOfordersDataGridView = DGVPermission.CurrentCell.RowIndex;
                selectColumnIndexOfordersDataGridView = DGVPermission.CurrentCell.ColumnIndex;
                scrollingRowIndexOfordersDataGridView = DGVPermission.FirstDisplayedScrollingRowIndex;
                scrollingColumnIndexOfordersDataGridView = DGVPermission.FirstDisplayedScrollingColumnIndex;
            }
            DataTable dt = CFormColumnManager.GetDGVDataSource(this.Name, "PMS_sys_PermissionSetting", "order by Permission,CNFormName", strWhere);
            if(DBNameToShowNameDic.ContainsKey("CNFormName"))
            {
                int Index;
                if (GetColumnsIndex(dt, DBNameToShowNameDic["CNFormName"], out Index))
                {
                    for(int count = dt.Rows.Count -1; count >= 0;count--)
                    {
                        DataRow dw = dt.Rows[count];
                        if (AllFormNameToShowNameDic.ContainsKey(dw[Index].ToString()))
                        {
                            dw[Index] = AllFormNameToShowNameDic[dw[Index].ToString()];
                        }
                        else
                        {
                            dt.Rows.RemoveAt(count);
                        }
                    }
                }
            }
            //if (DBNameToShowNameDic.ContainsKey("PermissionLevel"))
            //{
            //    int Index;
            //    if (GetColumnsIndex(dt, DBNameToShowNameDic["PermissionLevel"], out Index))
            //    {
            //        foreach (DataRow dw in dt.Rows)
            //        {
            //            dw[Index] = PerLevIntStrToEnumStr(dw[Index].ToString());
            //        }
            //    }
            //}

            DGVPermission.DataSource = dt;


            int n = DGVPermission.RowCount;
            int m = DGVPermission.ColumnCount;

            if (n != 0 && m != 0)
            {
                if (selectRowIndexOfordersDataGridView < n && selectColumnIndexOfordersDataGridView < m &&
                    scrollingRowIndexOfordersDataGridView < n && scrollingColumnIndexOfordersDataGridView < m)
                {
                    DGVPermission.CurrentCell = DGVPermission.Rows[selectRowIndexOfordersDataGridView].Cells[selectColumnIndexOfordersDataGridView];
                    DGVPermission.FirstDisplayedScrollingRowIndex = scrollingRowIndexOfordersDataGridView;
                    DGVPermission.FirstDisplayedScrollingColumnIndex = scrollingColumnIndexOfordersDataGridView;
                }
            }
        }

        private void InitLabelShow()
        {
            ShowLable(EPermissionShow.Permission, lbSelPermission);
            ShowLable(EPermissionShow.Permission, lbPermission);
            ShowLable(EPermissionShow.CNFormName, lbFormName);
            ShowLable(EPermissionShow.PermissionLevel, lbPermissionLevel);
            ShowLable(EPermissionShow.Remark, lbRemark);
            ShowLable(EPermissionShow.Reserved1, lbReserved1);
            ShowLable(EPermissionShow.Reserved2, lbReserved2);
            ShowLable(EPermissionShow.Reserved2, lbReserved2);
        }

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

            lbPermission.Visible = true;
            tbPermission.Visible = true;

            cbFormName.Visible = true;
            lbFormName.Visible = true;

            List<string> InitControlList = CFormColumnManager.GetNeedShowDBList(this.Name);
            foreach (string str in InitControlList)
            {
                switch (str)
                {
                    case "PermissionLevel":
                        lbPermissionLevel.Visible = true;
                        cbPermissionLevel.Visible = true;
                        break;
                    case "Remark":
                        lbRemark.Visible = true;
                        tbRemark.Visible = true;
                        break;
                    case "Reserved1":
                        lbReserved1.Visible = true;
                        tbReserved1.Visible = true;
                        break;
                    case "Reserved2":
                        lbReserved2.Visible = true;
                        tbReserved2.Visible = true;
                        break;
                    case "Reserved3":
                        lbReserved3.Visible = true;
                        tbReserved3.Visible = true;
                        break;
                    default:
                        break;
                }
            }
        }

        private void DGVPermission_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int DGVCurrentRow = e.RowIndex;

            ResetControl();
            if (DGVCurrentRow != -1 && DGVPermission.Rows[DGVCurrentRow] != null)
            {
                ShowText(tbPermission, EPermissionShow.Permission.ToString(), DGVCurrentRow);

                ShowText(cbFormName, EPermissionShow.CNFormName.ToString(), DGVCurrentRow);

                ShowText1(cbPermissionLevel, EPermissionShow.PermissionLevel.ToString(), DGVCurrentRow);

                ShowText(tbRemark, EPermissionShow.Remark.ToString(), DGVCurrentRow);

                ShowText(tbReserved1, EPermissionShow.Reserved1.ToString(), DGVCurrentRow);

                ShowText(tbReserved2, EPermissionShow.Reserved2.ToString(), DGVCurrentRow);

                ShowText(tbReserved3, EPermissionShow.Reserved3.ToString(), DGVCurrentRow);
            }
        }

        private void ShowLable(EPermissionShow Ekey, Label slable)
        {
            if (DBNameToShowNameDic.ContainsKey(Ekey.ToString()))
                slable.Text = DBNameToShowNameDic[Ekey.ToString()];
        }

        private void ShowText1(ComboBox sControl, string strKey, int DGVCurrentRow)
        {
            if (DBNameToShowNameDic.ContainsKey(strKey) && DGVPermission.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic[strKey]].Value != null)
            {
                string strValue = DGVPermission.Rows[DGVCurrentRow].Cells[DBNameToShowNameDic[strKey]].Value.ToString();

                sControl.Text = PerLevIntStrToEnumStr(strValue);

            }
        }

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

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

            gp_Read.Location = new Point(btHelps.Location.X, gp_Read.Location.Y);
            gp_Opt.Location = new Point(btHelps.Location.X, gp_Opt.Location.Y);
            gp_Opt1.Location = new Point(btHelps.Location.X, gp_Opt1.Location.Y);

            CasunUILib.GroupBoxReadModel(gp_Read,PermissionLevel);
            CasunUILib.GroupBoxReadWriteModel(gp_Opt, PermissionLevel);
            CasunUILib.GroupBoxReadWriteModel(gp_Opt1, PermissionLevel);

            CasunUILib.splitContainerModel(splitContainer1);
            InitFormShow();
            InitLabelShow();
            CasunUILib.DgvModel(DGVPermission);
            //CasunUILib.GroupBoxModel(GP_Per, PermissionLevel);
            Init();
        }

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

            if(!CFormColumnManager.GetAllFormNameToShowNameDic(out AllFormNameToShowNameDic))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("加载界面配置失败，请重启尝试恢复。" ) + "-2");
                return false;
            }

            foreach (string strKey  in AllFormNameToShowNameDic.Keys)
            {
                if (!AllShowNameToFormNameDic.ContainsKey(AllFormNameToShowNameDic[strKey]))
                {
                    AllShowNameToFormNameDic.Add(AllFormNameToShowNameDic[strKey], strKey);
                }
                else
                {
                    MessageBox.Show(CLanguageManager.LanguageChange("加载界面配置失败，请重启尝试恢复。" ) + "-3");
                    //MessageBox.Show("加载界面配置失败，有名称重复的界面配置。");
                    return false;
                }
            }
            return true;
        }

        private bool FormatData(out PmsCoreDB.Model.PMS_sys_PermissionSetting sPermission)
        {
            sPermission = new PmsCoreDB.Model.PMS_sys_PermissionSetting();
            if (!String.IsNullOrEmpty(tbPermission.Text.ToString()) ||
                String.IsNullOrEmpty(cbFormName.Text.ToString())
                   )
            {
                sPermission.Permission = tbPermission.Text.ToString();
                if(AllShowNameToFormNameDic.ContainsKey(cbFormName.Text.ToString()))
                {
                    sPermission.CNFormName = AllShowNameToFormNameDic[cbFormName.Text.ToString()];
                }
                else
                {
                    return false;
                }
                //sPermission.PermissionLevel = CasunUILib.StringToInt32();
                sPermission.PermissionLevel = StringToPermissionLevel(cbPermissionLevel.Text.ToString());
     
                sPermission.Remark = tbRemark.Text;
                sPermission.Reserved1 = tbReserved1.Text;
                sPermission.Reserved2 = tbReserved2.Text;
                sPermission.Reserved3 = tbReserved3.Text;

                sPermission.AuditPermissionLevel = CasunUILib.AuditPermission(
                        sPermission.CNFormName,
                        "",
                        sPermission.Permission,
                        sPermission.PermissionLevel
                        );
                return true;
            }
            else
            {
                return false;
            }
        }


        private string PerLevIntStrToEnumStr(string PermissionLevel)
        {
            EPermissionLevel EPerLev;
            if(Enum.TryParse(PermissionLevel,out EPerLev))
            {
                return EPerLev.ToString();
            }
            else
            {
                return EPermissionLevel.NoPower.ToString();
            }
        }

        private int StringToPermissionLevel(string PermissionLevel)
        {
            EPermissionLevel EPerLev;
            if (Enum.TryParse(PermissionLevel, out EPerLev))
            {
                return (int)EPerLev;
            }
            else
            {
                return (int)EPermissionLevel.NoPower;
            }
        }
        private void btAddPermission_Click(object sender, EventArgs e)
        {
            PmsCoreDB.Model.PMS_sys_PermissionSetting sPermission;
            if(!FormatData(out sPermission))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("添加失败") + "！");
                return;
            }
            else
            {
                if(PmsCoreDB.DBHost.Instance.PermissionSetting.Exists(sPermission.Permission, sPermission.CNFormName))
                {
                    MessageBox.Show(CLanguageManager.LanguageChange("已存在") + "！");
                    return;
                }
                else
                {
                    if (PmsCoreDB.DBHost.Instance.PermissionSetting.Add(sPermission))
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("添加成功") + "！");
                        string strOptLog = string.Format("【AddPermission】:Permission={0},Form ={1},Level = {2}"
                               , sPermission.Permission
                               , sPermission.CNFormName
                               , sPermission.PermissionLevel
                               );
                        COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                        if(!cbPermission.Items.Contains(sPermission.Permission))
                        {
                            cbPermission.Items.Add(sPermission.Permission);
                            cbPermission.Text = sPermission.Permission;
                        }
                    }
                    else
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("添加失败") + "！");
                    }
                    loadTable();
                }
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            PmsCoreDB.Model.PMS_sys_PermissionSetting sPermission;
            if (!FormatData(out sPermission))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请重新选择要处理的行") + "！");
                return;
            }
            else
            {
                string strMsg = CLanguageManager.LanguageChange("删除") + "：【" + sPermission.Permission + "】\r\n" + CLanguageManager.LanguageChange("请谨慎操作") + "！";
                if (MessageBox.Show(strMsg, CLanguageManager.LanguageChange("删除"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                {
                    return;
                }
                else
                {
                    if (PmsCoreDB.DBHost.Instance.PermissionSetting.Delete(sPermission.Permission,sPermission.CNFormName))
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("删除成功") + "！");
                        string strOptLog = string.Format("【DeletePermission】:Permission={0},Form ={1}"
                               , sPermission.Permission
                               , sPermission.CNFormName
                               );
                        COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                    }
                    else
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("删除失败") + "！");
                    }
                    loadTable();
                }
            }
        }

        private void btModfiyStep_Click(object sender, EventArgs e)
        {
            PmsCoreDB.Model.PMS_sys_PermissionSetting sPermission;
            if (!FormatData(out sPermission))
            {
                MessageBox.Show(CLanguageManager.LanguageChange("请重新选择要处理的行") + "！");
                return;
            }
            else
            {
                if (!PmsCoreDB.DBHost.Instance.PermissionSetting.Exists(sPermission.Permission, sPermission.CNFormName))
                {
                    MessageBox.Show(CLanguageManager.LanguageChange("信息不存在") + "！");
                    return;
                }
                else
                {
                    if (PmsCoreDB.DBHost.Instance.PermissionSetting.Update(sPermission))
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("更新成功") + "！");
                        string strOptLog = string.Format("【ModfiyPermission】:Permission={0},Form = {1},Level={2},remark={3},reserved1={4},reserved2={5},reserved3={6}"
                               , sPermission.Permission
                               , sPermission.CNFormName
                               , sPermission.PermissionLevel
                               , sPermission.Remark
                               , sPermission.Reserved1
                               , sPermission.Reserved2
                               , sPermission.Reserved3
                               );
                        COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);

                        if (!cbPermission.Items.Contains(sPermission.Permission))
                        {
                            cbPermission.Items.Add(cbPermission.Text);
                        }
                    }
                    else
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("更新失败") + "！");
                    }
                    loadTable();
                }
            }
        }

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

        private void btDeletePermission_Click(object sender, EventArgs e)
        {
            string strPermission = cbPermission.Text.ToString();
            string strMsg = CLanguageManager.LanguageChange("删除权限") + "：【" + strPermission + "】\r\n" + CLanguageManager.LanguageChange("请谨慎操作") + "！";
            if (MessageBox.Show(strMsg, CLanguageManager.LanguageChange("删除权限"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                if (PmsCoreDB.DBHost.Instance.PermissionSetting.DeletePermission(strPermission))
                {
                    cbPermission.Items.Remove(strPermission);
                    DGVPermission.Rows.Clear();

                    string strOptLog = string.Format("【DeletePermission】:Permission={0}"
                        , strPermission
                        );
                    COperateLog.Instance.InsertOperaterLogAsync(UserID, strOptLog, DateTime.Now);
                }
                else
                {

                }
            }
        }
    }
}
