using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.Media;
using System.Linq;
using NPOI.SS.Formula.Functions;
using System.Windows.Media.TextFormatting;
using UMESDLLService;

namespace FileWatcher
{
    public partial class AutoAnalysisXmlByStep : Form
    {

        public static DataHelper dh;

        DataTable dt;

        DataTable DB;

        /// <summary>
        /// 用户编号
        /// </summary>
        string iusercode;
        /// <summary>
        /// 岗位资源
        /// </summary>
        string isource;

        Tip tipform;

        Thread InitDB;
        /// <summary>
        /// 线别
        /// </summary> 
        string ilinecode;
        /// <summary>
        /// 不良代码组
        /// </summary>
        string ibadgroup;
        /// <summary>
        /// 当前工序
        /// </summary>
        string istepcode;
        StringBuilder sql = new StringBuilder();
        /// <summary>
        /// 缓存的文件
        /// </summary>
        public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
        /// <summary>
        /// 缓存的文件夹
        /// </summary>
        public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
        /// <summary>
        /// 需要解析的文件名
        /// </summary>
        List<string> _FileName = new List<string>();

        ftpOperater ftp;
        string imaster;

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                const int WS_EX_APPWINDOW = 0x40000;
                const int WS_EX_TOOLWINDOW = 0x80;
                cp.ExStyle &= (~WS_EX_APPWINDOW);
                cp.ExStyle |= WS_EX_TOOLWINDOW;
                return cp;
            }
        }

        public AutoAnalysisXmlByStep()
        {
            tipform = new Tip();

            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }

        public AutoAnalysisXmlByStep(string iUserName, string iSource, string iMaster)
        {
            tipform = new Tip();
            InitializeComponent();
            iusercode = iUserName;
            isource = iSource.ToUpper();
            imaster = iMaster;
            StartPosition = FormStartPosition.CenterScreen;
        }
        string fieltype = "";
        string ftpulr = "";
        private void Form1_Load(object sender, EventArgs e)
        {
            tipform.Show();
            CheckForIllegalCrossThreadCalls = false;
            FormBorderStyle = FormBorderStyle.FixedSingle;
            InitDB = new Thread(ConnectDB);
            //添加监控事件
            //XmlWatcher.Created += new FileSystemEventHandler(XmlWatcher_Created);
            SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
            stw.StartPosition = FormStartPosition.CenterScreen;
            stw.ShowDialog();
            List<string> CacheInf = new List<string>();
            StreamReader sR = new StreamReader(Application.StartupPath + @"\MES_SETTING.txt", Encoding.Default);
            while ((nextLine = sR.ReadLine()) != null)
            {
                string name = nextLine.ToString().Split('=')[0];
                string value = nextLine.ToString().Split('=')[1];
                if (name == "FTPURL")
                {
                    ftpulr = value;
                }
                if (name == "FileType")
                {
                    fieltype = value;
                }
            }


            string[] FTPInf = ftpulr.Split('#');
            ftp = new ftpOperater(FTPInf[0], FTPInf[1], FTPInf[2]);
            //获取缓存信息
            try
            {
                FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString();
                BackUpFolderPath.Text = BaseUtil.GetCacheData("BackUpFolderPath").ToString();
                Master.Text = BaseUtil.GetCacheData("Master").ToString();
                li_code.Text = BaseUtil.GetCacheData("Line").ToString();
                MachineType.Text = BaseUtil.GetCacheData("MachineType").ToString();
                Device.Text = BaseUtil.GetCacheData("Device").ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            StartWatch.PerformClick();
            bool hide = true;
            if (hide)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = true;
            }
        }

        private void ConnectDB()
        {
            dh = new DataHelper();
        }

        private void StartWatch_Click(object sender, EventArgs e)
        {
            if (FolderPath.Text == "")
            {
                OperateResult.AppendText("请选择监控文件夹\n");
                return;
            }
            else
            {
                if (!Directory.Exists(FolderPath.Text))
                {
                    OperateResult.AppendText("监控文件夹不存在\n");
                    return;
                }
            }
            if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'"))
            {
                OperateResult.AppendText("线别不存在\n");
                return;
            }
            XmlWatcher.Path = FolderPath.Text;
            XmlWatcher.Filter = "*.*";
            XmlWatcher.EnableRaisingEvents = true;
            //设置缓存数据
            BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
            BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
            BaseUtil.SetCacheData("Master", Master.Text);
            BaseUtil.SetCacheData("Line", li_code.Text);
            BaseUtil.SetCacheData("MachineType", MachineType.Text);
            BaseUtil.SetCacheData("Device", Device.Text);
            //BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);

            Timer.Interval = 1000 * int.Parse(TimerInter.Text.ToString());
            Timer.Start();
            //设置按钮不可点击
            StartWatch.Enabled = false;
            ChooseFolder.Enabled = false;
            Master.Enabled = false;
            StopWatch.Enabled = true;
            OperateResult.AppendText("开始执行监控\n");
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
        }

        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

        private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
        {
            string[] str = fieltype.Split('#');
            for (int i = 0; i < str.Length; i++)
            {
                if (e.FullPath.ToUpper().EndsWith(str[i].ToUpper()))
                {
                    TxtHandleProcess(e.FullPath);
                }
            }
        }
        string nextLine;
        private void TxtHandleProcess(string FileName)
        {
            List<string> badcode = new List<string>();
            List<string> badlocation = new List<string>();
            List<string> badprod = new List<string>();
            try
            {
                string filename = FileName;
                string folderpath = FileName.Substring(0, FileName.LastIndexOf(@"\"));
                string SN = FileName.Substring(FileName.LastIndexOf(@"\") + 1);
                string filetype = FileName.Substring(FileName.LastIndexOf(".") + 1);
                {
                    Console.WriteLine(FileName);
                    try
                    {
                        string sn1 = SN.Split('.')[0];
                        //string makecode = dh.getFieldDataByCondition("makeserial", "ms_makecode", "ms_sncode='" + sn1 + "'").ToString();
                        //MachineType.Text = makecode;
                        string ftppath = "/" + MachineType.Text + "/";
                        //string ErrMessage = ftp.UpLoadFile(folderpath, SN, ftppath, "");
                        DirectoryInfo info = new DirectoryInfo(folderpath);
                        MachineType.Text = info.Name;//获取当前路径最后一级文件夹名称
                        if (Device.Text == "炉后AOI")
                        {
                            StreamReader sR = new StreamReader(FileName, Encoding.Default);
                            string ASN = "";
                            string Model = "";
                            string Shift = "";
                            string Rep_Date_Time = "";
                            string OPID = "";
                            string StationName = "";
                            string Surface = "";
                            string CycleTime = "";
                            string Result = "";
                            int Rowindex = 0;
                            List<string> Location = new List<string>();
                            List<string> PinNum = new List<string>();
                            List<string> ErrCode = new List<string>();
                            List<string> RepairStatus = new List<string>();
                            while ((nextLine = sR.ReadLine()) != null)
                            {
                                string data = nextLine.ToString().Split('=')[1];
                                string itemname = nextLine.ToString().Split('=')[0];
                                switch (Rowindex)
                                {
                                    case 0:
                                        ASN = data;
                                        break;
                                    case 1:
                                        Model = data;
                                        break;
                                    case 2:
                                        Shift = data;
                                        break;
                                    case 3:
                                        Rep_Date_Time = data;
                                        break;
                                    case 4:
                                        OPID = data;
                                        break;
                                    case 5:
                                        StationName = data;
                                        break;
                                    case 6:
                                        Surface = data;
                                        break;
                                    case 7:
                                        CycleTime = data;
                                        break;
                                    default:
                                        break;
                                }
                                if (itemname == "Result")
                                {
                                    Result = data;
                                    continue;
                                }
                                if (Rowindex >= 8)
                                {
                                    //Location
                                    if ((Rowindex - 8) % 4 == 0)
                                    {
                                        Location.Add(data);
                                    }
                                    //PinNum
                                    if ((Rowindex - 8) % 4 == 1)
                                    {
                                        PinNum.Add(data);
                                    }
                                    //ErrCode
                                    if ((Rowindex - 8) % 4 == 2)
                                    {
                                        ErrCode.Add(data);
                                    }
                                    //RepairStatus
                                    if ((Rowindex - 8) % 4 == 3)
                                    {
                                        RepairStatus.Add(data);
                                    }
                                }

                                Rowindex = Rowindex + 1;
                            }
                            sR.Close();
                            Thread.Sleep(500);
                            int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class,STD_RESCODE,std_stepcode,std_linecode,std_machinetype, STD_TESTRESULT)select STEPTESTDETAIL_seq.nextval,'" + SN + "','',sysdate,'" + ftpulr.Split('#')[0] + imaster + "/" + ftppath + SN + "','" + isource + "','" + Device.Text + "','" + li_code.Text + "','" + MachineType.Text + "','" + Result + "' from dual", "insert").ToString());
                            if (Result.ToUpper() == "FAIL")
                            {
                                sql.Clear();
                                sql.Append("insert into makebad(mb_id,MB_MSCODE, MB_SNCODE, MB_INDATE, MB_STEPCODE, MB_SOURCECODE, MB_BADCODE, MB_YMD, MB_LINECODE,MB_BADNAME)");
                                sql.Append("values(makebad_seq.nextval,'" + ASN + "','" + ASN + "',sysdate,'AOI-B','',:MB_BADCODE,to_char(sysdate,'yyyymmdd'),'" + li_code.Text + "',:MB_BADNAME)");
                                dh.BatchInsert(sql.ToString(), new string[] { "mb_badcode", "mb_badname" }, ErrCode.ToArray(), Location.ToArray());
                            }
                            if (num > 0)
                            {
                                OperateResult.AppendText("序列号:" + SN + "上传成功\n");
                                string Backupfilename = BackUpFolderPath.Text + @"\" + MachineType.Text + @"\" + SN;
                                if (!Directory.Exists(BackUpFolderPath.Text + @"\" + MachineType.Text))
                                {
                                    Directory.CreateDirectory(BackUpFolderPath.Text + @"\" + MachineType.Text);
                                }
                                //if (File.Exists(Backupfilename))
                                //{
                                //    File.Delete(Backupfilename);
                                //}
                                if (!deleteFile.Checked)
                                {
                                    File.Move(FileName, Backupfilename);
                                }
                            }
                        }
                        else
                        {
                            int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class,STD_RESCODE,std_stepcode,std_linecode,std_machinetype)select STEPTESTDETAIL_seq.nextval,'" + SN + "','',sysdate,'" + ftpulr.Split('#')[0] + imaster + "/" + ftppath + SN + "','" + isource + "','" + Device.Text + "','" + li_code.Text + "','" + MachineType.Text + "' from dual", "insert").ToString());
                            if (num > 0)
                            {
                                OperateResult.AppendText("序列号:" + SN + "上传成功\n");
                                string Backupfilename = BackUpFolderPath.Text + @"\" + MachineType.Text + @"\" + SN;
                                if (!Directory.Exists(BackUpFolderPath.Text + @"\" + MachineType.Text))
                                {
                                    Directory.CreateDirectory(BackUpFolderPath.Text + @"\" + MachineType.Text);
                                }
                                File.Move(FileName, Backupfilename);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        OperateResult.AppendText(ex.Message + ex.StackTrace + "\n");
                    }
                }
            }
            catch (Exception e)
            {
                OperateResult.AppendText("解析失败:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n" + FileName + "\n" + e.Message + "\n");
            }
        }

        private void StopWatch_Click(object sender, EventArgs e)
        {
            XmlWatcher.EnableRaisingEvents = false;
            StartWatch.Enabled = true;
            Master.Enabled = true;
            ChooseFolder.Enabled = true;

            StopWatch.Enabled = false;
            OperateResult.AppendText("停止执行监控\n");
        }

        private void Clean_Click(object sender, EventArgs e)
        {
            OperateResult.Clear();
        }

        private void ChooseFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择监控文件夹";
            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK)
            {
                FolderPath.Text = folder.SelectedPath;
            }
        }

        private void ChooseBackUpFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择备份文件夹";
            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK)
            {
                BackUpFolderPath.Text = folder.SelectedPath;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string ExitConfirm = MessageBox.Show(this, "最小化托盘?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
            if (ExitConfirm == "Yes")
            {
                WindowState = FormWindowState.Minimized;
                e.Cancel = true;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void AutoStart_CheckedChanged(object sender, EventArgs e)
        {
            SetAutoRun();
        }

        private void SetAutoRun()
        {
            if (AutoStart.Checked) //设置开机自启动  
            {
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("UAS自动过站解析器.exe", path);
                rk2.Close();
                rk.Close();
            }
            else //取消开机自启动  
            {
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("UAS自动过站解析器.exe", false);
                rk2.Close();
                rk.Close();
            }
        }

        private void BatchAnalysus_Click(object sender, EventArgs e)
        {
            //var AllXmls = Directory.GetFiles(FolderPath.Text, "*.txt");
            //foreach (var Xml in AllXmls)
            //{
            //    TxtHandleProcess(Xml);
            //}
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (deleteFile.Checked)
            {
                var AllXmls = Directory.GetFiles(FolderPath.Text, "*.*", SearchOption.AllDirectories).Where(s => s.ToUpper().EndsWith(".TXT") || s.ToUpper().EndsWith(".INI"));
                foreach (var Xml in AllXmls)
                {
                    try
                    {
                        TxtHandleProcess(Xml.ToString());
                        File.Delete(Xml.ToString());
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        private void CleanFolderPath_Click(object sender, EventArgs e)
        {
            FolderPath.Text = "";
        }

        private void CleanBackUpFolderPath_Click(object sender, EventArgs e)
        {
            BackUpFolderPath.Text = "";
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (WindowState == FormWindowState.Minimized)
            {
                Thread.Sleep(1000);
                WindowState = FormWindowState.Normal;
                Thread.Sleep(1000);
                ShowInTaskbar = true;
            }
        }

        private void AutoAnalysisXmlByStep_Deactivate(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                ShowInTaskbar = false;
            }
        }
    }
}