using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using MSharp.Framework;
using SQLData;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class autocopy : 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();
    }

    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(',');
                if (tArr.Length != 2)
                {
                    conErc("订单ID不对，无法下载");
                    return;
                }
                string oldctid = tArr[0].ToString();
                string newctid = tArr[1].ToString();

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName from view_erptradecell where ctid='{0}'", oldctid);
                DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
                if (dt == null || dt.Rows.Count < 1)
                {
                    conErc("没有找到相关订单" + oldctid);
                    return;
                }
                StringBuilder sqlnew = new StringBuilder();
                sqlnew.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName,orderSn,payment,ProductId from view_erptradecell where (orderstate=3 or orderstate=4) and ctid='{0}'", newctid);
                DataTable dtnew = CeErpTradeCell.ExecuteDataset(sqlnew.ToString()).Tables[0];
                if (dtnew == null || dtnew.Rows.Count < 1)
                {
                    conErc("没有找到相关new新订单" + newctid);
                    return;
                }
                List<string> files = new List<string>();
                string oldDesignTime = "";
                string oldFilename = "";

                string df_name = "";
                string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
                string oldTag = ".cdr";
                List<string> noFileLst = new List<string>();
                List<string> errorFileLst = new List<string>();
                DataRow dr = dt.Rows[0];

                if (dr["FinishDesignTime"].ToString() == "")
                {
                    conErc("没有找到相关old老订单附件,FinishDesignTime为空");
                    return;
                }
                DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
                DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
                if (ftime.CompareTo(splitTime) > 0)
                {
                    oldDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);
                }
                else
                    oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
                //oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
                df_name = upPath + "\\" + oldDesignTime + "\\" + formatMemo(dr["seller_memo"]);
                foreach (string ext in extArr)
                {
                    oldFilename = df_name + ext;
                    oldTag = ext;
                    if (File.Exists(oldFilename))
                    {
                        break;
                        //if (!isUpdateError)
                        //{
                        //    files.Add(fname);
                        //    copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
                        //    fc++;
                        //}
                    }
                    else
                        oldFilename = "";

                }
                if (oldFilename == "")
                {
                    conErc("没有找到相关old老订单附件");
                    return;
                    //noFileLst.Add("'" + dr["ctid"].ToString() + "'");

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



                //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());
                DataRow newDr = dtnew.Rows[0];
                string newMemo = newDr["seller_memo"].ToString();
                newMemo = newMemo.Replace("（", "(");
                newMemo = newMemo.Replace("）", ")");
                string newmemoctid = MidStrEx(newMemo, "(", ")").Trim();
                string orderSn = newDr["orderSn"].ToString();
                if (newctid.IndexOf("C") != -1)
                {
                    /*if (newMemo.IndexOf("[") != -1 && newMemo.IndexOf("C") != -1)
                    {
                        if (newmemoctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1]   对应ctid是 S_S_C1_1962772776865084101
                        {
                            int lastIndex = newmemoctid.LastIndexOf("S_"); //最后一个S_的位置
                            string sPre = newmemoctid.Substring(0, lastIndex + 2); //S_S_
                            string initTid = newmemoctid.Substring(lastIndex + 2, newmemoctid.Length - lastIndex - 2); //1962772776865084101

                            string pre_ctid = MidStrEx(newMemo, "[", "]"); //C1
                            if (pre_ctid.IndexOf("+") != -1)
                            {
                                pre_ctid = "C" + pre_ctid.Split('+')[1];
                            }
                            newmemoctid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
                        }
                        else
                        {
                            string pre_ctid = MidStrEx(newMemo, "[", "]");
                            if (pre_ctid.IndexOf("+") != -1)
                            {
                                pre_ctid = "C" + pre_ctid.Split('+')[1];
                            }
                            if (newmemoctid.IndexOf('C') == -1)
                            {
                                newmemoctid = pre_ctid + "_" + newmemoctid;
                            }
                        }

                    }*/
                }
                if (string.IsNullOrEmpty(newmemoctid))
                {
                    conErc("上传的文件名格式不正确");
                    return;
                }
                if (orderSn != newmemoctid)
                {
                    conErc("新订单备注中的订单号不正确");
                    return;
                }
                string newUpDesignTime = getDesignTimeWithDay(DateTime.Now);
                //string newDfName = upPath + "\\" + newUpDesignTime + "\\" + formatMemo(newDr["seller_memo"])+oldTag;
                string newPathFileName = "";
                copyUpFile(newUpDesignTime, oldFilename, formatMemo(newDr["seller_memo"]) + oldTag, ref newPathFileName);
                //copyFile(getDesignDate(DateTime.Now), dr["SupplierName"].ToString(), oldFilename, formatMemo(newDr["seller_memo"]) + oldTag);

                CeErpTradeCell.UpdateRelationOrder(newctid);
                StringBuilder up_sql = new StringBuilder();
                up_sql.AppendFormat("update ce_erptradecell with(rowlock) set orderstate=5,IsReturn=0,StartDesignTime=getdate(),SupplierId={1},FinishDesignTime=getdate() where ctid='{0}'", newctid, dr["SupplierId"]);
                CeErpTradeCell.ExecuteNonQuery(up_sql.ToString());
                if (oldTag == ".cdr")
                {
                    //string sqlpng = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", newPathFileName);
                    //CeErpTradeLog.ExecuteNonQuery(sqlpng);
                }
                if (!Convert.IsDBNull(newDr["ProductId"]))
                {
                    CeErpProduct product = CeErpProduct.GetById(Convert.ToInt32(newDr["ProductId"]));
                    if (product != null)
                    {
                        string param = "[{ \"product_type\": \"" + product.PType + "\",\"remark\": \"" + newDr["seller_memo"] + "\",\"index\": \"" + orderSn + "\",\"orderid\": \"" + newDr["ctid"] + "\",\"price\": \"" + newDr["payment"] + "\"}]";
                        sysHttpClient(param);
                    }
                }
                CeErpTradeLog.AddLog(newctid, 5, userId, "自动上传老客户文件-" + newPathFileName);
                string fileSql = string.Format("INSERT INTO [dbo].[CE_ErpTradeCellFile]([tid], [ctid], [isDel], [url], [createtime], [type]) SELECT '{0}', '{1}', isDel ,url,getdate(),type FROM [dbo].[CE_ErpTradeCellFile] WHERE tid='{2}' and ctid='{3}' and isDel = 0 and type = 'AUTH_FILE'", dtnew.Rows[0]["tid"], dtnew.Rows[0]["tid"], dt.Rows[0]["tid"], dt.Rows[0]["tid"]);
                CeErpTradeCell.ExecuteNonQuery(fileSql);
                conSuc("文件已上传到共享目录");
                return;
            }
            catch (Exception ex)
            {
                conErc("错误的下载访问" + ex.Message);
                XLog.SaveLog(0, "autocopydown," + ex.Message);
                return;
            }
        }
    }


    public void sysHttpClient(string param)
    {
        Task.Run(async () =>
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://47.122.57.102:11004/quotations/batch"),
                Content = new StringContent(param)
                {
                    Headers =
                    {
                        ContentType = new MediaTypeHeaderValue("application/json")
                    }
                }
            };
            var task = Task.Run(() =>
            {
                try
                {
                    var response = client.SendAsync(request).Result;
                    response.EnsureSuccessStatusCode();
                    writeLog(param + "-" + response.Content.ReadAsStringAsync().Result);
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception e)
                {
                    return "";
                }


            });
        });
    }

    public static string MidStrEx(string sourse, string startstr, string endstr)
    {
        string result = string.Empty;
        int startindex, endindex;
        try
        {
            startindex = sourse.IndexOf(startstr);
            if (startindex == -1)
                return result;
            string tmpstr = sourse.Substring(startindex + startstr.Length);
            endindex = tmpstr.IndexOf(endstr);
            if (endindex == -1)
                return result;
            result = tmpstr.Remove(endindex);
        }
        catch (Exception ex)
        {
            Console.WriteLine("MidStrEx Err:" + ex.Message);
        }
        return result;
    }
    private string formatMemo(object memo)
    {
        string m = memo.ToString();
        m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
        return m;
    }

    private void copyUpFile(string date, string oldfile, string newfilename, ref string newPathFileName)
    {
        try
        {
            string path = upPath + "\\" + date;
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            //string fname = Path.GetFileName(file);
            File.Copy(oldfile, path + "\\" + newfilename, true);
            newPathFileName = path + "\\" + newfilename;
            if (!File.Exists(path + "\\" + newfilename))
            {
                File.Copy(oldfile, path + "\\" + newfilename, true);
            }
        }
        catch (Exception ex)
        {
            XLog.SaveLog(0, "自动复制上传文件发生错误," + newfilename + "," + ex.Message);
            throw ex;
        }

    }

    private void copyFile(string date, string supplier, string oldfile, string newFileName)
    {
        try
        {
            string path = copyPath + "\\" + date + "\\" + supplier;
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            //string fname = Path.GetFileName(file);
            File.Copy(oldfile, path + "\\" + newFileName, true);
            if (!File.Exists(path + "\\" + newFileName))
            {
                File.Copy(oldfile, path + "\\" + newFileName, true);
            }
        }
        catch (Exception ex)
        {
            XLog.SaveLog(0, "自动复制下载文件发生错误," + oldfile + "," + ex.Message);
        }

    }

    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)
    {
        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 = 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();
    }


    private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
    private static object logFlag = new object();
    public static void writeLog(string log)
    {
        lock (logFlag)
        {
            using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
                {
                    sw.Write(log + " ------时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                    sw.Flush();
                }
            }
        }
    }
}

