using LabelManager2;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using UAS_MES_NEW.CustomControl.AccordionMenu;
using UAS_MES_NEW.DataOperate;
using UAS_MES_NEW.Entity;
using UAS_MES_NEW.Properties;
using UAS_MES_NEW.PublicMethod;

namespace UAS_MES_NEW
{
    public partial class Main : Form
    {
        //所有用到了headBar的部分都需要这段代码
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
        public static extern int GetWindowLong(HandleRef hWnd, int nIndex);

        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong);

        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        string SerialPort1 = "Make!ColorBoxWeigh#Make!CartonBoxWeigh";

        Thread thread;

        DataHelper dh = SystemInf.dh;

        string sysdisc = Environment.GetEnvironmentVariable("windir").Substring(0, 1);
        string lblpath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":\Log\cacheInfo";

        public Main()
        {
            InitializeComponent();
            DoubleBuffered = true;
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }

        /// <summary>
        /// 删除7天前的日志
        /// </summary>
        private void DeleteLog()
        {
            DirectoryInfo dir = new DirectoryInfo(sysdisc + @":\Log");
            List<string> DeleteFileName = new List<string>();
            //保存6天前和今天的操作日志
            for (int i = 1; i <= 30; i++)
            {
                DeleteFileName.Add(System.DateTime.Now.AddDays(-i).ToString("yyyy-MM-dd") + ".txt");
            }
            DeleteFileName.Add(System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
            if (dir.Exists)
            {
                FileInfo[] file = dir.GetFiles();
                foreach (FileInfo f in file)
                {
                    if (!DeleteFileName.Contains(f.Name))
                        f.Delete();
                }
            }
        }

        //tabPage标签图片尺寸
        const int CLOSE_SIZE = 16;
        //窗体加载的时候将headBar的事件委托给指定的函数
        private void Main_Load(object sender, EventArgs e)
        {
            Closelblprocess();
            thread = new Thread(DeleteLog);
            thread.Start();
            this.Tag = "ShowDialogWindow";
            this.MainTabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MainTabControl.Padding = new Point(CLOSE_SIZE + 10, CLOSE_SIZE);
            this.MainTabControl.DrawItem += new DrawItemEventHandler(this.MainTabControl_DrawItem);
            this.MainTabControl.MouseDown += new MouseEventHandler(this.MainTabControl_MouseDown);
            //设置底部栏目的基础信息
            Inf_username_label.Caption = "姓名 : " + User.UserName;
            Inf_linecode_label.Caption = "线别 : " + User.UserLineCode;
            Inf_source_label.Caption = "岗位资源 : " + User.UserSourceCode;
            Inf_db_label.Caption = "数据库 : " + SystemInf.CurrentDB;
            Inf_currentstep_label.Caption = "当前工序 : " + User.CurrentStepName;
            //设置获取当前屏幕大小自动全屏但是保留任务栏
            Rectangle ScreenArea = Screen.GetWorkingArea(this);
            Top = 0;
            Left = 0;
            Width = ScreenArea.Width;
            Height = ScreenArea.Height;
            SetForm();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = "Visual Studio 2013 Blue";
        }

        //关闭打印进程
        private static void Closelblprocess()
        {
            try
            {
                //杀死全部未关闭的打印进程
                string[] lines = System.IO.File.ReadAllLines(SystemInf.CacheFolder + "lblprocess.txt");
                foreach (string line in lines)
                {
                    if (line != "")
                    {
                        string processid = line.Split('|')[0];
                        string lblid = line.Split('|')[1];
                        try
                        {
                            if (System.Diagnostics.Process.GetProcessById(int.Parse(processid)).ProcessName != System.Diagnostics.Process.GetCurrentProcess().ProcessName)
                                System.Diagnostics.Process.GetProcessById(int.Parse(lblid)).Kill();
                        }
                        catch (Exception)
                        {
                            try
                            {
                                System.Diagnostics.Process.GetProcessById(int.Parse(lblid)).Kill();
                            }
                            catch (Exception)
                            {
                            }
                            FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Open, FileAccess.Read);
                            StreamReader sr = new StreamReader(fs);
                            String s = sr.ReadToEnd();
                            sr.Close();
                            fs.Close();
                            FileStream fas = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Create, FileAccess.ReadWrite);
                            StreamWriter sw = new StreamWriter(fas);
                            sw.Write(s.Replace(line + "\r\n", ""));
                            sw.Flush();
                            sw.Close();
                            fas.Close();
                        }
                    }
                }
            }
            catch
            {
                FileStream fas = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fas);
                sw.Write("");
                sw.Flush();
                sw.Close();
                fas.Close();
            }

        }

        /// <summary>
        ///设置窗体的最大化和最小化状态
        /// </summary>
        public void SetForm()
        {
            int WS_SYSMENU = 0x00080000; // 系统菜单
            int WS_MINIMIZEBOX = 0x20000; // 最大最小化按钮
            int windowLong = (GetWindowLong(new HandleRef(this, this.Handle), -16));
            SetWindowLong(new HandleRef(this, this.Handle), -16, windowLong | WS_SYSMENU | WS_MINIMIZEBOX);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_MINIMIZEBOX = 0x00020000;  // Winuser.h中定义   
                CreateParams cp = base.CreateParams;
                cp.Style = cp.Style | WS_MINIMIZEBOX;   // 允许最小化操作   
                return cp;
            }
        }

        /// <summary>
        /// 重载创建文件句柄
        /// </summary>
        protected override void CreateHandle()
        {
            if (!IsHandleCreated)
            {
                try { base.CreateHandle(); }
                catch { }
                finally
                {
                    if (!IsHandleCreated)
                        base.RecreateHandle();
                }
            }
        }

        Bitmap image = Resources.close_16px_558195_easyicon_net;
        //鼠标点下的时候监听
        private void headBar_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            GlobalEventsHandler.keycode = keyData;
            return false;
        }

        private void MainTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Brush HeadTextColor = new SolidBrush(Color.Green);
                Rectangle myTabRect = this.MainTabControl.GetTabRect(e.Index);
                //先添加TabPage属性 
                if (e.State == DrawItemState.Selected)
                    e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, 134), HeadTextColor, myTabRect.X + 2, myTabRect.Y + 2);
                else
                    e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, 134), SystemBrushes.ControlText, myTabRect.X + 2, myTabRect.Y + 2);

                //再画一个矩形框
                using (Pen p = new Pen(SystemBrushes.Control))
                {
                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(p, myTabRect);
                }

                //画关闭符号
                using (Pen objpen = new Pen(Color.Black))
                {
                    //使用图片
                    Bitmap bt = new Bitmap(image);
                    Point p5 = new Point(myTabRect.X, 8);
                    e.Graphics.DrawImage(bt, p5);
                }
                e.Graphics.Dispose();
            }
            catch (Exception) { }
        }

        //关闭按钮功能
        private void MainTabControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = e.X, y = e.Y;
                //计算关闭区域   
                Rectangle myTabRect = this.MainTabControl.GetTabRect(this.MainTabControl.SelectedIndex);
                myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                myTabRect.Width = CLOSE_SIZE;
                myTabRect.Height = CLOSE_SIZE;
                //如果鼠标在区域内就关闭选项卡   
                bool isClose = x > myTabRect.X && x < myTabRect.Right && y > myTabRect.Y && y < myTabRect.Bottom;
                if (isClose == true)
                {
                    DataTable dt;
                    string RemindInf = "";
                    string PaOutBoxCode = "";
                    string ObCheckno = "";
                    switch (MainTabControl.SelectedTab.Controls[0].Tag.ToString())
                    {
                        case "Packing!PackageCollectionWeigh":
                            Packing.Packing_PackageCollectionWeigh PackWeigh = (Packing.Packing_PackageCollectionWeigh)MainTabControl.SelectedTab.Controls[0];
                            if (PackWeigh.ob_checkno.Text != "")
                            {
                                ObCheckno = PackWeigh.ob_checkno.Text;
                            }
                            if (PackWeigh.pa_outboxcode.Text != "")
                            {
                                PaOutBoxCode = PackWeigh.pa_outboxcode.Text;
                            }
                            break;
                        case "Packing!PackageCollection":
                            Packing.Packing_PackageCollection Pack = (Packing.Packing_PackageCollection)MainTabControl.SelectedTab.Controls[0];
                            if (Pack.ob_checkno.Text != "")
                            {
                                ObCheckno = Pack.ob_checkno.Text;
                            }
                            if (Pack.pa_outboxcode.Text != "")
                            {
                                PaOutBoxCode = Pack.pa_outboxcode.Text;
                            }
                            break;
                        case "Make!ColorBoxWeigh":
                            Make.Make_ColorBoxWeigh ColorWeigh = (Make.Make_ColorBoxWeigh)MainTabControl.SelectedTab.Controls[0];
                            if (ColorWeigh.ob_checkno.Text != "")
                            {
                                ObCheckno = ColorWeigh.ob_checkno.Text;
                            }
                            break;
                        case "Packing!CartonBoxWeigh":
                            Packing.Packing_CartonBoxWeigh CartonWeigh = (Packing.Packing_CartonBoxWeigh)MainTabControl.SelectedTab.Controls[0];
                            if (CartonWeigh.ob_checkno.Text != "")
                            {
                                ObCheckno = CartonWeigh.ob_checkno.Text;
                            }
                            break;
                        default:
                            break;
                    }
                    if (ObCheckno != "")
                    {
                        dt = (DataTable)dh.ExecuteSql("select ob_status from oqcbatch where ob_checkno='" + ObCheckno + "'", "select");
                        if (dt.Rows.Count > 0)
                            if (dt.Rows[0][0].ToString() == "ENTERING")
                                RemindInf = "当前批次未送检,是否关闭页面?";
                    }
                    if (PaOutBoxCode != "")
                    {
                        dt = (DataTable)dh.ExecuteSql("select pa_status from package where pa_outboxcode='" + PaOutBoxCode + "'", "select");
                        if (dt.Rows.Count > 0)
                            if (dt.Rows[0][0].ToString() != "1")
                                RemindInf = "当前箱号未封箱,是否关闭页面?";
                    }
                    if (RemindInf != "")
                    {
                        string closetab_confirm = MessageBox.Show(this.ParentForm, RemindInf, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                        if (closetab_confirm != "Yes")
                        {
                            return;
                        }
                    }
                    this.MainTabControl.TabPages.Remove(this.MainTabControl.SelectedTab);
                }
            }
        }

        private void MainTabControl_ControlRemoved(object sender, ControlEventArgs e)
        {
            //移除已打开的Form中的Form
            TabPage tb = e.Control as TabPage;
            NavagationBar.OpenedFormName.Remove(tb.Tag.ToString());
            (tb.Controls[0] as Form).Close();
            //掉用了串口的程序需要在这个步骤关闭串口
            try
            {
                if (SerialPort1.Contains(tb.Controls[0].Tag.ToString()))
                {
                    //在这里调用Form的Close方法来触发TabPage下的Form的FormClosing事件
                    (tb.Controls[0] as Form).Close();
                }
            }
            catch (Exception) { }
        }

        private void LoginOut_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string logout_confirm = MessageBox.Show(this.ParentForm, "退出登录?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
            if (logout_confirm == "Yes")
            {
                //注销的时候切换回默认数据库
                SystemInf.ConnectionString = Properties.Settings.Default.Properties["MES"].DefaultValue.ToString();
                DataHelper.DBConnectionString = SystemInf.ConnectionString;
                //清除上个用户的权限信息
                SystemInf.Caller.Clear();
                //清除已经打开过的窗口的信息
                NavagationBar.OpenedFormName.Clear();
                //注销的时候将除了登陆窗口之外的全部窗口关闭
                for (int i = 0; i < System.Windows.Forms.Application.OpenForms.Count; i++)
                {
                    if (System.Windows.Forms.Application.OpenForms[i].Name != "Login")
                        System.Windows.Forms.Application.OpenForms[i].Close();
                }
                this.Hide();
                Login login = new Login();
                login.ShowDialog();
                this.Close();
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //杀死全部未关闭的打印进程
                string[] lines = System.IO.File.ReadAllLines(SystemInf.CacheFolder + "lblprocess.txt");
                foreach (string line in lines)
                {
                    if (line != "")
                    {
                        string processid = line.Split('|')[0];
                        string lblid = line.Split('|')[1];
                        try
                        {
                            if (System.Diagnostics.Process.GetProcessById(int.Parse(processid)).Id == System.Diagnostics.Process.GetCurrentProcess().Id)
                            {
                                System.Diagnostics.Process.GetProcessById(int.Parse(lblid)).Kill();
                                FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Open, FileAccess.Read);
                                StreamReader sr = new StreamReader(fs);
                                String s = sr.ReadToEnd();
                                sr.Close();
                                fs.Close();
                                FileStream fas = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Create, FileAccess.ReadWrite);
                                StreamWriter sw = new StreamWriter(fas);
                                sw.Write(s.Replace(line + "\r\n", ""));
                                sw.Flush();
                                sw.Close();
                                fas.Close();
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            catch
            {
                FileStream fas = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fas);
                sw.Write("");
                sw.Flush();
                sw.Close();
                fas.Close();
            }
            BaseUtil.FormStepInOrOut(this, false);
        }

        private void MainTabControl_Selected(object sender, TabControlEventArgs e)
        {
            try
            {
                for (int i = 0; i < e.TabPage.Controls.Count; i++)
                {
                    if (e.TabPage.Controls[i] is Form)
                    {
                        if (e.TabPage.Controls[i].Name == "Make_Repair")
                        {
                            Make.Make_Repair repair = e.TabPage.Controls[i] as Make.Make_Repair;
                            if (repair.Controls["GetSNCode"].Text != "")
                            {
                                repair.RefreshData();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void NavBar_SizeChanged(object sender, EventArgs e)
        {
            MainTabControl.Location = new Point(NavBar.Width + 5, MainTabControl.Location.Y);
            MainTabControl.Width = Width - NavBar.Width;
            MainTabControl.Height = Height - headBar1.Height - 27;
        }
    }
}