using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using NPOI.OpenXmlFormats.Shared;
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;

public partial class download : 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"];

    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;
            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 fname;
            }
        }

        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;//转移到客户端下载

        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 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>();
            foreach (DataRow dr in dt.Rows)
            {
                string finishDesignTime = "";
                DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
                DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
                if (ftime.CompareTo(splitTime) > 0)
                {
                    finishDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
                }
                else
                {
                    finishDesignTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
                }
                string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
                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);
            }
            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("yyyyMM");
    }
    private string getDesignTimeWithDay(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)
    {
        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]);
        }
    }

    //public static object downfileObj = new object();
    private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
    {
        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);


    }


}