using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json.Linq;
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Security;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Security.Cryptography.X509Certificates;
using Utils;
using System.Runtime.InteropServices;
using NPOI.OpenXmlFormats.Shared;

public partial class caiyingtongload : 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)
    {
        if (msg.IndexOf("访问远程主机") == -1)
        {
            XLog.SaveLog(0, msg);
        }
        Response.Write(msg);
        //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;
            downloadcayingtonge();
        }
    }

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

        return "";
    }

    private void updateIsDownSuccess(int userId, string ctid)
    {
        try
        {
            XLog.SaveLog(0, "updateIsDownSuccess ,ctid:" + ctid);

            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 downloadcayingtonge()
    {
        string tids = Request["hexdata"];
        int onlyDownFile = 0;//只下文件
        if (Request["onlyfile"] != null)
        {
            Int32.TryParse(Request["onlyfile"], out onlyDownFile);
        }
        int cyt = 0;
        if (Request["cyt"] != null)
        {
            Int32.TryParse(Request["cyt"], out cyt);
        }
        int userId = 0;
        if (Request["userid"] != null)
        {
            Int32.TryParse(Request["userid"], out userId);
        }
        String ui = "";
        if (cyt == 1)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,IsSF from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1) ? "" : " and OrderState=5 "));

            DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
            if (dt == null || dt.Rows.Count < 1)
            {
                conErc("没有找到相关订单");
                return;
            }
            List<string> files = new List<string>();
            List<string> noFileLst = new List<string>();
            List<string> ctidLst = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string fileMd5 = "", fileNames = "";
                String seller_memo = "";
                int ISSF = 0;
                string finishDesignTime = getDesignTime(dr["FinishDesignTime"]);

                string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);

                if (!Convert.IsDBNull(dr["seller_memo"]))
                {
                    seller_memo = dr["seller_memo"].ToString();
                }
                if (!Convert.IsDBNull(dr["IsSF"]))
                {
                    ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
                }
                string fname = getCanDownFile(df_name);
                if (string.IsNullOrEmpty(fname))
                {
                    noFileLst.Add("'" + dr["ctid"].ToString() + "'");
                    ui += dr["ctid"].ToString() + "未找到附件，";
                    continue;
                }

                files.Add(fname);
                ctidLst.Add(dr["ctid"].ToString());

                fileMd5 += "," + dr["FileMd5"].ToString();
                fileNames += Path.GetFileName(fname);


                String er = downLoadFiles(userId, dr["ctid"].ToString(), fname, fileNames, seller_memo, ISSF);
                if (er.Contains("成功"))
                {
                    copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
                }
                ui += er + ",";

            }
            conSuc(ui);
        }
        else
        {
            conSuc(ui);
        }

    }



    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 cyt = 0;
        if (Request["cyt"] != null)
        {
            Int32.TryParse(Request["cyt"], out cyt);
        }

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

        int mvClientDown = 0;//转移到客户端下载

        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,IsSF 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 = "";
            String seller_memo = "";
            int ISSF = 0;
            List<string> files = new List<string>();
            List<string> noFileLst = new List<string>();
            List<string> ctidLst = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string finishDesignTime = getDesignDate(dr["FinishDesignTime"]);

                string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);

                if (!Convert.IsDBNull(dr["seller_memo"]))
                {
                    seller_memo = dr["seller_memo"].ToString();
                }
                if (!Convert.IsDBNull(dr["IsSF"]))
                {
                    ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
                }
                string fname = getCanDownFile(df_name);
                if (string.IsNullOrEmpty(fname))
                {
                    noFileLst.Add("'" + dr["ctid"].ToString() + "'");
                    continue;
                }

                files.Add(fname);
                ctidLst.Add(dr["ctid"].ToString());

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

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

            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 (files.Count == 1)
            {
                downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient);
                if (cyt == 1)
                {
                    downLoadFiles(userId, ctidLst[0], files[0], fileNames, seller_memo, ISSF);
                }
            }
            else
            {
                ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient); //downLoadFile(userId, ctidLst[i], files[i]);
            }

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


            return;
        }
    }


    private string formatMemo(object memo)
    {
        string m = memo.ToString();
        m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
        return m;
    }

    private void copyFile(string date, string supplier, string file)
    {
        string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        string fname = Path.GetFileName(file);
        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;
        /*if (v.ToString() == "") return "";
        return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
    }

    ///  批量进行多个文件压缩到一个文件
    /// </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)
    {
        MemoryStream ms = new MemoryStream();
        byte[] buffer = null;

        using (ZipFile file = ZipFile.Create(ms))
        {
            file.BeginUpdate();
            //file.NameTransform = new ZipNameTransform();
            file.NameTransform = new MyNameTransfom();
            foreach (var item in files)
            {
                if (File.Exists(item)) file.Add(item);
            }
            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("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));

        Response.BinaryWrite(buffer);
        Page.Response.Flush();

        for (int i = 0; i < files.Count; i++)
        {
            if (onlyDownFile != 1 && isFromClient != 1)
                updateIsDownSuccess(userId, ctidLst[i]);
            XLog.SaveLog(userId, files[i] + " is success");
        }
    }

    //public static object downfileObj = new object();
    private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
    {
        XLog.SaveLog(userId, file);

        string filePath = file;
        string dfile = Path.GetFileName(file);

        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(dfile, System.Text.Encoding.UTF8));
        Response.AddHeader("Content-Length", bytes.Length.ToString());
        Response.BinaryWrite(bytes);
        Response.Flush();

        if (onlyDownFile != 1 && isFromClient != 1)
            updateIsDownSuccess(userId, ctid);

        XLog.SaveLog(userId, file + " is success");

    }



    private String downLoadFiles(int userId, string ctid, string file, String fileNames, String seller_memo, int ISSF)
    {
        int IsFileEncrypt = IsFileEncrypted(file);
        if (IsFileEncrypt == 1 && File.Exists(file))
        {
            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);
                return ctid + "调用失败";
            }
            uint a = DecFile(file);
            if (a != 0)
            {
                addLog(ctid, userId, "解密失败" + a, 0);
                return ctid + "调用失败";
            }
        }
        int Isshunfen = 2;
        int Isjifu = 1;
        if (ISSF > 0)
        {
            Isshunfen = 1;
        }
        if (ISSF == 2)
        {
            Isjifu = 0;
        }
        UpLoadFile uf = new UpLoadFile();
        string YEAR = DateTime.Now.Year.ToString();
        string MONTH = DateTime.Now.Month.ToString();
        string DAY = DateTime.Now.Day.ToString();
        string strid = Guid.NewGuid().ToString("N");
        string fileExtension = Path.GetExtension(fileNames);//文件格式
        string finalfilename = strid + Path.GetExtension(fileNames);// ".cdr";
        string onlinepathfilename = "Uploads/temp/" + YEAR + "-" + MONTH + "-" + DAY + "/" + finalfilename;
        uf.uploadFilName(file, onlinepathfilename);
        string output = fileExtension.Replace(".", "");  // 移除点（.）
        CeErpTradeCell ce = new CeErpTradeCell();
        ce = CeErpTradeCell.GetByCtid(ctid);
        if (ce.ReturnReason != "")//打回先取消
        {
            try
            {
                cancelOrder(ctid);
            }
            catch (Exception ex)
            {
                addLog(ctid, userId, "订单取消失败" + ex.ToString(), 0);
            }
        }

        if (ce.OrderState == 5)
        {
            JObject jsonObject = new JObject
                {
                    { "Userid", "77886" },
                    { "pwd", "lt666888" },
                    { "FileId", strid },
                    { "ext", output },
                    { "platformorder", ce.tid },//淘宝单号
                    { "Filename", fileNames },
                    { "Isshunfen", Isshunfen },
                    { "Isjifu", Isjifu },
                    { "LTOrderId", ce.ctid }
                };

            string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTInsertNewOrder", jsonObject.ToString());
            JObject jsonObjects = JObject.Parse(response);
            string msg = jsonObjects["msg"].ToString();
            if (msg == "插入订单成功")
            {
                string cytMalId = jsonObjects["Data"]["CytMallId"]["Data"].ToString();
                string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 0 + ",'" + msg + "');";
                CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
                addLog(ctid, userId, "上传彩印通接口成功：" + msg, ce.OrderState);
                if (ce != null)
                {
                    ce.FinishPlaceTime = DateTime.Now;
                    ce.OrderState = 6;
                    ce.IsReturn = 0;
                    ce.PlaceUserId = userId;
                    ce.SupplierOrderSn = cytMalId;
                    ce.Update();

                    CeErpTradeLog logenty = new CeErpTradeLog();
                    logenty.tid = ctid;
                    logenty.OrderState = 6;
                    logenty.UserId = userId;
                    logenty.OperateTime = DateTime.Now;
                    logenty.Con = "下载设计文件";
                    logenty.Create();
                }
                return ctid + "上传成功";
            }
            else
            {
                string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 1 + ",'" + msg + "');";
                CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
                addLog(ctid, userId, "上传彩印通接口失败：" + msg, ce.OrderState);
                XLog.SaveLog(userId, ctid + "订单下单接口调用失败！" + msg);
                return ctid + "调用失败";
            }
        }
        return ctid + "调用失败";
    }

    public static void cancelOrder(string ctid)
    {
        JObject jsonObject = new JObject
                {
                    { "Userid", "77886" },
                    { "pwd", "lt666888" },
                    { "LTOrderId", ctid }
                };
        string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTCancelOrder", jsonObject.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();
    }
    public static string HttpPost(string url, string param = null)
    {
        HttpWebRequest request;
        //如果是发送HTTPS请求  
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
        }
        else
        {
            request = WebRequest.Create(url) as HttpWebRequest;
        }

        request.Method = "POST";
        request.ContentType = "application/json";
        request.Accept = "*/*";
        request.Timeout = 120000;
        request.AllowAutoRedirect = false;



        StreamWriter requestStream = null;
        WebResponse response = null;
        string responseStr = null;

        try
        {
            requestStream = new StreamWriter(request.GetRequestStream());
            requestStream.Write(param);
            requestStream.Close();

            response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        finally
        {
            request = null;
            requestStream = null;
            response = null;
        }

        return responseStr;
    }


    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true; //总是接受  
    }
}