using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace FileWatcher
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FileWatcher.Path = @"D:\";
            FileWatcher.Filter = "*.*";
            FileWatcher.EnableRaisingEvents = true;
            FileWatcher.Created += new FileSystemEventHandler(Watcher_Created);

            string path = Application.ExecutablePath;
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            rk2.SetValue("FileWatcher.exe", path);
            rk2.Close();
            rk.Close();
            timer1.Interval = 1000 * 10;
            timer1.Start();

            timer2.Interval = 1000 * 60 * 60;
            timer2.Start();

        }

        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            if (e.FullPath.Substring(e.FullPath.LastIndexOf(".") + 1) == "jdf" || e.FullPath.Substring(e.FullPath.LastIndexOf(".") + 1) == "njdf")
            {
                if (!e.FullPath.Contains("RECYCLE"))
                {
                    string FullName = e.FullPath;
                    string Filename = FullName.Substring(FullName.LastIndexOf(@"\") + 1).Split('.')[0];
                    string StartPath = FullName.Substring(0, FullName.LastIndexOf(@"\") + 1);
                    Thread.Sleep(1500);
                    if (File.Exists(FullName))
                    {
                        richTextBox1.AppendText(DateTime.Now.ToString("yyyy/MM/dd h:mm:ss.fff") + " " + e.FullPath + "\n");
                        DoLog(FullName);
                    }
                    else
                    {
                        richTextBox1.AppendText("不存在文件" + FullName + "\n");
                    }
                    //不存在同名的文件则进行转换,或者Excel文件小于100KB的
                    if ((!File.Exists(StartPath + Filename + ".xls") && File.Exists(FullName)))
                    {
                        if (FullName.Substring(FullName.LastIndexOf(".") + 1) == "jdf")
                        {
                            exec(@"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe", @"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe " + FullName);
                        }
                        else if (FullName.Substring(FullName.LastIndexOf(".") + 1) == "njdf")
                        {
                            exec(@"D:\FileWatcher\NJDF\DTS-Data2Excel.exe", @"D:\FileWatcher\NJDF\DTS-Data2Excel.exe " + FullName);
                        }
                    }
                    else
                    {
                        richTextBox1.AppendText(DateTime.Now.ToString("yyyy/MM/dd h:mm:ss.fff") + " 已存在Excel文件 " + e.FullPath + "\n");
                    }
                }
            }
        }

        public void exec(string exePath, string parameters)
        {
            Process process = new Process();
            process.StartInfo.FileName = exePath;
            process.StartInfo.Arguments = parameters;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
        }

        private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {

        }

        public void DoLog(string Message)
        {
            try
            {
                StreamWriter sw = File.AppendText(DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
                sw.WriteLine("\n【时间】" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Message + "\n");
                sw.Close();
            }
            catch (Exception) { }
        }

        /// <summary>
        /// 私有变量
        /// </summary>
        private List<FileInfo> lst = new List<FileInfo>();
        /// <summary>
        /// 获得目录下所有文件或指定文件类型文件(包含所有子文件夹)
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="extName">扩展名可以多个 例如 .mp3.wma.rm</param>
        /// <returns>List<FileInfo></returns>
        public List<FileInfo> getFile(string path, string extName)
        {
            getdir(path, extName);
            return lst;
        }
        /// <summary>
        /// 私有方法,递归获取指定类型文件,包含子文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extName"></param>
        private void getdir(string path, string extName)
        {
            try
            {
                string[] dir = Directory.GetDirectories(path); //文件夹列表   
                DirectoryInfo fdir = new DirectoryInfo(path);
                FileInfo[] file = fdir.GetFiles();
                //FileInfo[] file = Directory.GetFiles(path); //文件列表   
                if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空                   
                {
                    foreach (FileInfo f in file) //显示当前目录所有文件   
                    {
                        if (f.Attributes.ToString().IndexOf("Hidden") > -1 && f.Attributes.ToString().IndexOf("System") > -1)
                        {

                        }
                        else
                        {
                            if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
                            {
                                lst.Add(f);
                            }
                        }
                    }
                    foreach (string d in dir)
                    {
                        if (d.Contains("PROB"))
                            getdir(d, extName);//递归   
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                Process[] processes1 = Process.GetProcessesByName("DTS-JDFData2Excel");
                for (int i = 0; i < processes1.Length; i++)
                {
                    //杀掉超过20秒没关闭的进程
                    if (DateTime.Now > processes1[1].StartTime.AddSeconds(60))
                    {
                        processes1[i].Kill();
                    }
                }

                Process[] processes2 = Process.GetProcessesByName("DTS-Data2Excel");
                for (int i = 0; i < processes2.Length; i++)
                {
                    if (DateTime.Now > processes2[1].StartTime.AddSeconds(60))
                    {
                        processes2[i].Kill();
                    }
                }
            }
            catch (Exception)
            {

            }
            //每天0点清空文本框的内容
            if (DateTime.Now.ToString("HH:mm") == "00:00")
            {
                richTextBox1.Clear();
            }
        }

        private void RunTran()
        {
            try
            {
                List<FileInfo> lst = new List<FileInfo>();
                string[] path = new string[] { @"D:\PROB-071",@"D:\PROB-072",@"D:\PROB-073",@"D:\PROB-074",
                @"D:\PROB-075",@"D:\PROB-76",@"D:\PROB-077",@"D:\PROB-078",@"D:\PROB-079",@"D:\PROB-080",@"D:\PROB-081",@"D:\PROB-082",@"D:\PROB-001", @"D:\PROB-002", @"D:\PROB-003", @"D:\PROB-004",
                    @"D:\PROB-005", @"D:\PROB-006", @"D:\PROB-007", @"D:\PROB-008", @"D:\PROB-009",
                    @"D:\PROB-010", @"D:\PROB-011", @"D:\PROB-012", @"D:\PROB-013", @"D:\PROB-014",
                    @"D:\PROB-015", @"D:\PROB-004", @"D:\PROB-016", @"D:\PROB-017", @"D:\PROB-018",
                    @"D:\PROB-019", @"D:\PROB-020", @"D:\PROB-021", @"D:\PROB-022", @"D:\PROB-023",
                    @"D:\PROB-024", @"D:\PROB-026",@"D:\PROB-027",@"D:\PROB-028",@"D:\PROB-029",
                    @"D:\PROB-030",@"D:\PROB-031",@"D:\PROB-032",@"D:\PROB-033",@"D:\PROB-034",
                    @"D:\PROB-035",@"D:\PROB-036",@"D:\PROB-037",@"D:\PROB-038",@"D:\PROB-039",
                @"D:\PROB-040",@"D:\PROB-041",@"D:\PROB-042",@"D:\PROB-043",@"D:\PROB-045",@"D:\PROB-046",
                @"D:\PROB-047",@"D:\PROB-048",@"D:\PROB-049",@"D:\PROB-050",@"D:\PROB-051",@"D:\PROB-052",@"D:\PROB-053",
                @"D:\PROB-054",@"D:\PROB-055",@"D:\PROB-056",@"D:\PROB-057",@"D:\PROB-058",@"D:\PROB-059",@"D:\PROB-060",
                @"D:\PROB-061",@"D:\PROB-062",@"D:\PROB-063",@"D:\PROB-064",@"D:\PROB-65",@"D:\PROB-66",@"D:\PROB-067",
                @"D:\PROB-068",@"D:\PROB-069",@"D:\PROB-070"};
                for (int i = 0; i < path.Length; i++)
                {
                    richTextBox1.AppendText(path[i] + "\n");
                    List<FileInfo> lstFiles = getFile(path[i], ".jdf", lst);
                    foreach (FileInfo shpFile in lstFiles)
                    {
                        string Filename = shpFile.FullName.Substring(shpFile.FullName.LastIndexOf(@"\") + 1).Split('.')[0];
                        string StartPath = shpFile.FullName.Substring(0, shpFile.FullName.LastIndexOf(@"\") + 1);
                        //不存在同名的文件则进行转换
                        if (!File.Exists(StartPath + Filename + ".xls"))
                        {
                            Thread.Sleep(1500);
                            exec(@"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe", @"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe " + shpFile.FullName);
                            richTextBox1.AppendText(shpFile.FullName + "\n");
                        }
                    }
                    lst.Clear();
                    List<FileInfo> lstFiles1 = getFile(path[i], ".njdf", lst);
                    foreach (FileInfo shpFile in lstFiles1)
                    {
                        string Filename = shpFile.FullName.Substring(shpFile.FullName.LastIndexOf(@"\") + 1).Split('.')[0];
                        string StartPath = shpFile.FullName.Substring(0, shpFile.FullName.LastIndexOf(@"\") + 1);
                        //不存在同名的文件则进行转换
                        if (!File.Exists(StartPath + Filename + ".xls"))
                        {
                            Thread.Sleep(1500);
                            exec(@"D:\FileWatcher\NJDF\DTS-Data2Excel.exe", @"D:\FileWatcher\NJDF\DTS-Data2Excel.exe " + shpFile.FullName);
                            richTextBox1.AppendText(shpFile.FullName + "\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message + ex.StackTrace + "\n");
            }
        }

        private void RunTran1()
        {
            try
            {
                List<FileInfo> lst = new List<FileInfo>();
                string[] path = textBox1.Text.Split(',');
                for (int i = 0; i < path.Length; i++)
                {
                    richTextBox1.AppendText(path[i] + "\n");
                    List<FileInfo> lstFiles = getFile(path[i], ".jdf", lst);
                    foreach (FileInfo shpFile in lstFiles)
                    {
                        string Filename = shpFile.FullName.Substring(shpFile.FullName.LastIndexOf(@"\") + 1).Split('.')[0];
                        string StartPath = shpFile.FullName.Substring(0, shpFile.FullName.LastIndexOf(@"\") + 1);
                        //不存在同名的文件则进行转换
                        try
                        {
                            if (!File.Exists(StartPath + Filename + ".xls") ||
                                ((new FileInfo(shpFile.FullName).Length / 1024 > 50) && (File.Exists(StartPath + Filename + ".xls") && (new FileInfo(StartPath + Filename + ".xls").Length / 1024) < 100)))
                            {
                                Thread.Sleep(1500);
                                exec(@"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe", @"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe " + shpFile.FullName);
                                richTextBox1.AppendText(shpFile.FullName + "\n");
                            }
                        }
                        catch (Exception ex)
                        {
                            richTextBox1.AppendText(ex.Message + ex.StackTrace + "\n");
                        }
                    }
                    lst.Clear();
                    List<FileInfo> lstFiles1 = getFile(path[i], ".njdf", lst);
                    foreach (FileInfo shpFile in lstFiles1)
                    {
                        string Filename = shpFile.FullName.Substring(shpFile.FullName.LastIndexOf(@"\") + 1).Split('.')[0];
                        string StartPath = shpFile.FullName.Substring(0, shpFile.FullName.LastIndexOf(@"\") + 1);
                        //不存在同名的文件则进行转换
                        try
                        {
                            Thread.Sleep(1500);
                            exec(@"D:\FileWatcher\NJDF\DTS-Data2Excel.exe", @"D:\FileWatcher\NJDF\DTS-Data2Excel.exe " + shpFile.FullName);
                            richTextBox1.AppendText(shpFile.FullName + "\n");
                        }
                        catch (Exception ex)
                        {
                            richTextBox1.AppendText(ex.Message + ex.StackTrace + "\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message + ex.StackTrace + "\n");
            }
        }

        /// <summary>
        /// 获得目录下所有文件或指定文件类型文件(包含所有子文件夹)
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="extName">扩展名可以多个 例如 .mp3.wma.rm</param>
        /// <returns>List<FileInfo></returns>
        public static List<FileInfo> getFile(string path, string extName, List<FileInfo> lst)
        {
            try
            {
                string[] dir = Directory.GetDirectories(path); //文件夹列表  
                DirectoryInfo fdir = new DirectoryInfo(path);
                FileInfo[] file = fdir.GetFiles();
                //FileInfo[] file = Directory.GetFiles(path); //文件列表  
                if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空          
                {
                    foreach (FileInfo f in file) //显示当前目录所有文件  
                    {
                        if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
                        {
                            lst.Add(f);
                        }
                    }
                    foreach (string d in dir)
                    {
                        getFile(d, extName, lst);//递归  
                    }
                }
                return lst;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            RunTran();
        }

        private void RunTran2()
        {
            DataHelper dh = new DataHelper();
            StringBuilder sql = new StringBuilder();
            sql.Clear();
            sql.Append("select chipcode_,replace(replace(replace(substr(JDFPATH_,instr(JDFPATH_,'$')-1),'$',':'),'/','\\'),'\\\\','\\') jdf ");
            sql.Append(" from datacenter$chip where  chipcode_ in (select A_meschip.CHIPCODE from A_meschip) and datacenter$chip.JDFPATH_ is not null");
            DataTable dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string FullName = dt.Rows[i]["jdf"].ToString();
                if (FullName.Substring(FullName.LastIndexOf(".") + 1) == "jdf")
                {
                    exec(@"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe", @"D:\FileWatcher\JDF\DTS-JDFData2Excel.exe " + FullName);
                }
                else if (FullName.Substring(FullName.LastIndexOf(".") + 1) == "njdf")
                {
                    exec(@"D:\FileWatcher\NJDF\DTS-Data2Excel.exe", @"D:\FileWatcher\NJDF\DTS-Data2Excel.exe " + FullName);
                }
                richTextBox1.AppendText(FullName + "\n");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread tr = new Thread(RunTran1);
            tr.Start();
        }
    }
}