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

public partial class copydownload : System.Web.UI.Page
{
    public static string upPath = ConfigurationManager.AppSettings["upPath"];
    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();
    }

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

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["hexdata"] != null)
        {

            string tids = Request["hexdata"];
            if (tids.Trim() == "")
            {
                conErc("无法下载");
                return;
            }
            int userId = 0;
            if (Request["userid"] != null)
            {
                userId = Convert.ToInt32(Request["userid"]);
            }
            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();
                sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid,SupplierId from view_erptradecell where orderstate=5 and ctid in ({0})", tids);
                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;
                bool hasFile = false;
                string df_name = "";
                string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
                List<string> noFileLst = new List<string>();
                List<string> errorFileLst = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["FinishDesignTime"].ToString() == "") continue;
                    hasFile = false;
                    DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
                    DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
                    if (ftime.CompareTo(splitTime) > 0)
                    {
                        dTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
                    }
                    else
                    {

                        dTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
                    }
                    string tid = dr["tid"].ToString();
                    string orderSn = dr["OrderSn"].ToString();
                    string rname = "";
                    df_name = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]);
                    foreach (string ext in extArr)
                    {
                        fname = df_name + ext;
                        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;
                        }
                        if (!hasFile)
                        {
                            if (File.Exists(fname))
                            {
                                bool isCopyError = false;
                                double payment = 0;
                                string ctid = dr["ctid"].ToString();
                                CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
                                try
                                {
                                    if (entity != null)
                                    {
                                        payment = entity.payment;
                                    }
                                    hasFile = true;
                                    files.Add(fname);
                                    copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, payment, rname);
                                    fc++;
                                }
                                catch (Exception ex)
                                {
                                    isCopyError = true;
                                    errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
                                    XLog.SaveLog(0, "复制文件发生错误," + fname + "," + ex.Message);
                                }
                                //复制完成后修改数据
                                if (!isCopyError)
                                {
                                    try
                                    {

                                        if (entity != null)
                                        {
                                            //update ce_erptradecell WITH(ROWLOCK) set FinishPlaceTime = getdate(), OrderState = 6, IsReturn = 0, PlaceUserId = @userid where CHARINDEX(',' + ctid + ',',',' + @mainctids + ',')> 0 and orderstate = 5 and isDianziOrder = 0
                                            //insert into CE_ErpTradeLog(tid, orderstate, userid, operatetime, con) select ctid,6,@userid,getdate(),'下载设计文件' from ce_erptradecell where CHARINDEX(',' + ctid + ',', ',' + @mainctids + ',') > 0
                                            entity.FinishPlaceTime = DateTime.Now;
                                            entity.OrderState = 6;
                                            entity.IsReturn = 0;
                                            entity.PlaceUserId = userId;
                                            entity.Update();

                                            CeErpTradeLog logenty = new CeErpTradeLog();
                                            logenty.tid = ctid;
                                            logenty.OrderState = 6;
                                            logenty.UserId = userId;
                                            logenty.OperateTime = DateTime.Now;
                                            logenty.Con = "下载设计文件";
                                            logenty.Create();

                                            CeErpDataSendOrderInfo.createObject(entity.ctid);
                                        }

                                        SqlParameter[] sqlParameter ={
                                    new SqlParameter("@mainctids", SqlDbType.VarChar,500),
                                    new SqlParameter("@userid", SqlDbType.VarChar,4),
                                    new SqlParameter("@res", SqlDbType.VarChar, 4000)
                                    };
                                        sqlParameter[0].Value = dr["ctid"].ToString();
                                        sqlParameter[1].Value = userId;
                                        sqlParameter[2].Direction = ParameterDirection.Output;
                                        CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
                                    }
                                    catch (Exception ex)
                                    {
                                        errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
                                        XLog.SaveLog(0, "下载发生错误,ctid:" + dr["ctid"].ToString() + "," + ex.Message);
                                    }
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (!hasFile)
                    {
                        noFileLst.Add("'" + dr["ctid"].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='{0}' ;", dr["ctid"], (int)OrderState.下单完成, 0, "找不到设计文件");
                        //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
                        //conErc("找不到文件,订单号：" + dr["ctid"]);
                        //return;
                    }
                    //if (hasFile)
                    //{
                    //    fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
                    //    if (File.Exists(fname))
                    //    {
                    //        files.Add(fname);
                    //        copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
                    //    }
                    //}

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

                //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, (int)OrderState.下单完成, userId, "下载设计文件");
                //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
                //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);

                //CeErpTradeCell.ExecuteNonQuery(sql.ToString());

                foreach (string ctid in tArr)
                {
                    CeErpTradeCell.UpdateRelationOrder(ctid);
                }

                if (Request["supplier"] != null && Request["supplier"].ToString() == "1")
                {
                    ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
                }
                else if (noFileLst.Count > 0 || errorFileLst.Count > 0)
                {
                    string tips = "";
                    if (noFileLst.Count > 0)
                    {
                        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;
                    }
                    if (errorFileLst.Count > 0)
                    {
                        string ertids = string.Join(",", errorFileLst.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}) ;", ertids, (int)OrderState.下单完成, 0, "下载设计文件出错");
                        CeErpTradeCell.ExecuteNonQuery(sql.ToString());
                        tips += " 复制下载出错,单号：" + ertids;
                    }
                    conErc(tips);
                }
                else
                {
                    conSuc("文件已下载到共享目录");
                }

                return;
            }
            catch (Exception ex)
            {
                conErc("复制错误的下载访问");
                XLog.SaveLog(0, "copydown" + ex.Message);
                return;
            }
        }
    }


    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, double payment, string rname)
    {

        string SupName = supplier;
        if (payment >= 500)
        {
            SupName = supplier + "500";
        }
        string path = copyPath + "\\" + date + "\\" + SupName;
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        string fname = Path.GetFileName(file);
        foreach (var rule in replaceRules)
        {
            rname = rname.Replace(rule.Key, rule.Value);
        }

        File.Copy(file, path + "\\" + rname, true);
        if (!File.Exists(path + "\\" + rname))
        {
            File.Copy(file, path + "\\" + rname, 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(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 = Server.MapPath("d/" + 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(file, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
}

