using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Timers;
using System.Xml;
using DataPumpWindowsService;
using XmlDucumentAnalysis.model;
using System.Net;
using ICSharpCode.SharpZipLib.Tar;

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

        private System.Timers.Timer timer = new System.Timers.Timer();
        private string baseFilePath
        {
            get;
            set;
        }
        private string csvBaseFilePath
        {
            get;
            set;
        }
        private string xmlBasePath
        {
            get;
            set;
        }
        private string copyXmlFilePath
        {
            get;
            set;
        }
        private string ConnectString
        {
            get;
            set;
        }
        private DateTime minDateTime
        {
            get;
            set;
        }
        private DateTime maxDateTime
        {
            get;
            set;
        }
        private string copyStartTime
        {
            get;
            set;
        }

        private string copyEndTime
        {
            get;
            set;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Log.Info("点击复制该时间段的录音文件");
            Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "录音文件拷贝任务");
            RecordingCopyJob(this.minDateTime, this.maxDateTime);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Log.Info("点击生成csv文件");
            Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "的生成csv文件任务");
            CreateCsvFileJob(this.minDateTime, this.maxDateTime);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // 定时任务时间间隔为12小时
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["interval"]))
            {
                this.timer.Interval = (double)int.Parse(ConfigurationManager.AppSettings["interval"]);
            }
            // xml底层目录
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["xmlBasePath"]))
            {
                this.xmlBasePath = ConfigurationManager.AppSettings["xmlBasePath"];
            }
            // 复制xml底层目录
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["copyXmlFilePath"]))
            {
                this.copyXmlFilePath = ConfigurationManager.AppSettings["copyXmlFilePath"];
            }
            // 获取配置里的Oracle连接信息
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["default"]))
            {
                this.ConnectString = ConfigurationManager.AppSettings["default"];
            }
            // 获取配置里的Oracle连接信息
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["baseFilePath"]))
            {
                this.baseFilePath = ConfigurationManager.AppSettings["baseFilePath"];
            }
            // 获取csv存放路径
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["csvBaseFilePath"]))
            {
                this.csvBaseFilePath = ConfigurationManager.AppSettings["csvBaseFilePath"];
            }
        }

        // xml解析方法并设置XmlModel属性
        public static XmlModel XmlFileAnalysis(string filePath, XmlModel xmlModel)
        {
            Log.Info("开始分析" + filePath);
            //这一步实例化一个xml命名空间管理器
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
            nsMgr.AddNamespace("x", "http://www.verint.com/xmlns/recording20080320");

            // 获取节点内容
            XmlNode contacts = doc.SelectSingleNode("x:recording/x:contacts", nsMgr);
            XmlNode contact = contacts.FirstChild;
            if (contact != null)
            {
                XmlNode sessions = contact.SelectSingleNode("x:sessions", nsMgr);
                XmlNode session = sessions.FirstChild;
                XmlNode aniNode = session.SelectSingleNode("x:ani", nsMgr);
                if (aniNode == null)
                {
                    return xmlModel;
                }
                // 主叫号码
                string ani = aniNode.InnerText;
                // 被叫号码
                string dnis = session.SelectSingleNode("x:dnis", nsMgr).InnerText;
                // 通话时长
                string duration = session.SelectSingleNode("x:duration", nsMgr).InnerText;
                // 录音流水ID
                string parentinum = session.Attributes["x:parentinum"].Value;
                // 通话拨打时间
                string starttime = session.SelectSingleNode("x:starttime", nsMgr).InnerText;
                starttime = SplitDateTimeString(starttime);
                // 呼叫类型
                string direction = session.SelectSingleNode("x:direction", nsMgr).InnerText;
                // 录音流水ID
                string switch_call_id = session.SelectSingleNode("x:switch_call_id", nsMgr).InnerText;

                if ("Inbound".Equals(direction))
                {
                    direction = "0";
                }
                else
                {
                    direction = "1";
                }
                // 平台code
                string switch_id = session.SelectSingleNode("x:switch_id", nsMgr).InnerText;
                // 坐席ID
                XmlNode sessionTags = session.SelectSingleNode("x:tags", nsMgr);
                XmlNode sessionTag = sessionTags.FirstChild;
                string agentid = "";
                foreach (XmlNode xn1 in sessionTag)
                {
                    XmlElement xe1 = (XmlElement)xn1;
                    if (xe1.GetAttribute("x:key").ToString() == "agentid")
                    {
                        agentid = xn1.InnerText;
                        break;
                    }
                }
                xmlModel.callerNumber = ani;
                xmlModel.destinationNumber = dnis;
                xmlModel.duration = duration;
                xmlModel.dateStartCall = starttime;
                xmlModel.callType = direction;
                xmlModel.platformCode = switch_id;
                xmlModel.agentId = agentid;
                xmlModel.switch_call_id = switch_call_id;
            }
            // 通话结束时间
            XmlNode tags = doc.SelectSingleNode("x:recording/x:segment/x:tags", nsMgr);
            XmlNodeList tagList = tags.ChildNodes;
            foreach (XmlNode xn in tagList)
            {
                XmlNode xn2 = xn.FirstChild;
                string childAttributesValue = xn2.Attributes["x:key"].Value;
                if ("endtime".Equals(childAttributesValue))
                {
                    string endtime = xn2.InnerText;
                    endtime = SplitDateTimeString(endtime);
                    xmlModel.dateHangup = endtime;
                    break;
                }
            }
            return xmlModel;
        }
        // 截取时间段
        public static string SplitDateTimeString(string dateTimeString)
        {
            dateTimeString = dateTimeString.Substring(0, 19);
            dateTimeString = dateTimeString.Replace("T", " ");
            return dateTimeString;
        }
        // 获取文件MD5值方法
        public static string getMD5ByMD5CryptoService(string path)
        {
            if (!File.Exists(path)) return "";
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
            byte[] buffer = md5Provider.ComputeHash(fs);
            string resule = BitConverter.ToString(buffer);
            md5Provider.Clear();
            fs.Close();
            return resule;
        }
        // 生成csv文件公共方法
        private void CreateCsvFile(string filePath, List<string> lineList)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();  //文件不存在，创建文件
            }

            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, Encoding.Default);
            // 循环列数组  写入表数据
            foreach (string line in lineList)
            {
                sw.WriteLine(line);
            }
            sw.Close();
            fs.Close();
        }
        // 生成csv文件定时任务
        private void CreateCsvFileJob(DateTime minTime, DateTime maxTime)
        {
            Log.Debug("开始生成csv文件任务");
            // 定义表数组    
            List<string> lineList = new List<string>();
            // 定义表头
            lineList.Add("录音流水ID,录音文件名,数据包,通话时长(单位:秒),通话拨打时间,通话挂机时间,主叫号码,被叫号码,坐席工号,坐席ID,质检场景,呼叫类型(0：呼入，1：呼出),客户号,平台code,扩展字段1,扩展字段2,扩展字段3,扩展字段4,扩展字段5,扩展字段6");
            OdbcHelper odbcHelper = null;
            DataTable dataList = new DataTable();
            try
            {
                odbcHelper = new OdbcHelper(this.ConnectString);
                dataList = getSqlField(odbcHelper, minTime, maxTime);
                odbcHelper = null;
            }
            catch (Exception exp)
            {
                Log.Debug(exp);
            }
            finally
            {
                bool flag = odbcHelper != null;
                if (flag)
                {
                    odbcHelper.CloseConnection();
                    odbcHelper = null;
                }
            }
            // 获取录音流水文件List
            string lastTimeFileName = this.baseFilePath + "\\lastTimeFileName.txt";
            Log.Debug("获取上次分析路径为:" + lastTimeFileName);
            List<string> filePathList = new List<string>();
            // 判断文件是否存在
            if (File.Exists(lastTimeFileName))
            {
                
                string catalog = File.ReadAllText(lastTimeFileName);
                Log.Debug("成功获取上次记录:" + catalog);
                //E:\Recording\400001\004\11\40
                // 上一次copy文件夹的目录级别
                string[] catalogList = catalog.Split('\\');
                int catalogListSize = catalogList.Length;
                string level1Catalog = catalogList[catalogListSize - 3];//004
                string level2Catalog = catalogList[catalogListSize - 2];//11
                string level3Catalog = catalogList[catalogListSize - 1];//40
                //4-99
                for (int i = int.Parse(level1Catalog); i <= 99; i++)
                {
                    //copyXmlFilePath=E:\Recording\400001
                    string level1Dir = this.copyXmlFilePath + "\\" + i.ToString().PadLeft(3, '0');
                    Log.Debug("判断文件夹路径是否存在" + level1Dir);//E:\Recording\400001\004
                    // 判断文件夹路径是否存在 不存在则结束循环
                    if (!Directory.Exists(level1Dir))
                    {
                        break;
                    }
                    //如果是旧的上层文件夹，则下一层从该序号开始
                    for (int j = i == int.Parse(level1Catalog) ? int.Parse(level2Catalog) : 0; j <= 99; j++)
                    {
                        //E:\Recording\400001\004\11
                        string level2Dir = level1Dir + "\\" + j.ToString().PadLeft(2, '0');
                        Log.Debug("判断文件夹路径是否存在" + level2Dir);
                        // 判断文件夹路径是否存在 不存在则结束循环
                        if (!Directory.Exists(level2Dir))
                        {
                            break;
                        }
                        for (int k = j == int.Parse(level2Catalog) ? int.Parse(level3Catalog) : 0; k <= 99; k++)
                        {
                            //E:\Recording\400001\004\11\40
                            string level3Dir = level2Dir + "\\" + k.ToString().PadLeft(2, '0');
                            Log.Debug("判断文件夹路径是否存在" + level3Dir);
                            // 判断文件夹路径是否存在 不存在则结束循环
                            if (!Directory.Exists(level3Dir))
                            {
                                break;
                            }
                            filePathList = GetDirectories(level3Dir, filePathList);
                            string filePathString = string.Join(",", filePathList);
                            Log.Debug("扫描到的文件列表为：" + filePathString);
                        }
                    }
                }
            }
            // 获取当前日期格式
            string nowDate = maxTime.AddHours(-1).ToString("yyyy-MM-dd");
            string newFilePath = this.csvBaseFilePath + "\\" + nowDate;

            // 最后一个文件名
            string lastFileName = "";

            if (dataList != null && dataList.Rows.Count > 0)
            {
                foreach (string path in filePathList)
                {
                    // 获取录音文件信息
                    FileInfo xmlFile = new FileInfo(path);
                    string extension = Path.GetExtension(path);
                    if (".xml".Equals(extension))
                    {
                        // 设置xmlModel属性
                        XmlModel xmlModel = new XmlModel();
                        XmlFileAnalysis(path, xmlModel);
                        string switchCallId = xmlModel.switch_call_id;
                        if (switchCallId != null)
                        {
                            DataRow[] row = dataList.Select("callid = " + xmlModel.switch_call_id);
                            if (row.Length > 0)
                            {
                                //拷贝到csv当天目录下
                                string wavPath = path.Replace("xml", "wav");
                                CopyToFile(wavPath, newFilePath);
                                DataRow dr = row[0];
                                // 获取录音ID   
                                string recordingId = dr[0].ToString();
                                // 获取质检场景
                                string caltype = dr[1].ToString();
                                caltype = caltype.Replace("-", "_");
                                int index = caltype.IndexOf("(");
                                if (index >= 0)
                                {
                                    caltype = caltype.Substring(0, index);
                                }
                                // 获取入司时间
                                string employedDate = dr[2].ToString();
                                // 获取组别
                                string title = dr[3].ToString();
                                // 客户评价
                                string evaluation = dr[4].ToString();
                                // 客户等级
                                string level = dr[5].ToString();
                                // 客户类别
                                string category = dr[6].ToString();
                                // 坐席工号
                                string staffname = dr[7].ToString();
                                // 坐席ID
                                string agent_id = dr[8].ToString();
                                // 业务号
                                string remark6 = dr[9].ToString();

                                xmlModel.recordingId = recordingId;
                                xmlModel.recordingFileName = Path.GetFileNameWithoutExtension(path) + ".wav";
                                xmlModel.sceneName = caltype;
                                xmlModel.remark1 = employedDate;
                                xmlModel.remark2 = title;
                                xmlModel.remark3 = evaluation;
                                xmlModel.remark4 = level;
                                xmlModel.remark5 = category;
                                xmlModel.agentCti = staffname;
                                xmlModel.agentId = agent_id;
                                xmlModel.remark6 = remark6;

                                lastFileName = Path.GetFileNameWithoutExtension(path) + ".wav";
                                // 定义列字符串
                                string lineString = "";
                                // 遍历对象属性赋值拼接字符串
                                foreach (System.Reflection.PropertyInfo p in xmlModel.GetType().GetProperties())
                                {
                                    lineString += p.GetValue(xmlModel);
                                    lineString += ",";
                                }
                                lineString = lineString.Remove(lineString.LastIndexOf(","));
                                lineString = lineString.Remove(lineString.LastIndexOf(","));
                                lineList.Add(lineString);
                            }
                        }
                    }
                }
            }
            string filePath = newFilePath + "\\" + maxTime.ToString("yyyy-MM-ddHH") + ".csv";  //文件路径
            CreateCsvFile(filePath, lineList);
            // 获取最后一个文件目录完成csv生成之后将最后一个文件所在目录缓存进文件
            if (!string.IsNullOrEmpty(lastFileName))
            {
                string directory1 = lastFileName.Substring(6, 3);
                string directory2 = lastFileName.Substring(9, 2);
                string directory3 = lastFileName.Substring(11, 2);
                string lastFilePath = this.copyXmlFilePath + "\\" + directory1 + "\\" + directory2 + "\\" + directory3;
                string path = this.baseFilePath + "\\lastTimeFileName.txt";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                File.AppendAllText(path, lastFilePath);
            }
        }
        // 拷贝文件到另一个文件夹下
        // <param name="sourceName">源文件路径</param>
        // <param name="folderPath">目标路径（目标文件夹）</param>
        private void CopyToFile(string sourceName, string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            //当前文件如果不用新的文件名，那么就用原文件文件名
            string fileName = Path.GetFileName(sourceName);
            //这里可以给文件换个新名字，如下：
            //string fileName = string.Format("{0}.{1}", "newFileText", "txt");

            //目标整体路径
            string targetPath = Path.Combine(folderPath, fileName);

            //Copy到新文件下
            FileInfo file = new FileInfo(sourceName);
            if (file.Exists)
            {
                //true 为覆盖已存在的同名文件，false 为不覆盖
                file.CopyTo(targetPath, true);
            }
        }

        private void CopyToFile(string sourceName, string folderPath, string newFileName)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            //这里可以给文件换个新名字，如下：
            //目标整体路径
            string targetPath = Path.Combine(folderPath, newFileName);

            //Copy到新文件下
            FileInfo file = new FileInfo(sourceName);
            if (file.Exists)
            {
                //true 为覆盖已存在的同名文件，false 为不覆盖
                file.CopyTo(targetPath, true);
            }
        }
        // 时间检测 定时任务
        public void OnTimer(object sender, ElapsedEventArgs args)
        {
            // 时间等于12:15  执行中午的录音拷贝
            if (DateTime.Now.Hour == 12 && DateTime.Now.Minute == 15)
            {
                // 当天0时0分0秒：
                minDateTime = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                // 当天12：00
                maxDateTime = minDateTime.AddHours(12);
                Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "录音文件拷贝任务");
                // 调用录音拷贝任务
                RecordingCopyJob(minDateTime, maxDateTime);
            }
            // 时间等于12: 30  执行中午的生成csv文件
            else if (DateTime.Now.Hour == 12 && DateTime.Now.Minute == 30)
            {
                // 当天0时0分0秒：
                minDateTime = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                // 当天12：00
                maxDateTime = minDateTime.AddHours(12);
                Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "的生成csv文件任务");
                CreateCsvFileJob(minDateTime, maxDateTime);
            }
            // 时间等于00：15 执行下午的录音拷贝
            else if (DateTime.Now.Hour == 00 && DateTime.Now.Minute == 15)
            {

                maxDateTime = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                minDateTime = maxDateTime.AddHours(-12);
                Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "录音文件拷贝任务");
                RecordingCopyJob(minDateTime, maxDateTime);
            }
            // 时间等于00：30 执行下午的生成csv文件，00：30
            else if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 30)
            {
                maxDateTime = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                minDateTime = maxDateTime.AddHours(-12);
                Log.Debug("开始执行" + minDateTime + "至" + maxDateTime + "的生成csv文件任务");
                CreateCsvFileJob(minDateTime, maxDateTime);
            }
        }

        // 录音拷贝任务
        public void RecordingCopyJob(DateTime minTime, DateTime maxTime)
        {
            Log.Debug("开始录音拷贝处理");
            // 定义文件路径列表
            List<string> list = new List<string>();
            // 获取某文件夹里最新的文件夹
            string path = this.baseFilePath + "\\lastTimeFileName.txt";
            Log.Debug("获取上次拷贝地址为:" + path);
            // 判断文件是否存在
            if (File.Exists(path))
            {
                Log.Debug("成功获取上次记录:" + path);
                string catalog = File.ReadAllText(path);
                // 上一次copy文件夹的目录级别
                string[] catalogList = catalog.Split('\\');
                int catalogListSize = catalogList.Length;
                string level1Catalog = catalogList[catalogListSize - 3];
                string level2Catalog = catalogList[catalogListSize - 2];
                string level3Catalog = catalogList[catalogListSize - 1];
                if (level3Catalog == "00")
                {
                    level3Catalog = "99";
                    if (level2Catalog == "00")
                    {
                        level2Catalog = "99";
                        level1Catalog = (int.Parse(level1Catalog) - 1).ToString().PadLeft(3, '0');
                    }
                    else
                    {
                        level2Catalog = (int.Parse(level2Catalog) - 1).ToString().PadLeft(2, '0');
                    }
                }
                else
                {
                    level3Catalog = (int.Parse(level3Catalog) - 1).ToString().PadLeft(2, '0');
                }

                // 获取文件夹内的最新文件夹(max:一级目录，max2:二级目录，max3：三级目录)
                FtpHelper ftpHelper = new FtpHelper();
                List<string> dirctoryList = ftpHelper.GetDirctory(this.xmlBasePath);
                int max = getMaxNumber(dirctoryList);
                int max2 = 0;
                int max3 = 0;
                // 循环获取对象中的文件路径
                for (int i = int.Parse(level1Catalog); i <= max; i++)
                {
                    string path2 = this.xmlBasePath + i.ToString().PadLeft(3, '0') + "/";
                    string copyPath2 = this.copyXmlFilePath + "\\" + i.ToString().PadLeft(3, '0');
                    string path3 = "";
                    string copyPath3 = "";
                    string path4 = "";
                    string copyPath4 = "";
                    List<string> dirctoryList2 = ftpHelper.GetDirctory(path2);
                    max2 = getMaxNumber(dirctoryList2);
                    Log.Debug("i:"+i+ "|level1Catalog:"+ int.Parse(level1Catalog));
                    if (i > int.Parse(level1Catalog))
                    {
                        level2Catalog = "0";
                        level3Catalog = "0";
                    }
                    for (int j = int.Parse(level2Catalog); j <= max2; j++)
                    {
                        path3 = path2 + j.ToString().PadLeft(2, '0') + "/";
                        copyPath3 = copyPath2 + "\\" + j.ToString().PadLeft(2, '0');
                        ftpHelper.GetDirctory(path3);
                        List<string> dirctoryList3 = ftpHelper.GetDirctory(path3);
                        max3 = getMaxNumber(dirctoryList3);
                        if (j > int.Parse(level2Catalog))
                        {
                            level3Catalog = "0";
                        }
                        Log.Debug("secondCatalog:" + path3 + "|max3:" + max3 + "|level3Catalog:" + level3Catalog);
                        for (int l = int.Parse(level3Catalog); l <= max3; l++)
                        {
                            path4 = path3 + l.ToString().PadLeft(2, '0') + "/";
                            copyPath4 = copyPath3 + "\\" + l.ToString().PadLeft(2, '0');
                            Log.Info("开始从" + path4 + "复制录音文件");
                            ftpHelper.DownFtp(path4, copyPath4);
                        }
                    }
                }
            }
            else
            {
                List<string> filePathList = new List<string>();
                FtpHelper ftpHelper = new FtpHelper();
                ftpHelper.DownFtp(this.xmlBasePath, this.copyXmlFilePath);
            }

        }
        // 获取当前路径下数量最大的文件夹名称
        public int getMaxNumberDirectories(string path)
        {
            DirectoryInfo d = new DirectoryInfo(path);
            DirectoryInfo[] directs = d.GetDirectories();//文件夹
            int max = 0;
            foreach (DirectoryInfo dd in directs)
            {
                int temp = int.Parse(dd.Name);
                if (temp > max)
                {
                    max = temp;
                }
            }

            return max;
        }
        // 获取当前路径下数量最大的文件夹名称
        public int getMaxNumber(List<string> numberList)
        {
            int max = 0;
            foreach (string number in numberList)
            {
                int temp = int.Parse(number);
                if (temp > max)
                {
                    max = temp;
                }
            }
            return max;
        }
        // 获取文件夹名
        public List<string> GetDirectories(string dir, List<string> list)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            FileInfo[] files = d.GetFiles();//文件
            DirectoryInfo[] directs = d.GetDirectories();//文件夹
            foreach (FileInfo f in files)
            {
                list.Add(f.FullName);//添加文件名到列表中  
            }
            //获取子文件夹内的文件列表，递归遍历  
            foreach (DirectoryInfo dd in directs)
            {
                GetDirectories(dd.FullName, list);
            }
            return list;
        }
        /// <summary>
        /// 将制定目录下的文件压缩为tar文件
        /// </summary>
        /// <param name="IN">源目录D:\\Images</param>
        /// <param name="OUT">目标目录tar文件F:\\tar\\aaa.tar</param>
        public static void CompressTarFile(string IN, string OUT)
        {
            Stream outStream = new FileStream(OUT, FileMode.OpenOrCreate);
            TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
            String[] files = Directory.GetFiles(IN);
            foreach (String name in files)
            {
                TarEntry entry = TarEntry.CreateEntryFromFile(name);
                entry.Name = name.Substring(name.LastIndexOf('\\') + 1);
                archive.WriteEntry(entry, true);
            }
            if (archive != null)
            {
                archive.CloseArchive();
            }
        }
        private DataTable getSqlField(OdbcHelper odbcHelper, DateTime minTime, DateTime maxTime)
        {
            string sql = string.Format("select r.recordno ID," +
                "case when s3.workordertype3desc is null and s2.workordertype2desc is not null then s1.workordertype1desc || '_' || s2.workordertype2desc "+
                "when s3.workordertype3desc is null and s2.workordertype2desc is null then substr(caltype, instr(caltype, '-', 1, 2) + 1, instr(caltype, '(') - 9) "+
                "when ec.CALLNATUREGROUP_ID = 'FWF7RO' and e.calltype = '1' then substr(caltype, instr(caltype, '-', 1, 2) + 1, instr(caltype, '(') - 9)  "+
                "else s1.workordertype1desc || '_' || s2.workordertype2desc || '_' || s3.workordertype3desc end 质检场景,"+
                "case when s.employeddate is null then '无入司时间'" +
                "when floor(months_between(sysdate,s.employeddate)) >=0 and floor(months_between(sysdate,s.employeddate))< 3 then '三个月以内'" +
                "when floor(months_between(sysdate,s.employeddate)) >=6 and floor(months_between(sysdate,s.employeddate))< 12 then '半年到一年'" +
                "when floor(months_between(sysdate,s.employeddate)) >=12 and floor(months_between(sysdate,s.employeddate))< 24 then '一年到两年'" +
                "else '两年及以上' end   入司时间,s.title 组别,decode(w.statisfaction1,'1','非常满意','2','满意','3','不满意','4','非常不满意','') 客户评价,c.fax 客户等级,c.homepage 客户类别," +
                "s.staffname 坐席工号,s.agent_id 坐席id,t.businessno 业务号,r.initcallid callid from callcenter.record r " +
                "left join callcenter.event e on e.event_guid = r.event_guid " +
                "left join callcenter.tabccalsum t on t.relation_id = r.event_guid " +
                "left join (select wm.event_guid,wm.statisfaction1,row_number() over(partition by wm.event_guid order by createddate) rn from wmsk_statisfaction wm) w on e.event_guid=w.event_guid " +
                "left join callcenter.staff s on r.staff_id = s.staff_id " +
                "left join callcenter.customer c on r.customer_guid = c.customer_guid " +
                "left join callcenter.eventcallnature ec on ec.event_guid = r.event_guid " +
                "left join callcenter.sys_workordertype1 s1 on s1.workordertype1_id = ec.callnaturegroup_id " +
                "left join callcenter.sys_workordertype2 s2 on s2.workordertype2_id = ec.callnature_id " +
                "left join callcenter.sys_workordertype3 s3 on s3.workordertype3_id = ec.callnature3_id " +
                "left join callcenter.sys_workordertype4 s4 on s4.workordertype4_id = ec.callnature4_id " +
                "left join callcenter.custom_parameter cp1 on cp1.parameter_id = t.producttype and cp1.parameter_type = 'producttype' " +
                "where (w.rn=1 or w.rn is null) and " +
                "r.starttime>=to_date('{0}','yyyy-mm-dd hh24:mi:ss') " +
                "and r.starttime <= to_date('{1}','yyyy-mm-dd hh24:mi:ss')", minTime.ToString(), maxTime.ToString());
            DataTable data = odbcHelper.GetDataTable(sql);
            string idString = "";
            if (data != null) 
            {
                Log.Debug("sql查询结果行数:" + data.Rows.Count.ToString());
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    idString = idString + data.Rows[i]["callid"].ToString() + ",";//行集合.行【号】列【名】
                }
            }
            
            Log.Debug("sql查询结果11为:" + idString);
            return data;
        }

        public static string DeleteOneFile(string fileFullPath)
        {
            // 1、首先判断文件或者文件路径是否存在
            if (Directory.Exists(fileFullPath))
            {
                // 2、根据路径字符串判断是文件还是文件夹
                FileAttributes attr = File.GetAttributes(fileFullPath);
                // 3、根据具体类型进行删除
                if (attr == FileAttributes.Directory)
                {
                    Directory.Delete(fileFullPath, true); // 3.1、删除文件夹
                }
                else
                {
                    File.Delete(fileFullPath);// 3.2、删除文件
                }
                File.Delete(fileFullPath);
                return "删除成功:" + fileFullPath;
            }
            return "无该文件或文件夹:" + fileFullPath;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            this.minDateTime = this.dateTimePicker1.Value;
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            this.maxDateTime = this.dateTimePicker2.Value;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Log.Debug("手动执行" + DateTime.Now.Hour + "清理过期录音文件任务");
            CleanCsvRecardFile(this.copyXmlFilePath, 8);
            CleanCsvRecardFile(this.csvBaseFilePath, 8);
        }

        // 删除某文件下超过days天的文件并且保留csv文件
        public static void CleanCsvRecardFile(string folderPath, int days)
        {
            // 获取当前日期和时间
            DateTime currentDate = DateTime.Now;

            // 遍历文件夹中的所有文件
            string[] files = Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                // 获取文件最后写入时间
                DateTime lastWriteTime = File.GetLastWriteTime(file);

                // 获取文件拓展名
                String fileExtension = Path.GetExtension(file);

                // 计算最后写入时间与当前时间的差值
                TimeSpan timeDifference = currentDate - lastWriteTime;

                // 如果差值大于指定天数，则删除文件
                if (timeDifference.TotalDays > days && fileExtension != ".csv")
                {
                    File.Delete(file);
                    Console.WriteLine("Deleted file: " + file);
                }
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            
        }
    }
}
