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 AutoAnalysisXLSJC : 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 = new ftpOperater();
        string imaster;

        public AutoAnalysisXLSJC()
        {
            tipform = new Tip();
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }

        public AutoAnalysisXLSJC(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>();

            //获取缓存信息
            try
            {
                FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString();
                BackUpFolderPath.Text = BaseUtil.GetCacheData("BackUpFolderPath").ToString();
                Master.Text = BaseUtil.GetCacheData("Master").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 = false;
            //}
        }

        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;
                }
            }
            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("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 = new string[] { "xls" };
            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);
                {
                    try
                    {
                        string ftppath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                        int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class,STD_RESCODE,std_stepcode,STD_TESTRESULT,std_class)select STEPTESTDETAIL_seq.nextval,'" + SN + "','',sysdate,'" + SN + "','" + isource + "','" + Device.Text + "','','http://172.16.51.3:8099/ftp" + ftppath + SN + ".xls" +"' from dual", "insert").ToString());
                        if (num > 0)
                        {
                         
                            ftp.UpLoadFile(folderpath, SN, ftppath, "");
                            OperateResult.AppendText("序列号:" + SN + "上传成功\n");
                            string Backupfilename = BackUpFolderPath.Text + @"\" + SN;
                            if (!Directory.Exists(BackUpFolderPath.Text))
                            {
                                Directory.CreateDirectory(BackUpFolderPath.Text);
                            }
                            if (!deleteFile.Checked)
                            {
                                if (File.Exists(Backupfilename))
                                {
                                    File.Delete(Backupfilename);
                                }
                                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;
            }
        }

        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.EndsWith(".xls") || s.EndsWith(".ini"));
                //foreach (var Xml in AllXmls)
                //{
                //    File.Delete(Xml.ToString());
                //}
            }
        }

        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)
            {
                //WindowState = FormWindowState.Normal;
                //ShowInTaskbar = true;
            }
        }

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

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