using AjaxControlToolkit.HtmlEditor.ToolbarButtons;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.PeerToPeer;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Utils.Serialization;


public partial class xhyOrderFile : 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)
    {
        XLog.SaveLog(0, msg);
        Response.Write(msg);
        //Response.StatusCode = (int)HttpStatusCode.NotFound;
        //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 ext;
            }
        }

        return "";
    }
    static bool running = false;
    static HttpClient client = new HttpClient();
    static string pUrl = "http://test.new-only.com:54444/shopPlat/front/needlogin/erp/orderFile.do";
    static string pCheckUrl = "http://test.new-only.com:54444/shopPlat/front/needlogin/erp/checkOrderParam.do";
    static string userName = "18959023975";
    static string passWord = "lt50510";

    private static string tempUpPath = ConfigurationManager.AppSettings["curPath"] + "\\tempUp";
    private void downloadMore()
    {
        if (running)
        {
            conSuc("运行中！");
            return;
        }
        running = true;

        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        Task.Run(async () =>
        {
            using (identity.Impersonate())
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select * from CE_ErpXhyOrderInfo WITH(nolock) where type = 0");
                int userId = 1;
                DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
                string updateSql = "";
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string json = dr["json"].ToString();
                        string ctid = dr["ctid"].ToString();
                        string post_url = dr["url"].ToString();
                        string id = dr["id"].ToString();
                        string filePath = "";
                        try
                        {
                            CeErpTradeCell itemData = CeErpTradeCell.GetByCtid(ctid);
                            List<string> files = new List<string>();
                            List<string> tids = new List<string>();

                            string finishDesignTime = getDesignTime(itemData.FinishDesignTime);
                            string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(itemData.seller_memo);
                            string ext = getCanDownFile(df_name);
                            if (string.IsNullOrEmpty(ext))
                            {
                                updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '文件不存在!{1}',type=2,sendtime = GETDATE() where id= {0};", id, df_name);
                                CeErpTradeLog.ExecuteNonQuery(updateSql);
                                continue;
                            }
                            string fname = df_name + ext;
                            string rname = formatMemo(itemData.seller_memo) + ext;

                            if (itemData.OrderState != 5)
                            {
                                updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '订单状态不正确!',type=2,sendtime = GETDATE() where id= {0};", id);
                                CeErpTradeLog.ExecuteNonQuery(updateSql);
                                continue;
                            }
                            int IsFileEncrypt = IsFileEncrypted(fname);
                            if (IsFileEncrypt == 1 && File.Exists(fname))
                            {
                                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);
                                    updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '解密失败!',type=2,sendtime = GETDATE() where id= {0};", id);
                                    CeErpTradeLog.ExecuteNonQuery(updateSql);
                                    continue;
                                }
                                uint a = DecFile(fname);
                                if (a != 0)
                                {
                                    addLog(ctid, userId, "解密失败" + a, 0);
                                    updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '解密失败!' ,type=2,sendtime = GETDATE() where id= {0};", id);
                                    CeErpTradeLog.ExecuteNonQuery(updateSql);
                                    continue;
                                }
                            }
                            if (string.IsNullOrEmpty(fname))
                            {
                                updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '解密失败!',type=2,sendtime = GETDATE() where id= {0};", id);
                                CeErpTradeLog.ExecuteNonQuery(updateSql);
                                continue;
                            }
                            try
                            {

                                long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                                Dictionary<string, object> param = new Dictionary<string, object>();
                                param.Add("orderNo", itemData.ctid);
                                param.Add("useract", userName);
                                param.Add("timestamp", timestamp);
                                param.Add("sign", GetMD5Hash(itemData.ctid + timestamp.ToString()) + GetMD5Hash(passWord));
                                string url = pUrl + "?" + ToUrlParams(param);

                                filePath = copyFile(getDesignDate(itemData.FinishDesignTime), "XHY", fname, rname);
                                // filePath = copyTempFile(fname, rname);

                                writeLog("XHY复制文件！:" + fname);
                                writeLog("XHY复制文件！地址:" + filePath);

                                using (var postVars = new MultipartFormDataContent())
                                {

                                    postVars.Add(new StringContent(json), "json");
                                    if (filePath != null)
                                    {
                                        // 使用 FileStream 打开文件，并包装为 StreamContent
                                        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                        var streamContent = new StreamContent(fileStream);
                                        // 设置 Content-Disposition，需要手动指定文件名
                                        streamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                                        {
                                            Name = "file",
                                            FileName = Path.GetFileName(filePath)
                                        };
                                        postVars.Add(streamContent);
                                    }
                                    var request = new HttpRequestMessage
                                    {
                                        Method = HttpMethod.Post,
                                        RequestUri = new Uri(url),
                                        Headers =
                                         {
                                             { "ContentType", "application/json" },
                                         },
                                    };
                                    request.Content = postVars;

                                    using (var response = client.SendAsync(request).GetAwaiter().GetResult())
                                    {
                                        string responseBody = await response.Content.ReadAsStringAsync();

                                        string result = response.Content.ReadAsStringAsync().Result;

                                        ApiXhyResponse xhyResponse = JsonConvert.DeserializeObject<ApiXhyResponse>(result);
                                        if (xhyResponse.code == 200)
                                        {
                                            updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '{1}',type=1,sendtime = GETDATE() where id= {0};", id, xhyResponse.message);
                                            // updateSql += string.Format("update CE_ErpTradeCell set OrderState=6,IsHaveNewOrder=0 where ctid ='{0}' and OrderState=5 and IsHaveNewOrder=3;", itemData.ctid);
                                        }
                                        else
                                        {
                                            updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '{1}',type=2,sendtime = GETDATE() where id= {0};", id, xhyResponse.message);
                                        }
                                        CeErpTradeLog.ExecuteNonQuery(updateSql);
                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                writeLog("Xh复制文件出错！" + ex);
                                updateSql = string.Format("update CE_ErpXhyOrderInfo set message = '复制文件出错!{1}' ,type=2,sendtime = GETDATE() where id= {0};", id, ex.Message);
                                CeErpTradeLog.ExecuteNonQuery(updateSql);
                            }
                            finally
                            {
                                if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                                {
                                    try
                                    {
                                        // File.Delete(filePath);
                                    }
                                    catch (Exception delEx)
                                    {
                                        writeLog("删除临时文件失败: " + delEx.Message);
                                    }
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            writeLog("Xh打包文件出错！" + ex.Message);
                            updateSql = string.Format("update CE_ErpXhyOrderInfo set message = 'Xh打包文件出错!{1}' ,type=2,sendtime = GETDATE() where id= {0};", id, ex.Message);
                            CeErpTradeLog.ExecuteNonQuery(updateSql);
                        }

                    }
                }
                running = false;
            }
        });

        conSuc("运行结束！");
        //FileOssUp();
    }

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


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

    private string copyFile(string date, string supplier, string file, string rname, string zipName = "")
    {
        string path = getCopyPath(date, supplier, zipName);

        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        string fname = Path.GetFileName(file);
        File.Copy(file, path + "\\" + rname, true);
        if (!File.Exists(path + "\\" + rname))
        {
            File.Copy(file, path + "\\" + rname, true);
        }
        return path + "\\" + rname;
    }
    private string copyTempFile(string file, string rname)
    {

        if (!Directory.Exists(tempUpPath)) Directory.CreateDirectory(tempUpPath);
        string fname = Path.GetFileName(file);
        File.Copy(file, tempUpPath + "\\" + rname, true);
        if (!File.Exists(tempUpPath + "\\" + rname))
        {
            File.Copy(file, tempUpPath + "\\" + rname, true);
        }
        return tempUpPath + "\\" + rname;
    }

    private string getCopyPath(string date, string supplier, string zipName = "")
    {
        string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
        if (!string.IsNullOrEmpty(zipName))
        {
            path = path + "\\" + zipName;
        }
        return path;
    }

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


    static Dictionary<string, string> replaceRules = new Dictionary<string, string>
        {
            { "皙贝", "白卡" },
            { "睿狐", "莱尼" },
            { "岚蝶", "安格" },
            { "琮纹", "刚古" },
            { "珠光", "珠光" },
            { "溪雪", "珠光" },
            { "雅柔", "雅柔" },
            { "萱姿", "雅柔" },
            { "草香", "草香" },
            { "芳怡", "草香" },
            { "金绒", "牛皮" },
            { "素芸", "棉卡" },
            { "玉蕊", "蛋壳" }
        };

    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();
    }
    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();
                }
            }
        }
    }
    public static string GetMD5Hash(string input)
    {
        // 创建一个MD5对象
        using (MD5 md5 = MD5.Create())
        {
            // 将输入字符串转换为字节数组
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            // 计算输入字节数组的哈希值
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            // 将字节数组转换为字符串
            StringBuilder hashString = new StringBuilder();
            foreach (byte b in hashBytes)
            {
                hashString.AppendFormat("{0:x2}", b);
            }
            return hashString.ToString();
        }
    }
    public static string ToUrlParams(Dictionary<string, object> jsonObject)
    {
        if (jsonObject == null || jsonObject.Count == 0)
            return string.Empty;

        var sb = new StringBuilder();
        bool first = true;

        foreach (var kvp in jsonObject)
        {
            string key = kvp.Key;
            object value = kvp.Value;

            if (value == null) continue;

            // 判断是否为集合（排除字符串）
            IEnumerable enumerable = value as IEnumerable;
            if (enumerable != null && !(value is string))
            {
                int index = 0;
                foreach (var item in enumerable)
                {
                    string encodedKey = Uri.EscapeDataString(key) + "[" + index + "]";
                    string encodedValue = Uri.EscapeDataString(item != null ? item.ToString() : string.Empty);
                    AppendParameter(sb, ref first, encodedKey, encodedValue);
                    index++;
                }
            }
            else
            {
                string encodedKey = Uri.EscapeDataString(key);
                string encodedValue = Uri.EscapeDataString(value.ToString());
                AppendParameter(sb, ref first, encodedKey, encodedValue);
            }
        }

        return sb.ToString();
    }

    private static void AppendParameter(StringBuilder sb, ref bool first, string key, string value)
    {
        if (!first)
            sb.Append('&');
        else
            first = false;

        sb.Append(key).Append('=').Append(value);
    }
    public class ApiXhyResponse
    {
        public string message { get; set; }
        public int code { get; set; }
    }

    public class Data
    {
        public string msg { get; set; }

        public double price { get; set; }
    }
}
