using CasunCommon.BaseUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace PMSUI
{
    public partial class SettingForm : Form
    {
        //private string m_Permission = "";
        private string m_UserID = "";
        private string m_UserName = "";

        private CWarehouseTypeForm m_CWarehouseTypeForm;
        private CWMSSettingForm m_CWMSSettingForm;
        private CMenuSettingForm m_MenuSettingForm;
        private HistoryDataForm m_HistoryDataForm;
        private DisplayLanguageForm m_DisplayLanguageForm;
        private DisplaySettingForm m_DisplaySettingForm;
        private CStationIDRelatedForm m_CStationIDRelatedForm;
        private CSystemResetForm m_CSystemResetForm;
        private UserSettingForm m_UserSettingForm;
        private CBookTemplateForm m_CTaskTemplateForm;
        private CStepTemplateForm m_CStepTemplateForm;
        private CTaskExceptionHandling m_CTaskExceptionHandling;


        private static SettingForm m_Instance;           // 该类实例对象
        private int m_nNoSignalTime = 0;
        private ToolStripStatusLabel Time = new ToolStripStatusLabel();
        private ToolStripStatusLabel InfoLable = new ToolStripStatusLabel();
        private ToolStripStatusLabel OptTimeCheck = new ToolStripStatusLabel();

        public string UserID
        {
            get
            {
                return m_UserID;
            }
            set
            {
                m_UserID = value;
            }
        }
        public string UserName
        {
            get
            {
                return m_UserName;
            }
            set
            {
                m_UserName = value;
            }
        }

        public static SettingForm Instance
        {
            get
            {
                //if(m_Instance == null)
                //{
                //    m_Instance = new SettingForm();
                //}
                return m_Instance;
            }
        }

        public SettingForm()
        {
            InitializeComponent();
            LoadMenuSetting();
            CLanguageManager.SetLang(this);
            m_Instance = this;
        }

        private void Init()
        {
            InitColor();

            ToolStripStatusLabel Tss;
            Tss = new ToolStripStatusLabel();
            Tss.BackColor = CasunUILib.g_FormBackColor;
            Tss.Text = "用户ID：" + m_UserID;
            statusStrip1.Items.Add(Tss);

            Tss = new ToolStripStatusLabel();
            Tss.BorderSides = ToolStripStatusLabelBorderSides.Left;
            Tss.BackColor = CasunUILib.g_FormBackColor;
            Tss.Text = "用户名：" + m_UserName;
            statusStrip1.Items.Add(Tss);

            //Tss = new ToolStripStatusLabel();
            //Tss.BorderSides = ToolStripStatusLabelBorderSides.Left;
            //Tss.BackColor = CasunUILib.g_FormBackColor;
            //Tss.Text = "权限：" + m_Permission;
            //statusStrip1.Items.Add(Tss);

            //if (!InitPermission())
            //{
            //    Tss.ForeColor = Color.Red;
            //    Tss.Text = "初始化权限失败";
            //}
            InfoLable.BackColor = CasunUILib.g_FormBackColor;
            InfoLable.Spring = true;
            statusStrip1.Items.Add(InfoLable);

            Time.BackColor = CasunUILib.g_FormBackColor;
            Time.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
            Time.BorderSides = ToolStripStatusLabelBorderSides.Left;
            Time.Click += new EventHandler(Time_Click);

            statusStrip1.Items.Add(Time);

            OptTimeCheck.BackColor = CasunUILib.g_FormBackColor;
            OptTimeCheck.Text = "";
            OptTimeCheck.BorderSides = ToolStripStatusLabelBorderSides.Left;
            statusStrip1.Items.Add(OptTimeCheck);

            timer1.Enabled = true;
            timer1.Interval = 500;

            timer_CheckForm.Enabled = true;
            timer_CheckForm.Interval = 1000;
        }


        private void InitColor()
        {
            int a = CasunUILib.g_FormBackColor.A;
            int r = CasunUILib.g_FormBackColor.R + 122 > 255 ? CasunUILib.g_FormBackColor.R - 122 : CasunUILib.g_FormBackColor.R + 122;
            int g = CasunUILib.g_FormBackColor.G + 122 > 255 ? CasunUILib.g_FormBackColor.G - 122 : CasunUILib.g_FormBackColor.G + 122;
            int b = CasunUILib.g_FormBackColor.B + 122 > 255 ? CasunUILib.g_FormBackColor.B - 122 : CasunUILib.g_FormBackColor.B + 122;

            //int a = CasunUILib.g_FormBackColor.A;
            //int r = 255 - CasunUILib.g_FormBackColor.R;
            //int g = 255 - CasunUILib.g_FormBackColor.G;
            //int b = 255 - CasunUILib.g_FormBackColor.B;

            treeViewEx1.SelectColor = Color.LightBlue;
            treeViewEx1.SelectColor2 = Color.LightBlue;
            treeViewEx1.ColorEx = Color.LightBlue;

            //treeViewEx1.SelectColor = Color.FromArgb(a, r, g, b);
            //treeViewEx1.SelectColor2 = Color.FromArgb(a, r - 30 > 0 ? r - 30 : r, g - 30 > 0 ? g - 30 : g, b - 30 > 0 ? b - 30 : b);
            //treeViewEx1.ColorEx = Color.FromArgb(a, r - 60 > 0 ? r - 60 : r, g - 60 > 0 ? g - 60 : g, b - 60 > 0 ? b - 60 : b);

            treeViewEx1.BackColor = Color.FromArgb(CasunUILib.g_FormBackColor.R, CasunUILib.g_FormBackColor.G, CasunUILib.g_FormBackColor.B);
            statusStrip1.BackColor = Color.FromArgb(100, CasunUILib.g_FormBackColor.R, CasunUILib.g_FormBackColor.G, CasunUILib.g_FormBackColor.B);

            foreach (ToolStripStatusLabel con in statusStrip1.Items)
            {
                con.BackColor = CasunUILib.g_FormBackColor;
            }
        }

        /// <summary>
        /// 更新背景色
        /// </summary>
        public void BackColorChangeHandle()
        {
            InitColor();
        }

        private void SettingForm_Load(object sender, EventArgs e)
        {
            Init();
            PromptForm.OpenAction += OpenSettingForm;
        }
        
        private void LoadMenuSetting()
        {
            //清空
            treeViewEx1.Nodes.Clear();
            menuStrip1.Items.Clear();

            #region 获取数据
            List<PmsCoreDB.Model.PMS_sys_MenuSetting> smodelList = PmsCoreDB.DBHost.Instance.MenuSetting.GetModelList("1=1 order by ParentMenuSort,ChildMenuSort");
            Dictionary<string, List<PmsCoreDB.Model.PMS_sys_MenuSetting>> MenuDic = new Dictionary<string, List<PmsCoreDB.Model.PMS_sys_MenuSetting>>();
            
            foreach (PmsCoreDB.Model.PMS_sys_MenuSetting model in smodelList)
            {
                if (!model.IsShow)
                {
                    continue;
                }
                if (!MenuDic.ContainsKey(model.ModuleName))
                {
                    List<PmsCoreDB.Model.PMS_sys_MenuSetting> newModuleList = new List<PmsCoreDB.Model.PMS_sys_MenuSetting>();
                    newModuleList.Add(model);
                    MenuDic.Add(model.ModuleName, newModuleList);
                }
                else
                {
                    if (!MenuDic[model.ModuleName].Contains(model))
                    {
                        MenuDic[model.ModuleName].Add(model);
                    }
                }
            }
            #endregion
            #region 左边树菜单
            foreach (KeyValuePair<string, List<PmsCoreDB.Model.PMS_sys_MenuSetting>> pair in MenuDic)
            {
                //加根节点
                if (!treeViewEx1.Nodes.ContainsKey(pair.Key))
                {
                    TreeNode blankNode = new TreeNode();
                    TreeNode parentNode = new TreeNode(pair.Key);
                    parentNode.Text = pair.Key;
                    parentNode.Name = pair.Key;
                    treeViewEx1.Nodes.Add(blankNode);
                    treeViewEx1.Nodes.Add(parentNode);
                }

                //子节点
                foreach (PmsCoreDB.Model.PMS_sys_MenuSetting item in pair.Value)
                {
                    TreeNode node = new TreeNode(item.MenuName);
                    node.Text = item.DisplayMenuName;
                    node.Name = item.MenuName;

                    foreach (TreeNode parentNode in treeViewEx1.Nodes)
                    {
                        if (parentNode.Text == item.ModuleName)
                        {
                            parentNode.Nodes.Add(node);
                        }
                    }
                }
            }
            #endregion
            #region 上面菜单
            foreach (KeyValuePair<string, List<PmsCoreDB.Model.PMS_sys_MenuSetting>> pair in MenuDic)
            {
                //加根节点
                if (!menuStrip1.Items.ContainsKey(pair.Key))
                {
                    ToolStripMenuItem parentItem = new ToolStripMenuItem();
                    parentItem.Text = pair.Key;
                    menuStrip1.Items.Add(parentItem);
                }

                //子节点
                foreach (PmsCoreDB.Model.PMS_sys_MenuSetting item in pair.Value)
                {
                    ToolStripMenuItem childItem = new ToolStripMenuItem();
                    childItem.Text = item.DisplayMenuName;
                    childItem.Name = item.MenuName;
                    childItem.Click += new EventHandler(toolStripMenuItem_Click);
                    
                    
                    foreach (ToolStripMenuItem parentItem in menuStrip1.Items)
                    {
                        if (parentItem.Text == item.ModuleName)
                        {
                            parentItem.DropDownItems.Add(childItem);
                        }
                    }
                }
            }
            #endregion
        }

        private void Time_Click(object sender, EventArgs e)
        {
            ToolStripStatusLabel item = sender as ToolStripStatusLabel;
            if (item != null)
            {
                PromptForm form = new PromptForm();
                //form.Show();
                form.ShowDialog();
            }
        }

        private void SettingForm_FormClosed(object sender, FormClosedEventArgs e)
        {

            if (m_CWarehouseTypeForm != null)
            {
                m_CWarehouseTypeForm.Close();
            }
            if (m_CWMSSettingForm != null)
            {
                m_CWMSSettingForm.Close();
            }

            m_Instance = null;
            PromptForm.OpenAction -= OpenSettingForm;
            //Dispose();
        }

        public void Dispose()
        {
            //try
            //{
            //    CConfigManager.SaveGlobalData();
            //}
            //catch
            //{ }

            //Process[] process = Process.GetProcesses();
            Process currentProcess = Process.GetCurrentProcess();
            currentProcess.Kill();
            //for (int i = 0; i < process.Count(); i++)
            //{
            //    if (process[i].ProcessName == currentProcess.ProcessName)
            //    {
            //        process[i].Kill();
            //    }
            //}
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            Time.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
            OptTimeCheck.Text = "离线时间：" + m_nNoSignalTime.ToString() + "S";
        }

        #region 界面共性设置
        private void Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            Form sform = sender as Form;
            foreach (TabPage tp in tabControl1.TabPages)
            {
                if (tp.Name == sform.Name)
                {
                    tabControl1.TabPages.Remove(tp);
                }
            }
        }

        /// <summary>
        /// 新建一个 TabPage
        /// </summary>
        /// <param name="frm"></param>
        private void NewTabpage(CasunForm frm, int PermissionLevel)
        {
            if(frm == null)
            {
                return;
            }
            frm.TopLevel = false;
            frm.WindowState = FormWindowState.Normal;
            frm.Dock = DockStyle.Fill;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.BackColor = CasunUILib.g_FormBackColor;
            frm.PermissionLevel = PermissionLevel;
            frm.UserID = m_UserID;

            TabPage Ta = new TabPage();
            Ta.Name = frm.Name;
            Ta.Text = frm.Text;
            Ta.Controls.Add(frm);
            Ta.AutoScroll = true;
            Ta.ToolTipText = "Double click Close";
            tabControl1.TabPages.Add(Ta);
            frm.FormClosed += Form_FormClosed;
            frm.Show();
            tabControl1.SelectedTab = Ta;
        }

        /// <summary>
        /// 显示一个 TabPage
        /// </summary>
        /// <param name="frm"></param>
        private void ShowTabpage(Form frm)
        {
            frm.BackColor = CasunUILib.g_FormBackColor;
            tabControl1.SelectedTab = (TabPage)frm.Parent;
        }


        private void tabControl1_MouseClick(object sender, MouseEventArgs e)
        {

            TabControl tab = sender as TabControl;
            Form sForm = tab.SelectedTab.Controls[0] as Form;
            sForm.BackColor = CasunUILib.g_FormBackColor;
        }

        private void tabControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            TabControl tab = sender as TabControl;
            Form sForm = tab.SelectedTab.Controls[0] as Form;
            sForm.Close();
        }
        #endregion
        
        private void OnCTaskTemplateFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWMSSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CTaskTemplateForm == null)
            {
                m_CTaskTemplateForm = new CBookTemplateForm();
                NewTabpage(m_CTaskTemplateForm, PermissionLevel);
            }
            else if (m_CTaskTemplateForm.IsDisposed)
            {
                m_CTaskTemplateForm = new CBookTemplateForm();
                NewTabpage(m_CTaskTemplateForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CTaskTemplateForm);
            }
        }


        private void OnWMSSettingCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWMSSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CWMSSettingForm == null)
            {
                m_CWMSSettingForm = new CWMSSettingForm();
                NewTabpage(m_CWMSSettingForm, PermissionLevel);
            }
            else if (m_CWMSSettingForm.IsDisposed)
            {
                m_CWMSSettingForm = new CWMSSettingForm();
                NewTabpage(m_CWMSSettingForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CWMSSettingForm);
            }
        }
        private void OnCStepTemplateFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWMSSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CStepTemplateForm == null)
            {
                m_CStepTemplateForm = new CStepTemplateForm();
                NewTabpage(m_CStepTemplateForm, PermissionLevel);
            }
            else if (m_CStepTemplateForm.IsDisposed)
            {
                m_CStepTemplateForm = new CStepTemplateForm();
                NewTabpage(m_CStepTemplateForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CStepTemplateForm);
            }
        }

        private void OnCTaskExceptionHandlingCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWMSSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CTaskExceptionHandling == null)
            {
                m_CTaskExceptionHandling = new CTaskExceptionHandling();
                NewTabpage(m_CTaskExceptionHandling, PermissionLevel);
            }
            else if (m_CTaskExceptionHandling.IsDisposed)
            {
                m_CTaskExceptionHandling = new CTaskExceptionHandling();
                NewTabpage(m_CTaskExceptionHandling, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CTaskExceptionHandling);
            }
        }

        private void OnWarehouseTypeCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWarehouseTypeForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CWarehouseTypeForm == null)
            {
                m_CWarehouseTypeForm = new CWarehouseTypeForm();
                NewTabpage(m_CWarehouseTypeForm, PermissionLevel);
            }
            else if (m_CWarehouseTypeForm.IsDisposed)
            {
                m_CWarehouseTypeForm = new CWarehouseTypeForm();
                NewTabpage(m_CWarehouseTypeForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CWarehouseTypeForm);
            }
        }
        private void OnHistoryDataCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWarehouseTypeForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_HistoryDataForm == null)
            {
                m_HistoryDataForm = new HistoryDataForm();
                NewTabpage(m_HistoryDataForm, PermissionLevel);
            }
            else if (m_HistoryDataForm.IsDisposed)
            {
                m_HistoryDataForm = new HistoryDataForm();
                NewTabpage(m_HistoryDataForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_HistoryDataForm);
            }
        }

        private void OnDisPlayLanguageCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CChargeSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_DisplayLanguageForm == null)
            {
                m_DisplayLanguageForm = new DisplayLanguageForm();
                NewTabpage(m_DisplayLanguageForm, PermissionLevel);
            }
            else if (m_DisplayLanguageForm.IsDisposed)
            {
                m_DisplayLanguageForm = new DisplayLanguageForm();
                NewTabpage(m_DisplayLanguageForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_DisplayLanguageForm);
            }
        }

        private void OnUserSettingFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CChargeSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_UserSettingForm == null)
            {
                m_UserSettingForm = new UserSettingForm();
                NewTabpage(m_UserSettingForm, PermissionLevel);
            }
            else if (m_UserSettingForm.IsDisposed)
            {
                m_UserSettingForm = new UserSettingForm();
                NewTabpage(m_UserSettingForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_UserSettingForm);
            }
        }
      
        private void OnDisplaySettingFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CChargeSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_DisplaySettingForm == null)
            {
                m_DisplaySettingForm = new DisplaySettingForm();
                NewTabpage(m_DisplaySettingForm, PermissionLevel);
            }
            else if (m_DisplaySettingForm.IsDisposed)
            {
                m_DisplaySettingForm = new DisplaySettingForm();
                NewTabpage(m_DisplaySettingForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_DisplaySettingForm);
            }
        }

        private void OnCSystemResetFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CChargeSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CSystemResetForm == null)
            {
                m_CSystemResetForm = new CSystemResetForm();
                NewTabpage(m_CSystemResetForm, PermissionLevel);
            }
            else if (m_CSystemResetForm.IsDisposed)
            {
                m_CSystemResetForm = new CSystemResetForm();
                NewTabpage(m_CSystemResetForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CSystemResetForm);
            }
        }
        private void OnCStationIDRelatedFormCheck()
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CChargeSettingForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_CStationIDRelatedForm == null)
            {
                m_CStationIDRelatedForm = new CStationIDRelatedForm();
                NewTabpage(m_CStationIDRelatedForm, PermissionLevel);
            }
            else if (m_CStationIDRelatedForm.IsDisposed)
            {
                m_CStationIDRelatedForm = new CStationIDRelatedForm();
                NewTabpage(m_CStationIDRelatedForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_CStationIDRelatedForm);
            }
        }
   
        void OpenSettingForm(int eve)
        {
            int PermissionLevel = 0;
            //if (!CheckFormPerimission("CWarehouseTypeForm", out PermissionLevel))
            //{
            //    return;
            //}
            if (m_MenuSettingForm == null)
            {
                m_MenuSettingForm = new CMenuSettingForm();
                NewTabpage(m_MenuSettingForm, PermissionLevel);
            }
            else if (m_MenuSettingForm.IsDisposed)
            {
                m_MenuSettingForm = new CMenuSettingForm();
                NewTabpage(m_MenuSettingForm, PermissionLevel);
            }
            else
            {
                ShowTabpage(m_MenuSettingForm);
            }
        }

        private void timer_CheckForm_Tick(object sender, EventArgs e)
        {
            //m_nNoSignalTime += 1;
            //// 大于10分钟 无操作 界面退出
            //// 优化 根据用户权限不同设置不同的超时时间 权限越高 超时越短
            //if (m_nNoSignalTime > 300)
            //{
            //    this.Close();
            //}
        }

        private void treeViewEx1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            TreeNode tn = e.Node;
            if (tn.Parent != null)
            {
                foreach (TreeNode node in tn.Parent.Nodes)
                {
                    if (tn != node)
                    {
                        node.Collapse();
                    }
                }
            }
            while (tn.Parent != null)
                tn = tn.Parent;

            foreach (TreeNode node in treeViewEx1.Nodes)
            {
                if (tn != node)
                {
                    node.Collapse();
                }
            }
        }
        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            if (item != null)
            {
                OpenForm(item.Name);
            }
        }

        private void treeViewEx1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            OpenForm(e.Node.Name);
        }

        private void OpenForm(string ItemName)
        {
            switch (ItemName)
            {
                case "WarehouseSetting":
                    OnWMSSettingCheck();
                    break;
                case "WarehouseTypeSetting":
                    OnWarehouseTypeCheck();
                    break;
                case "HistoryOrderDataQuery":
                    OnHistoryDataCheck();
                    break;
                case "LanguageSetting":
                    OnDisPlayLanguageCheck();
                    break;
                case "DisplaySetting":
                    OnDisplaySettingFormCheck();
                    break;
                case "StationIDRelateSetting":
                    OnCStationIDRelatedFormCheck();
                    break;
                case "SystemReset":
                    OnCSystemResetFormCheck();
                    break;
                case "UserSetting":
                    OnUserSettingFormCheck();
                    break;
                case "TaskBookTemplateSetting":
                    OnCTaskTemplateFormCheck();
                    break;
                case "OrderExceptionHandling":
                    OnCTaskExceptionHandlingCheck();
                    break;
                case "StepBookTemplateSetting":
                    OnCStepTemplateFormCheck();
                    break;
                default:
                    break;
            }
        }
    }
}
