using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using NPOI.OpenXmlFormats.Dml.Diagram;
using NPOI.OpenXmlFormats.Shared;
using SiteCore.Handler;
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;

public partial class supplierDownload : System.Web.UI.Page
{
    public static string upPath = ConfigurationManager.AppSettings["upPath"];
    public static string copyPath = ConfigurationManager.AppSettings["copyPath"];

    public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
    [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
    public static extern uint DecFile(string filename);

    [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
    public static extern int IsFileEncrypted(string filename);//返回1为加密，0为未被加密
    [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
    public static extern void CreateUserKey(StringBuilder key, int len);
    [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
    public static extern int InitAesKey(StringBuilder key, int len);

    [DllImport("DrvInterface64.dll")]
    public static extern int IsInitedAesKey();

    private void conErc(string msg)
    {
        XLog.SaveLog(0, msg);
        Response.Write(msg);
        //Response.StatusCode = (int)HttpStatusCode.NotFound;
        //Response.End();
    }

    private void conSuc(string msg)
    {
        Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
        //Response.End();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            Response.Buffer = true;
            downloadMore();
        }
    }

    private string getCanDownFile(string fileName)
    {
        string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
        foreach (string ext in extArr)
        {
            string fname = fileName + ext;
            if (File.Exists(fname))
            {
                return ext;
            }
        }

        return "";
    }

    private void updateIsDownSuccess(int userId, string ctid)
    {
        try
        {
            SqlParameter[] sqlParameter ={
                                    new SqlParameter("@mainctids", SqlDbType.VarChar,500),
                                    new SqlParameter("@userid", SqlDbType.VarChar,4),
                                    new SqlParameter("@res", SqlDbType.VarChar, 4000)
                                    };
            sqlParameter[0].Value = ctid;
            sqlParameter[1].Value = userId;
            sqlParameter[2].Direction = ParameterDirection.Output;
            CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);

            CeErpTradeCell.UpdateRelationOrder(ctid);
        }
        catch (Exception ex)
        {
            //errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
            XLog.SaveLog(0, "下载发生错误,ctid:" + ctid + "," + ex.Message);
        }
    }


    private void downloadMore()
    {
        if (Request["hexdata"] == null || Request["hexdata"].Trim() == "")
        {
            conErc("错误的下载访问");
            return;
        }

        string tids = Request["hexdata"];
        int onlyDownFile = 0;//只下文件
        if (Request["onlyfile"] != null)
        {
            Int32.TryParse(Request["onlyfile"], out onlyDownFile);
        }


        int userId = 0;
        if (Request["userid"] != null)
        {
            Int32.TryParse(Request["userid"], out userId);
        }

        int mvClientDown = 0;//转移到客户端下载
        string ctids = "";
        int isFromClient = 0;
        if (onlyDownFile != 1)
        {
            if (Request["supplier"] == null || Request["supplier"].ToString() != "1")//如果不是只下文件，那他就要是供应商
            {
                conErc("错误的下载访问");
                return;
            }
            else
            {
                /* Int32.TryParse(Request["isFromClient"], out isFromClient);

                 if (userId > 0 && isFromClient != 1)
                 {
                     string file_client_down_flg = erpRedis.RedisHelper.StringGet("file_client_down_flg_" + userId);
                     if (file_client_down_flg != null && file_client_down_flg == "1")
                     {
                         mvClientDown = 1;
                     }
                 }*/

            }
        }
        try
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,OrderSn,tid,SupplierId from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1 || isFromClient == 1) ? "" : " and OrderState=5 "));
            DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
            if (dt == null || dt.Rows.Count < 1)
            {
                conErc("没有找到相关订单");
                return;
            }
            string fileMd5 = "", fileNames = "";
            List<string> files = new List<string>();
            List<string> noFileLst = new List<string>();
            List<string> ctidLst = new List<string>();
            List<string> rnameList = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string finishDesignTime = getDesignTime(dr["FinishDesignTime"]);
                string ctid = dr["ctid"].ToString();
                string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
                string ext = getCanDownFile(df_name);
                string fname = df_name + ext;
                string tid = dr["tid"].ToString();
                string orderSn = dr["OrderSn"].ToString();
                string rname = formatMemo(dr["seller_memo"]) + ext;
                if ("14".Equals(dr["SupplierId"].ToString()))
                {
                    rname = dealMemoName(rname);
                }
                if ("138".Equals(dr["SupplierId"].ToString()))
                {
                    rname = formatMemo(dr["seller_memo"]) + string.Format("《{0}》", dr["ctid"]) + ext;
                }
                int IsFileEncrypt = IsFileEncrypted(fname);
                if (IsFileEncrypt == 1 && File.Exists(fname))
                {
                    string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
                    var sb = new StringBuilder(key);

                    //Linux系统的接口要调用一次，Windows系统要调用两次
                    CreateUserKey(sb, key.Length);
                    CreateUserKey(sb, key.Length); //破解用dse生成的文件，需要调2次。
                    int result = InitAesKey(sb, sb.Length);
                    result = IsInitedAesKey();
                    if (result != 1)
                    {
                        addLog(ctid, userId, "初始化秘钥失败" + result, 0);
                        noFileLst.Add("'" + ctid + "'");
                        continue;
                    }
                    uint a = DecFile(fname);
                    if (a != 0)
                    {
                        addLog(ctid, userId, "解密失败" + a, 0);
                        noFileLst.Add("'" + ctid + "'");
                        continue;
                    }
                }
                if (string.IsNullOrEmpty(fname))
                {
                    noFileLst.Add("'" + ctid + "'");
                    continue;
                }

                files.Add(fname);
                ctidLst.Add(ctid);

                rnameList.Add(rname);
                fileMd5 += "," + dr["FileMd5"].ToString();
                fileNames += "#$#" + Path.GetFileName(fname);

                if (onlyDownFile != 1 && mvClientDown != 1)
                {
                    copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, rname);
                }
            }

            if (files.Count == 0)
            {
                conErc("没有找到相关的设计附件");
                return;
            }

            /*if (noFileLst.Count > 0)
            {
                string tips = "";
                string notids = string.Join(",", noFileLst.ToArray());
                sql = new StringBuilder();
                sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", notids, (int)OrderState.下单完成, 0, "找不到设计文件");
                CeErpTradeCell.ExecuteNonQuery(sql.ToString());
                tips += "找不到文件,单号:" + notids;

                conErc(tips);
                return;
            }*/

            if (mvClientDown == 1)
            {
                for (int i = 0; i < files.Count; i++)
                {
                    if (onlyDownFile != 1)
                        updateIsDownSuccess(userId, ctidLst[i]);
                }

                string key = "file_client_down_list_" + userId;
                string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
                    + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
                erpRedis.RedisHelper.ListLeftPush(key, data);
                return;
            }


            if (ctidLst.Count > 0)
            {
                ctids = string.Join(",", ctidLst);
                if (!string.IsNullOrEmpty(ctids))
                {
                    CeErpTradeCell.ExecuteNonQuery(string.Format("update CE_ErpTradeCell set IsHaveNewOrder = 2 where ctid in ({0}) ;", ("'" + ctids.Replace(",", "','") + "'")));
                }
            }
            if (files.Count == 1)
            {
                downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient, rnameList[0]);
            }
            else
            {
                ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient, rnameList); //downLoadFile(userId, ctidLst[i], files[i]);
            }

            //conSuc("文件已下载完成");
            return;
        }
        catch (Exception ex)
        {
            conErc("错误的下载访问" + ex.Message);
            XLog.SaveLog(0, "supplierDownload download" + ex.Message);

            return;
        }
    }
    private string dealMemoName(string name)
    {
        string[] al = name.Split('-');
        List<string> list = new List<string>();
        string pa = string.Empty;
        for (int i = 0; i < al.Length; i++)
        {
            if (i == 1)
            {
                if (al[i].Contains("(") || al[i].Contains("（"))
                {
                    string tname = al[i].Replace(")", "").Replace("）", "").Replace("（", "").Replace("(", "");
                    if (!string.IsNullOrEmpty(tname))
                    {
                        pa = al[i];
                    }
                    continue;
                }

            }
            list.Add(al[i]);
        }
        if (!string.IsNullOrEmpty(pa))
        {
            list.Insert(3, pa);
        }
        name = string.Join("-", list);
        return name;
    }

    private string formatMemo(object memo)
    {
        string m = memo.ToString();
        m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
        return m;
    }
    Dictionary<string, string> replaceRules = new Dictionary<string, string>
        {
            { "皙贝", "白卡" },
            { "睿狐", "莱尼" },
            { "岚蝶", "安格" },
            { "琮纹", "刚古" },
            { "珠光", "珠光" },
            { "溪雪", "珠光" },
            { "雅柔", "雅柔" },
            { "萱姿", "雅柔" },
            { "草香", "草香" },
            { "芳怡", "草香" },
            { "金绒", "牛皮" },
            { "素芸", "棉卡" },
            { "玉蕊", "蛋壳" }
        };
    private void copyFile(string date, string supplier, string file, string rname)
    {
        string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        string fname = Path.GetFileName(file);
        foreach (var rule in replaceRules)
        {
            fname = fname.Replace(rule.Key, rule.Value);
        }

        File.Copy(file, path + "\\" + fname, true);
        if (!File.Exists(path + "\\" + fname))
        {
            File.Copy(file, path + "\\" + fname, true);
        }
    }

    private string getDesignTime(object v)
    {
        if (v.ToString() == "") return "";
        return Convert.ToDateTime(v).ToString("yyyyMMdd");
    }

    private string getDesignDate(object v)
    {
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;
        return year + "\\" + month + "\\" + day;
    }

    ///  批量进行多个文件压缩到一个文件
    /// </summary>
    /// <param name="files">文件列表(绝对路径)</param> 这里用的数组，你可以用list 等或者
    /// <param name="zipFileName">生成的zip文件名称</param>
    private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient, List<string> rnameList)
    {
        MemoryStream ms = new MemoryStream();
        byte[] buffer = null;
        List<string> addFiles = new List<string>();
        List<string> addCtid = new List<string>();

        using (ZipFile file = ZipFile.Create(ms))
        {

            file.BeginUpdate();
            //file.NameTransform = new ZipNameTransform();
            file.NameTransform = new MyNameTransfom();
            for (int i = 0; i < ctidLst.Count; i++)
            {
                if (File.Exists(files[i]))
                {
                    try
                    {
                        foreach (var rule in replaceRules)
                        {
                            rnameList[i] = rnameList[i].Replace(rule.Key, rule.Value);
                        }
                        file.Add(files[i], rnameList[i]);
                        addFiles.Add(files[i]);
                        addCtid.Add(ctidLst[i]);
                    }
                    catch (Exception ex)
                    {
                        XLog.SaveLog(0, "supplierdownload_ZipFileDownload:" + ex.Message);
                    }
                }
            }

            file.CommitUpdate();
            buffer = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(buffer, 0, buffer.Length);   //读取文件内容(1次读ms.Length/1024M)
            ms.Flush();
            ms.Close();

        }
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
        Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
        Page.Response.Flush();

        //for (int i = 0; i < addFiles.Count; i++)
        //{
        //    updateIsDownSuccess(userId, addCtid[i]);
        //}
        //sql = new StringBuilder();
        //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
        //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
    }

    //public static object downfileObj = new object();
    private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient, string fname)
    {
        string filePath = file;
        string dfile = Path.GetFileName(file);
        foreach (var rule in replaceRules)
        {
            fname = fname.Replace(rule.Key, rule.Value);
        }
        FileStream fs = new FileStream(filePath, FileMode.Open);
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();


        Response.Clear();
        //
        Response.ClearContent();
        Response.ClearHeaders();

        Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
        Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
        //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.UTF8));
        Response.AddHeader("Content-Length", bytes.Length.ToString());
        Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
        Response.BinaryWrite(bytes);
        Response.Flush();

        //updateIsDownSuccess(userId, ctid);
        //StringBuilder sql = new StringBuilder();
        //string tids = string.Join(",", ctid);
        //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
        //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
        //sql = new StringBuilder();
        //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
        //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
    }

    public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
    {
        CeErpTradeLog log = new CeErpTradeLog();
        log.tid = ctid;
        log.UserId = userid;
        log.Con = con;
        log.OrderState = orderState;
        log.AfterSaleState = aftersaleState;
        log.OperateTime = DateTime.Now;
        log.Create();
    }
}