using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class simdownload : System.Web.UI.Page
{
    public static string dPath = ConfigurationManager.AppSettings["dPath"];
    public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
    private void conErc(string msg)
    {
        Response.Write("{\"type\":\"error\",\"result\":\"" + 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 (Request["hexdata"] != null)
        {
            string tids = Request["hexdata"];
            string fpId = Request["hexdata"];
            if (tids.Trim() == "")
            {
                conErc("无法下载");
                return;
            }
            try
            {
                string[] tArr = tids.Split(',');
                List<string> tLst = new List<string>();
                foreach (string id in tArr)
                {
                    tLst.Add("'" + id + "'");
                }
                tids = string.Join(",", tLst.ToArray());
                StringBuilder sql = new StringBuilder();
                string ut = Request["ut"];
                if (ut == "fp")
                {
                    sql.AppendFormat("select tid,img from ce_erpbill where id=" + fpId );
                }
                DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
                if (dt == null || dt.Rows.Count < 1)
                {
                    conErc("没有找到相关附件");
                    return;
                }
                List<string> files = new List<string>();
                string dTime = "";
                string fname = "";
                int fc = 0;
                foreach (DataRow dr in dt.Rows)
                {

                    if (dr["img"].ToString() != "")
                    {
                        if(!File.Exists(dPath + "\\" + ut + "\\" + dr["img"].ToString()))
                        {
                            conErc("找不到文件："+ dr["img"].ToString());
                            return;
                        }
                        files.Add(dPath + "\\" + ut + "\\" + dr["img"].ToString());
                    }
                }
                if (files.Count < 1)
                {
                    conErc("没有找到相关附件");
                    return;
                }
                if(files.Count==1)downLoadFile(files[0]);
                else
                {
                    ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
                }
                return;
            }
            catch (Exception ex)
            {
                conErc("错误的下载访问" + tids + "," + 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);
    }

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

    private string getDesignDate(object v)
    {
        return DateTime.Now.ToString("yyyy-MM-dd");
        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(List<string> files, string zipFileName)
    {
        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();
        Page.Response.SuppressContent = true;
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
        //Response.Flush();
        //Response.End();
    }

    private void downLoadFile(string 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.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bytes);
        //Response.Flush();
        Response.End();
    }
}
