using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
using SevenZip;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using Utils;
using SiteCore;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging;
using Microsoft.WindowsAPICodePack.Shell;
using System.Drawing.Imaging;
using CorelDRAW;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Data;
using System.Text.RegularExpressions;
using MSharp.Framework;
using System.Net.Http.Headers;
using System.Net.Http;
using SQLData;
using NHibernate.Mapping;
using System.Collections.Generic;
using System.Linq;
using NPOI.OpenXmlFormats.Shared;

public partial class uploadFile : System.Web.UI.Page
{
    public static string upPath = ConfigurationManager.AppSettings["upPath"];
    public static string curPath = ConfigurationManager.AppSettings["curPath"];
    static CdrConvert cdrConvert = new CdrConvert();

    private void conSuc(string msg)
    {
        Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "!\"}");
        //Response.End();
    }

    private void conErc(string msg)
    {
        Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "!\"}");
        //Response.End();
    }

    public string GetMD5HashFromFile(HttpPostedFile file)
    {
        try
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file.InputStream);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            XLog.SaveLog(0, "上传MD5错误!" + ex.Message);
        }

        return "";
    }


    private static byte[] GetBlobByHttpPostedFile(HttpPostedFile httpPostedFile)
    {
        var contentLength = httpPostedFile.ContentLength;
        var result = new byte[contentLength];
        var inputStream = httpPostedFile.InputStream;
        inputStream.Read(result, 0, contentLength);
        return result;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (CurrentUser == null)
        //{
        //    Response.Write(err);
        //    return;
        //}
        //CeErpTradeCell.GetByCtid("1717009344450030601");

        if (Request.Files.Count < 1)
        {
            conErc("空文件!");
            return;
        }
        int userId = 0;
        int orgid = 0;
        if (Request["userid"] != null)
        {
            userId = Convert.ToInt32(Request["userid"]);
        }
        if (Request["orgid"] != null)
        {
            orgid = Convert.ToInt32(Request["orgid"]);
        }

        HttpPostedFile postFile = Request.Files[0];
        if (postFile != null)
        {
            string file_name = postFile.FileName;
            string namePattern = @"《(.*?)》";
            Regex nameReg = new Regex(namePattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
            MatchCollection nameMatches = nameReg.Matches(file_name);//设定要查找的字符串
            if (nameMatches.Count > 0)
            {
                foreach (Match match in nameMatches)
                {
                    file_name = file_name.Replace(match.Value, "");
                }
            }
            file_name = file_name.Replace("（", "(");
            file_name = file_name.Replace("）", ")");
            string ctid = MidStrEx(file_name, "(", ")").Trim();
            if (string.IsNullOrEmpty(ctid))
            {
                conErc("上传的文件名格式不正确");
                return;
            }
            string memoCtid = ctid;
            if (ctid.IndexOf("C") == -1)
            {
                if (file_name.IndexOf("[") != -1 && file_name.IndexOf("C") != -1)
                {
                    if (ctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1]   对应ctid是 S_S_C1_1962772776865084101
                    {
                        int lastIndex = ctid.LastIndexOf("S_"); //最后一个S_的位置
                        string sPre = ctid.Substring(0, lastIndex + 2); //S_S_
                        string initTid = ctid.Substring(lastIndex + 2, ctid.Length - lastIndex - 2); //1962772776865084101

                        string pre_ctid = MidStrEx(file_name, "[", "]"); //C1
                        if (pre_ctid.IndexOf("+") != -1)
                        {
                            pre_ctid = "C" + pre_ctid.Split('+')[1];
                        }
                        memoCtid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
                    }
                    else
                    {
                        string pre_ctid = MidStrEx(file_name, "[", "]");
                        if (pre_ctid.IndexOf("+") != -1)
                        {
                            pre_ctid = "C" + pre_ctid.Split('+')[1];
                        }
                        memoCtid = pre_ctid + "_" + ctid;
                    }

                }
            }
            CeErpTradeCell entity = null;
            if (ctid != "") entity = CeErpTradeCell.GetByCode(ctid);
            if (entity == null) entity = CeErpTradeCell.GetByCtid(ctid);
            if (entity == null) entity = CeErpTradeCell.GetByCtid(memoCtid);
            try
            {

                if (entity != null)
                {
                    string pname = Path.GetFileNameWithoutExtension(file_name);
                    if (entity.IsRefund == 2)
                    {
                        StringBuilder sql = new StringBuilder();
                        sql.AppendFormat("select refund_status from CE_ErpTradeOrder where tid='{0}'", entity.tid);

                        DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
                        bool isAll = true;
                        foreach (DataRow dr in dt.Rows)
                        {
                            if ("NO_REFUND".Equals(dr["refund_status"]))
                            {
                                isAll = false;
                                break;
                            }
                        }
                        if (isAll)
                        {
                            conErc("此单退款，不允许上传");
                            return;
                        }
                    }
                    if (entity.seller_memo != pname)
                    {
                        conErc("上传的文件名与备注不符合!");
                        return;
                    }
                    if (entity.OrderState == -1)
                    {
                        conErc("还未审核不允许上传");
                        return;
                    }
                    if (entity.OrderState < (int)OrderState.设计中 && orgid != 10 && orgid != 4)
                    {
                        conErc("还未开始设计不允许上传");
                        return;
                    }
                    //if (pname.IndexOf("现货") != -1)
                    //{
                    //    conErc("设计款的单文件名不能有现货字眼");
                    //    return;
                    //}
                    //更新状态
                    if (entity.OrderState >= (int)OrderState.下单完成)
                    {
                        conErc("已经下单无法上传!");
                        return;
                    }
                    if (entity.IsVerifyToSupplier)
                    {
                        conErc("订单已到车间无法上传!");
                        return;
                    }
                    string extend = Path.GetExtension(file_name).ToLower();
                    if (!(extend == ".cdr" || extend == ".zip" || extend == ".rar" || extend == ".pdf"))
                    {
                        conErc("只允许上传zip和cdr文件!");
                        return;
                    }
                    CeErpTrade ceErpTrade = CeErpTrade.Get(entity.tid);
                    if (ceErpTrade != null)
                    {
                        if (ceErpTrade.receiver_state.Contains("台湾") && string.IsNullOrEmpty(ceErpTrade.receiver_zip))
                        {
                            conErc("台湾客户需填写身份证号!");
                            return;
                        }
                    }

                    if (entity.OrderState != 5)
                    {
                        entity.FinishDesignTime = DateTime.Now;
                        if (entity.isDianziOrder == 1 || entity.ProductId == 57 || entity.ProductId == 28)
                        {
                            entity.OrderState = 6;
                            entity.SupplierId = 35;
                            entity.FinishPlaceTime = DateTime.Now;
                            bool sendResult = commonHelper.SetOrderDummyDelivery(entity.tid);
                            if (sendResult)
                            {
                                entity.OrderState = 7;
                            }
                        }
                        else
                            entity.OrderState = 5; //设计完成
                                                   //if (entity.IsReturn == 2) //2是下单人打回给设计的,重新上传的话，需要清除打回
                                                   //{

                        entity.IsXianHuo = 0;
                        entity.IsVerifyToSupplier = false;
                        //}
                    }
                    entity.IsReturn = 0;
                    int num = getProductCount(entity.seller_memo);
                    if (entity.MemoOpt == 1 || entity.MemoOpt == 2)
                    {
                        entity.MemoOpt = 0;
                    }

                    if (string.IsNullOrEmpty(entity.OtherMemo) && !entity.ctid.Contains("S_"))
                    {
                        int supplierId = 0;
                        try
                        {
                            supplierId = getsupplierId(entity);

                        }
                        catch (Exception ex)
                        {
                            XLog.SaveLog(0, "上传自动指派车间发生错误!" + ex);
                        }
                        if (supplierId > 0)
                        {
                            entity.IsVerifyToSupplier = true;
                            entity.SupplierId = supplierId;
                            entity.FinishPlaceTime = DateTime.Now;
                        }
                    }

                    if (entity.ProductId == 2690)
                    {
                        entity.IsVerifyToSupplier = true;
                        entity.SupplierId = 97;
                        entity.FinishPlaceTime = DateTime.Now;
                    }
                    if (entity.ProductId == 2701)
                    {
                        entity.IsVerifyToSupplier = true;
                        entity.SupplierId = 98;
                        entity.FinishPlaceTime = DateTime.Now;
                    }
                    string dPath = entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMMdd");
                    //XLog.SaveLog(5, dPath);
                    string sPath = Path.Combine(upPath, dPath);
                    string cpath = Path.Combine(upPath, entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMM"));
                    //XLog.SaveLog(5, sPath);
                    //XLog.SaveLog(5, Directory.Exists(sPath).ToString());
                    if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);
                    if (!Directory.Exists(cpath)) Directory.CreateDirectory(cpath);
                    string saveFile = Path.Combine(sPath, file_name);

                    string f_ext = Path.GetExtension(saveFile);
                    string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
                    string _file = "";
                    foreach (string ext in extArr)
                    {
                        if (f_ext != ext)
                        {
                            _file = saveFile.Replace(f_ext, ext);
                            if (File.Exists(_file)) File.Delete(_file);
                        }
                        else
                        {
                            if (File.Exists(saveFile)) File.Delete(saveFile);

                        }
                    }
                    //上传文件
                    postFile.SaveAs(saveFile);
                    entity.FileMd5 = GetMD5HashFromFile(postFile);
                    //XLog.SaveLog(0, saveFile);
                    entity.UpdateTime = DateTime.Now;
                    entity.Update();
                    //CeErpTradeCell.UpdateRelationOrder(entity);
                    CeErpTradeCell.UpdateRelationOrder(entity.ctid);
                    CeErpProduct product = CeErpProduct.GetById(entity.ProductId);
                    if (product != null)
                    {
                        string param = "[{ \"product_type\": \"" + product.PType + "\",\"remark\": \"" + entity.seller_memo + "\",\"index\": \"" + entity.OrderSn + "\",\"orderid\": \"" + entity.ctid + "\",\"price\": \"" + entity.payment + "\"}]";
                        sysHttpClient(param);
                    }
                    CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, userId, "上传设计文件-" + saveFile);
                    if (ctid.IndexOf("S_") >= -1)
                    {
                        StringBuilder sql = new StringBuilder();
                        sql.AppendFormat("select * from Ce_ErpTradeCellExtend where ctid='{0}'", entity.ctid);
                        DataTable cellEx = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
                        if (cellEx.Rows.Count > 0)
                        {
                            string txtReprintTime = cellEx.Rows[0]["ReprintTime"].ToString();
                            if (!string.IsNullOrEmpty(txtReprintTime) && !"null".Equals(txtReprintTime))
                            {
                                DateTime reprint = DateTime.Parse(txtReprintTime);
                                if (DateTime.Compare(DateTime.Now.AddHours(-24), reprint) >= 0)
                                {
                                    string parentId = entity.ctid.Substring(2);
                                    string update_sql = string.Format("update Ce_ErpTradeAfterSaleExtend set ReprintOut = ReprintOut+1 where tid= '{0}' ;", parentId);
                                    CeErpTradeLog.ExecuteNonQuery(update_sql);
                                }
                            }

                        }
                    }
                    if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        //string sql = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", saveFile);
                        //CeErpTradeLog.ExecuteNonQuery(sql);
                    }
                    else if (Path.GetExtension(saveFile).IndexOf("zip", StringComparison.OrdinalIgnoreCase) != -1 || Path.GetExtension(saveFile).IndexOf("rar", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        try
                        {
                            DecompressZIPandRAR(saveFile, sPath, file_name);
                        }
                        catch (Exception ex)
                        {
                            CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "解压失败!");
                            XLog.SaveLog(0, "上传解压发生错误!" + ex.Message);
                        }
                        //Decompress(saveFile,sPath);
                    }
                    //new Thread(new ThreadStart(delegate ()
                    //{
                    //System.Threading.Thread.Sleep(2000);

                    if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        var identity = WindowsIdentity.GetCurrent();
                        var principal = new WindowsPrincipal(identity);
                        Task.Run(async () =>
                       {
                           string filePath = Path.GetFullPath(saveFile);
                           string targPath = Path.Combine(cpath, file_name);
                           using (identity.Impersonate())
                           {
                               try
                               {
                                   if (File.Exists(filePath))
                                   {
                                       cdrConvert.CdrConvertPng(filePath, targPath);
                                   }

                               }
                               catch (Exception ex)
                               {
                                   XLog.SaveLog(0, filePath + ",转成图片出错：" + ex.Message);
                               }
                           }
                       });
                    }

                    //})).Start();
                    conSuc("上传成功！");
                    return;
                }
                else
                {
                    conErc("找不到对应的订单");
                    return;
                }
            }
            catch (Exception ex)
            {

                conErc("上传发生错误!" + CommonHelper.FormatTextArea(ex.Message));
                CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "上传失败!");
                XLog.SaveLog(0, "上传发生错误!" + ex.Message);
                return;
            }
            finally
            {
                if (postFile != null)
                {
                    postFile.InputStream.Close();
                }
            }
        }
        conErc("空文件!");
    }

    private int getsupplierId(CeErpTradeCell entity)
    {
        int supplierId = 0;
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat("select * from CE_ErpUpFileSupplier where isOpen = 1", "");
        DataTable cellEx = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
        if (entity == null)
        {
            return supplierId;
        }
        int num = getProductCount(entity.seller_memo);
        foreach (DataRow row in cellEx.Rows)
        {
            bool isIn = true;
            //判断材质工艺都要符合
            if (!Convert.IsDBNull(row["seller_memo"]) && !string.IsNullOrEmpty(row["seller_memo"].ToString()))
            {
                string memo = row["seller_memo"].ToString();

                string[] memolist = memo.Split('+');
                for (int i = 0; i < memolist.Length; i++)
                {
                    if (!Regex.IsMatch(entity.seller_memo, memolist[i].Replace("/", "|")))
                    {
                        isIn = false;
                    }
                }
            }

            if (!isIn)
            {
                continue;
            }
            //判断金额符不符合
            if (!Convert.IsDBNull(row["payment"]) && !string.IsNullOrEmpty(row["payment"].ToString()))
            {
                string payment = row["payment"].ToString();
                string[] paymentList = payment.Split('-');

                if (!string.IsNullOrEmpty(paymentList[0]))
                {
                    if (entity.payment < Convert.ToDouble(paymentList[0]))
                    {
                        continue;
                    }
                }

                if (!string.IsNullOrEmpty(paymentList[1]))
                {
                    if (entity.payment > Convert.ToDouble(paymentList[1]))
                    {
                        continue;
                    }
                }
            }

            if (!Convert.IsDBNull(row["size"]) && !string.IsNullOrEmpty(row["size"].ToString()))
            {
                string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
                string memo = entity.seller_memo.Replace("MM", "mm").Replace("CM", "cm");
                Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
                MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
                double width = 0;
                double height = 0;
                try
                {
                    if (matches[0].Success)
                    {
                        string sizematches = matches[0].Groups[0].Value;
                        sizematches = sizematches.Replace("mm", "");
                        sizematches = sizematches.Replace("cm", "");
                        string[] size_list = sizematches.Split('x');
                        if (size_list.Length > 1)
                        {
                            width = Convert.ToDouble(size_list[0]);
                            height = Convert.ToDouble(size_list[1]);
                        }

                    }

                }
                catch (Exception ex)
                {

                }
                string size = row["size"].ToString();
                string[] sizeList = size.Split('-');
                if (!string.IsNullOrEmpty(sizeList[0]))
                {
                    string[] sizeItemList = sizeList[0].Split('x');
                    //第一个尺寸格式不正确
                    if (sizeItemList.Length < 2)
                    {
                        continue;
                    }
                    double sizeWidth = Convert.ToDouble(sizeItemList[0]);
                    double sizeheight = Convert.ToDouble(sizeItemList[1]);
                    //备注尺寸要大于第一个尺寸

                    if (!((width > sizeWidth && height > sizeheight) || (width > sizeheight && height > sizeWidth)))
                    {
                        continue;
                    }

                }

                if (!string.IsNullOrEmpty(sizeList[1]))
                {
                    string[] sizeItemList = sizeList[1].Split('x');
                    //第二个尺寸格式不正确
                    if (sizeItemList.Length < 2)
                    {
                        continue;
                    }
                    double sizeWidth = Convert.ToDouble(sizeItemList[0]);
                    double sizeheight = Convert.ToDouble(sizeItemList[1]);
                    //备注尺寸要大于第二个尺寸

                    if (!((width < sizeWidth && height < sizeheight) || (width < sizeheight && height < sizeWidth)))
                    {
                        continue;
                    }

                }
            }
            //判断数量是否符合
            if (!Convert.IsDBNull(row["number"]) && !string.IsNullOrEmpty(row["number"].ToString()))
            {
                string numberText = row["number"].ToString();

                string[] numberTextList = numberText.Split('-');
                int number = 0;
                if (!string.IsNullOrEmpty(numberTextList[0]))
                {
                    number = Convert.ToInt32(numberTextList[0]);
                    if (number > num)
                    {
                        continue;
                    }
                }
                if (!string.IsNullOrEmpty(numberTextList[1]))
                {
                    number = Convert.ToInt32(numberTextList[1]);
                    if (number < num)
                    {
                        continue;
                    }
                }
            }
            //判断店铺符不符合
            if (!Convert.IsDBNull(row["shopIds"]) && !string.IsNullOrEmpty(row["shopIds"].ToString()))
            {
                List<string> shopids = row["shopIds"].ToString().Split(',').ToList();

                if (!shopids.Contains(entity.ShopId.ToString()))
                {
                    continue;
                }
            }
            //判断店铺符不符合
            if (!Convert.IsDBNull(row["noShopIds"]) && !string.IsNullOrEmpty(row["noShopIds"].ToString()))
            {
                List<string> shopids = row["noShopIds"].ToString().Split(',').ToList();

                if (shopids.Contains(entity.ShopId.ToString()))
                {
                    continue;
                }
            }
            //地区不符合
            if (!Convert.IsDBNull(row["address"]) && !string.IsNullOrEmpty(row["address"].ToString()))
            {
                if (!Regex.IsMatch(entity.seller_memo, row["address"].ToString().Replace("、", "|")))
                {
                    continue;
                }
            }
            //限制条件
            if (!Convert.IsDBNull(row["filterText"]) && !string.IsNullOrEmpty(row["filterText"].ToString()))
            {
                if (Regex.IsMatch(entity.seller_memo, row["filterText"].ToString().Replace("/", "|")))
                {
                    continue;
                }
            }
            supplierId = Convert.ToInt32(row["supplierId"]);
            break;
        }

        return supplierId;
    }
    class CdrConvert
    {
        private object lockObject = new object();

        public void CdrConvertPng(string filePath, string targPath)
        {
            lock (lockObject)
            {
                targPath = targPath.Replace(".cdr", ".png");
                try
                {
                    Application cdr = new Application();
                    cdr.OpenDocument(filePath, 1);
                    cdr.ActiveDocument.ExportBitmap(
                    targPath,
                    cdrFilter.cdrPNG,
                    cdrExportRange.cdrCurrentPage,
                    cdrImageType.cdrRGBColorImage,
                    0, 0, 72, 72,
                    cdrAntiAliasingType.cdrNoAntiAliasing,
                    false,
                    true,
                    true,
                    false,
                    cdrCompressionType.cdrCompressionNone,
                    null).Finish();
                    cdr.ActiveDocument.Close();
                    cdr.Quit();
                    cdr = null;
                }
                catch (Exception ex)
                {
                    XLog.SaveLog(0, targPath + ",转成图片出错：" + ex.Message);

                }
                finally
                {
                    KillProcessByName("CorelDRW");
                }

            }
        }

        void KillProcessByName(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);

            foreach (Process process in processes)
            {
                try
                {
                    process.Kill();
                    process.WaitForExit(); // 等待进程退出
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
    public static int getProductCount(string txt)
    {
        // 提取"个"或"张"前面的数字
        int unit = 0;
        try
        {
            string unitPattern = @"(\d+)(?=个|张|本|套|件|卷|劵|条|箱 )";
            Match unitMatch = Regex.Match(txt, unitPattern);
            string unitNum = unitMatch.Success ? unitMatch.Groups[1].Value : "1";

            if (!int.TryParse(unitNum, out unit))
            {
                return 0;
            }

        }
        catch (Exception ex)
        {

        }
        return unit;
    }
    private void DecompressZIPandRAR(string zipFile, string targetPath, string filename)
    {

        string notExtension = filename.Substring(0, filename.Length - 4);
        SevenZipExtractor.SetLibraryPath(Server.MapPath("bin\\7z.dll"));
        LibraryFeature lf = SevenZipExtractor.CurrentLibraryFeatures;
        using (SevenZipExtractor szExtra = new SevenZipExtractor(zipFile))
        {
            //szExtra.ExtractArchive("d:\\temp");
            foreach (string afn in szExtra.ArchiveFileNames)
            {
                if (afn.IndexOf(notExtension, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    szExtra.ExtractFiles(targetPath, afn);
                    break;
                }
            }
        }

    }

    public void sysHttpClient(string param)
    {
        Task.Run(async () =>
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://47.122.57.102:11004/quotations/batch"),
                Content = new StringContent(param)
                {
                    Headers =
                    {
                        ContentType = new MediaTypeHeaderValue("application/json")
                    }
                }
            };
            var task = Task.Run(() =>
            {
                try
                {
                    var response = client.SendAsync(request).Result;
                    response.EnsureSuccessStatusCode();
                    writeLog(param + "-" + response.Content.ReadAsStringAsync().Result);
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception e)
                {
                    return "";
                }


            });
        });
    }

    private void Decompress(string GzipFile, string targetPath)
    {
        //string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\";   
        string directoryName = targetPath + "\\";
        if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录   
                                                                                       //helper.writeLog(GzipFile);
                                                                                       //helper.writeLog(directoryName);
        string CurrentDirectory = directoryName;
        byte[] data = new byte[2048];
        int size = 2048;
        ZipEntry theEntry = null;
        Stream _stream = File.OpenRead(GzipFile);
        if (_stream.Length == 0) { _stream.Close(); return; }
        try
        {
            using (ZipInputStream s = new ZipInputStream(_stream))
            {
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsDirectory)
                    {// 该结点是目录   
                        if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                    }
                    else
                    {
                        if (theEntry.Name != String.Empty && (theEntry.Name.IndexOf(".png", StringComparison.OrdinalIgnoreCase) != -1 || theEntry.Name.IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) != -1))
                        {
                            //解压文件到指定的目录   
                            using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
                            {
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size <= 0) break;

                                    streamWriter.Write(data, 0, size);
                                }
                                streamWriter.Close();
                            }
                            break;
                        }
                    }
                }
                s.Close();
            }
        }
        catch (Exception ex)
        {
            XLog.SaveLog(0, "解压uncau:" + ex.Message);
        }
    }

    public string unCompressRAR(string unRarPatch, string rarPatch, string rarName)

    {

        string the_rar;
        RegistryKey the_Reg;
        object the_Obj;
        string the_Info;
        try
        {
            the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
            the_Obj = the_Reg.GetValue("");
            the_rar = the_Obj.ToString();
            the_Reg.Close();
            if (Directory.Exists(unRarPatch) == false)
            {
                Directory.CreateDirectory(unRarPatch);
            }

            the_Info = "x " + rarName + " " + unRarPatch + " -y";
            ProcessStartInfo the_StartInfo = new ProcessStartInfo();
            the_StartInfo.FileName = the_rar;
            the_StartInfo.Arguments = the_Info;
            the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径
            Process the_Process = new Process();
            the_Process.StartInfo = the_StartInfo;
            the_Process.Start();
            the_Process.WaitForExit();
            the_Process.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return unRarPatch;

    }

    private void ShellCdrConvertPng(string path, string targPath)
    {
        ShellFile shellFile = ShellFile.FromFilePath(path);
        System.Drawing.Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;

        //在画板的指定位置画图
        targPath = targPath.Replace(".cdr", ".png");
        shellThumb.Save(targPath, ImageFormat.Png);
        shellThumb.Dispose();
        shellFile.Dispose();
    }

    private void CdrConvertPng(string path, string targPath)
    {
        using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Aspose.Imaging.Image.Load(path))
        {
            PngOptions options = new Aspose.Imaging.ImageOptions.PngOptions();

            options.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;

            // Set rasterization options for fileformat
            options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)
                image.GetDefaultOptions(new object[] { Aspose.Imaging.Color.White, image.Width, image.Height });
            options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            options.VectorRasterizationOptions.SmoothingMode = Aspose.Imaging.SmoothingMode.None;
            targPath = targPath.Replace(".cdr", ".png");
            image.Save(targPath, options);
            options.Dispose();
        }
    }
    private string CdrExPng(string path, string targPath)
    {
        try
        {
            targPath = targPath.Replace(".cdr", ".png");
            Application cdr = new Application();
            cdr.OpenDocument(path, 1);
            cdr.ActiveDocument.ExportBitmap(
            targPath,
            cdrFilter.cdrPNG,
            cdrExportRange.cdrCurrentPage,
            cdrImageType.cdrRGBColorImage,
            0, 0, 72, 72,
            cdrAntiAliasingType.cdrNoAntiAliasing,
            false,
            true,
            true,
            false,
            cdrCompressionType.cdrCompressionNone,
            null).Finish();
            cdr.ActiveDocument.Close();
            cdr.Quit();
            cdr = null;
            GC.Collect();
        }
        catch (Exception ex)
        {
            XLog.SaveLog(0, path + ",转成图片出错：" + ex.Message);
        }
        finally
        {

        }
        return "111";
    }

    private static object cdrpngobj = new object();
    private void CdrExportPng(string path, string cdrFile)
    {
        lock (cdrpngobj)
        {
            string fname = curPath + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png";
            string new_fname = path + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png";
            CorelDRAW.Application cdr = new CorelDRAW.Application();
            cdr.OpenDocument(cdrFile, 1);
            cdr.ActiveDocument.ExportBitmap(
                fname,
                CorelDRAW.cdrFilter.cdrPNG,
                CorelDRAW.cdrExportRange.cdrCurrentPage,
                CorelDRAW.cdrImageType.cdrRGBColorImage,
                0, 0, 72, 72,
                CorelDRAW.cdrAntiAliasingType.cdrNoAntiAliasing,
                false,
                true,
                true,
                false,
                CorelDRAW.cdrCompressionType.cdrCompressionNone,
                null).Finish();
            cdr.ActiveDocument.Close();
            cdr.Quit();

            if (File.Exists(fname))
            {
                File.Copy(fname, new_fname);
                File.Delete(fname);
            }
        }
    }


    public static string MidStrEx(string sourse, string startstr, string endstr)
    {
        string result = string.Empty;
        int startindex, endindex;
        try
        {
            startindex = sourse.IndexOf(startstr);
            if (startindex == -1)
                return result;
            string tmpstr = sourse.Substring(startindex + startstr.Length);
            endindex = tmpstr.IndexOf(endstr);
            if (endindex == -1)
                return result;
            result = tmpstr.Remove(endindex);
        }
        catch (Exception ex)
        {
            Console.WriteLine("MidStrEx Err:" + ex.Message);
        }
        return result;
    }

    private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
    private static object logFlag = new object();
    public static void writeLog(string log)
    {
        lock (logFlag)
        {
            using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
                {
                    sw.Write(log + " ------时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                    sw.Flush();
                }
            }
        }
    }
}