using Common;
using Infragistics.Win.UltraWinTabControl;
using MeterPlugInLibrary;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace JC_MeasuringSystem
{
    /// <summary>
    /// 子窗体在Load事件中若要关闭主窗体则会出现异常，此时我们可以通过委托的方式来处理
    /// </summary>
    //public delegate void EventChildCloseForm(string e);

    public partial class ST_MainForm : Form
    {
        private Hashtable hMenuItem = new Hashtable();
        private string userID = "";
        private string userName = "";

        private CoreAppUser userInfo = null;

        public string UserID
        {
            get { return userID; }
        }

        public string UserName
        {
            get { return userName; }
        }

        public CoreAppUser AppUser
        {
            get { return userInfo; }
        }

        public ST_MainForm(CoreAppUser _userInfo)
        {
            userInfo = _userInfo;
            userID = userInfo.userid;
            userName = userInfo.username;
            userInfo.joindate = DateTime.Now; //loginTime.ToString("yyyy-MM-dd HH:mm:ss:fff");

            InitializeComponent();

            LoadMenuConfig();
        }

        private void LoadMenuConfig()
        {
            string MenuItems = "";

            string roleType = ConfigurationManager.AppSettings["roleType"].ToString().Trim();
            if (roleType == "1")
            {
                #region 通过数据库权限配置来获取值

                try
                {
                    DataSet ds = new DataSet();
                    //测试数据库:192.168.102.45 lims ；正式数据库：192.168.185.183 limsdb;;;pid 890325369868128256表示父级菜单为远程计量
                    string connString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.185.183)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=JGJLDB)));Persist Security Info=True;User ID=sso;Password=sso#2021;";
                    string sql = string.Format(@"select distinct m.MENU_LABEL, m.MENU_URL, m.seq
                                                  from SYS_MENU m, sys_user_role r, SYS_AUTHORIZE a
                                                 where m.p_id = '890325369868128256'
                                                   and m.status = '1'
                                                   and m.menu_id=a.resource_id
                                                   and r.role_id=a.role_id
                                                   and r.user_id='{0}' order by m.seq asc", userID); //  原为and r.user_code='{0}'", userID);2021年4月9日调整

                    using (OracleDataAdapter oadapter = new OracleDataAdapter(sql, connString))
                    {
                        oadapter.Fill(ds);
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            //汽车衡监控:CarMonitor:frmMonitor,
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                MenuItems += dr["MENU_LABEL"].ToString() + ":" + dr["MENU_URL"].ToString() + ",";
                            }
                            MenuItems = MenuItems.Substring(0, MenuItems.Length - 1);
                        }
                        else
                        {
                            MessageBox.Show("当前用户未配置权限");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("获取权限配置信息失败，请联系管理员" + ex);
                }

                #endregion 通过数据库权限配置来获取值
            }
            else
            {
                MenuItems = ConfigurationManager.AppSettings["MenuItem"].ToString().Trim();
            }

            try
            {
                if (!string.IsNullOrEmpty(MenuItems))
                {
                    string[] mis = MenuItems.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries);
                    if (mis.Count() > 0)
                    {
                        foreach (string mi in mis)
                        {
                            string[] mics = mi.Split(new string[] { ":", "：" }, StringSplitOptions.RemoveEmptyEntries);
                            if (mics.Count() >= 3)
                            {
                                ToolStripMenuItem mItem = new System.Windows.Forms.ToolStripMenuItem();
                                mItem.Text = mics[0];
                                mItem.Tag = new ArrayList() { mics[0], mics[1], mics[2] };
                                mItem.Click += new EventHandler(SysMenuItem_Click);
                                this.SystemMainMenu.DropDownItems.Add(mItem);
                            }
                        }
                    }
                }

                ToolStripMenuItem xItem = new System.Windows.Forms.ToolStripMenuItem();
                xItem.Text = "退出";
                xItem.Click += new EventHandler(CloseApp);
                this.SystemMainMenu.DropDownItems.Add(xItem);
            }
            catch { }
        }

        public void SysMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!TabForm.Tabs.Exists(sender.GetHashCode().ToString()))
                {
                    ArrayList mt = (ArrayList)((ToolStripMenuItem)sender).Tag;
                    string assemblyName = mt[1].ToString();
                    string className = mt[2].ToString();
                    Assembly baseFormAssembly = Assembly.Load(assemblyName);
                    Type type = baseFormAssembly.GetType(assemblyName + "." + className);

                    System.Diagnostics.Debug.Assert(type.IsSubclassOf(typeof(Form)));

                    Form form = Activator.CreateInstance(type, true) as Form;
                    form.MdiParent = this;
                    form.Text = mt[0].ToString();
                    //form.WindowState = FormWindowState.Maximized;
                    //form.Size = this.Size;
                    form.Dock = DockStyle.Fill;
                    form.Show();

                    if (!hMenuItem.ContainsKey(sender.GetHashCode()))
                    {
                        hMenuItem.Add(sender.GetHashCode(), form);
                    }

                    UltraTab ut = TabForm.Tabs.Add(sender.GetHashCode().ToString(), mt[0].ToString());
                    ut.Active = true;
                    ut.Selected = true;
                    ut.Tag = form;
                }
                else
                {
                    UltraTab ut = TabForm.Tabs[sender.GetHashCode().ToString()];

                    ut.Active = true;
                    ut.Selected = true;
                    ((Form)(ut.Tag)).Activate();
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "打开界面出错");
            }
        }

        private void CloseApp(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
        {
            if (e.Item.Text.Length == 0 || e.Item.Text == "还原(&R)" || e.Item.Text == "最小化(&N)" || e.Item.Text == "关闭(&C)")
            {
                e.Item.Visible = false;
            }
        }

        private void ST_MainForm_MdiChildActivate(object sender, EventArgs e)
        {
            foreach (UltraTab ut in TabForm.Tabs)
            {
                if (ut.Tag == sender)
                {
                    ut.Selected = true;
                    ut.Active = true;
                }
            }
        }

        private void TabForm_TabClosing(object sender, TabClosingEventArgs e)
        {
            if (e.Tab.Tag != null)
            {
                ((Form)(e.Tab.Tag)).Close();
                TabForm.Tabs.Remove(e.Tab);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (TabForm.Tabs.Count > 0)
                {
                    foreach (UltraTab ut in TabForm.Tabs)
                    {
                        if (ut.Tag == null)
                        {
                            ut.Dispose();
                        }
                        else if (ut.Tag == this.ActiveMdiChild && !ut.Active)
                        {
                            ut.Active = true;
                            ut.Selected = true;
                        }
                    }
                }
            }
            catch { }
        }

        private void TabForm_ActiveTabChanged(object sender, ActiveTabChangedEventArgs e)
        {
            UltraTabControl ut = (UltraTabControl)sender;
            if (ut.ActiveTab.Tag != null)
            {
                ((Form)(ut.ActiveTab.Tag)).Focus();
            }
        }

        private void ST_MainForm_Load(object sender, EventArgs e)
        {
            timer1.Start();

            imageControl.Start();
        }

        //图片控制器含图片压缩及上传sftp
        private ImageControl imageControl = new ImageControl();

        private void ST_MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                imageControl.Stop();
            }
            catch { }

            timer1.Stop();
            Application.Exit();
            //System.Environment.Exit(0);
        }
    }
}