using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Service;
using Hncore.Pass.Sells.Domain;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using Hncore.Infrastructure.Serializer;
using System;
using System.Security.Cryptography;
using System.Net;
using System.Web;
using System.IO;
using System.Text;

namespace Hncore.Pass.Sells.Service
{
    public class SellerTaoBaoService : ServiceBase<TaoBaoOrderEntity>, IFindService
    {
        CourseContext m_DbContext;
      
        public SellerTaoBaoService(
            CourseContext dbContext
            ,IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_DbContext = dbContext;         
        }

        public async override Task<TaoBaoOrderEntity> Add(TaoBaoOrderEntity entity, bool autoSave = true)
        {
            if (!this.Exist(m => m.Tid == entity.Tid))
            {
                return await base.Add(entity, autoSave);
            }
            return entity;
        }

        public async Task<string> ReceivedMsg(HttpRequest request, Func<string, Task<string>> process)
        {
            string appSecret = "xrzmtmfv46mmt9c9rzt2g7c74h9g7u7u";
            long timestamp = long.Parse(request.Query["timestamp"]);
            long aopic = long.Parse(request.Query["aopic"]);  // 根据aopic判断推送类型
            string sign = request.Query["sign"];
            string json = request.Form["json"];


            LogHelper.Info("淘宝回调", $"timestamp={timestamp},aopic={aopic},sign={sign},json={json}");

            var dictParams = new Dictionary<string, string>();
            dictParams.Add("timestamp", timestamp.ToString());
            dictParams.Add("json", json);
            var checkSign = Sign(dictParams, appSecret);
            if (!string.Equals(checkSign, sign))
            {
                LogHelper.Error("淘宝回调验签失败", checkSign);
                return "验签失败";
            }
            // 验签通过进行相关的业务

            /* 
            * 返回空字符或者不返回，不进行任何操作
            * 返回规定格式，进行相应操作。允许的操作有更新发货状态、更新备注、生成旺旺消息
            * DoDummySend：更新发货状态（false不更新发货状态）
            * DoMemoUpdate：更新备注（null不更新备注）。Flag是旗帜，可以传0-5的数字，如果传-1或者不传此参数，则保留原旗帜；Memo为备注内容
            * AliwwMsg：想要发给买家的旺旺消息（null或空字符串，不发消息）
            */
            if (process != null)
            {
                var msg_info = await process(json);
                if (msg_info != "")
                {
                    var returnJson = new
                    {
                        DoDummySend = true,
                        DoMemoUpdate = new
                        {
                            Flag = 1,
                            Memo = msg_info
                        },
                        AliwwMsg = msg_info
                    };
                    return returnJson.ToJson();
                }
            }
            return "";
        }

        public async Task<string> SengMsg(string Tid,string msg)
        {
            string appSecret = "xrzmtmfv46mmt9c9rzt2g7c74h9g7u7u";


            //阿奇所发送消息
            string accessToken = "TbAldsa2ph4sa7de69r5vvccm2767evg7k9rs4gsf4273upm8c";

            WebRequest apiRequest = WebRequest.Create("http://gw.api.agiso.com/alds/WwMsg/Send");
            apiRequest.Method = "POST";
            apiRequest.ContentType = "application/x-www-form-urlencoded";
            apiRequest.Headers.Add("Authorization", "Bearer " + accessToken);
            apiRequest.Headers.Add("ApiVersion", "1");

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var args = new Dictionary<string,string>()       
                {    
                    {"timestamp",Convert.ToInt64(ts.TotalSeconds).ToString()},
                    {"tid",Tid},
                    {"msg",msg},
                };
            args.Add("sign", Sign(args, appSecret));

            string postData = "";
            foreach (var p in args)
            {
                if (!String.IsNullOrEmpty(postData))
                {
                    postData += "&";
                }
                string tmpStr = String.Format("{0}={1}", p.Key, HttpUtility.UrlEncode(p.Value));
                postData += tmpStr;
            }

            using (var sw = new StreamWriter(apiRequest.GetRequestStream()))
            {
                sw.Write(postData);
            }
            WebResponse apiResponse = null;
            try
            {
                apiResponse = apiRequest.GetResponse();
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    apiResponse = (we.Response as HttpWebResponse);
                }
                else{
                    //TODO:处理异常
                    return "";
                }
            }
            using(Stream apiDataStream = apiResponse.GetResponseStream()){
                using(StreamReader apiReader = new StreamReader(apiDataStream, Encoding.UTF8)){
                    string apiResult = apiReader.ReadToEnd();
                    apiReader.Close();
                    apiResponse.Close();
                    return apiResult;
                }
            }
          
        }

        public async Task<string> ReceivedRefundMsg(HttpRequest request, Func<string, Task<bool>> process)
        {
            string appSecret = "xrzmtmfv46mmt9c9rzt2g7c74h9g7u7u";
            long timestamp = long.Parse(request.Query["timestamp"]);
            long aopic = long.Parse(request.Query["aopic"]);  // 根据aopic判断推送类型
            string sign = request.Query["sign"];
            string json = request.Form["json"];


            LogHelper.Info("淘宝回调", $"timestamp={timestamp},aopic={aopic},sign={sign},json={json}");

            var dictParams = new Dictionary<string, string>();
            dictParams.Add("timestamp", timestamp.ToString());
            dictParams.Add("json", json);
            var checkSign = Sign(dictParams, appSecret);
            if (!string.Equals(checkSign, sign))
            {
                LogHelper.Error("淘宝回调验签失败", checkSign);
                return "验签失败";
            }
            // 验签通过进行相关的业务

            /* 
            * 返回空字符或者不返回，不进行任何操作
            * 返回规定格式，进行相应操作。允许的操作有更新发货状态、更新备注、生成旺旺消息
            * DoDummySend：更新发货状态（false不更新发货状态）
            * DoMemoUpdate：更新备注（null不更新备注）。Flag是旗帜，可以传0-5的数字，如果传-1或者不传此参数，则保留原旗帜；Memo为备注内容
            * AliwwMsg：想要发给买家的旺旺消息（null或空字符串，不发消息）
            */
            if (process != null)
            {
                if (await process(json))
                {
                    var returnJson = new
                    {
                        DoDummySend = true,
                        DoMemoUpdate = new
                        {
                            Flag = 1,
                            Memo = "退款处理中"
                        },
                        AliwwMsg = "退款处理中"
                    };
                    return returnJson.ToJson();
                }
            }
            return "";
        }

        //参数签名
        public string Sign(IDictionary<string, string> args, string ClientSecret)
        {
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(args, StringComparer.Ordinal);
            string str = "";
            foreach (var m in sortedParams)
            {
                str += (m.Key + m.Value);
            }
            //头尾加入AppSecret
            str = ClientSecret + str + ClientSecret;
            var encodeStr = MD5Encrypt(str).ToUpper();
            return encodeStr;
        }

        //Md5摘要
        public static string MD5Encrypt(string text)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x2");
            }

            return byte2String;
        }


        public async Task<string> Test()
        {
            string appSecret = "xrzmtmfv46mmt9c9rzt2g7c74h9g7u7u";
            long timestamp = 1585122176;
            long aopic = 2;  // 根据aopic判断推送类型
            string sign = "442B91FB4811A8899EBEA689205F98A1";
            string json = "{\"Platform\":\"TAOBAO\",\"PlatformUserId\":\"619727442\",\"ReceiverName\":null,\"ReceiverMobile\":\"15538302361\",\"ReceiverPhone\":null,\"ReceiverAddress\":null,\"BuyerArea\":null,\"ExtendedFields\":{},\"Tid\":908706240358624821,\"Status\":\"WAIT_SELLER_SEND_GOODS\",\"SellerNick\":\"可乐开发商\",\"BuyerNick\":\"woai853133256\",\"Type\":null,\"BuyerMessage\":null,\"Price\":\"1.00\",\"Num\":6,\"TotalFee\":\"6.00\",\"Payment\":\"6.00\",\"PayTime\":null,\"PicPath\":\"https://img.alicdn.com/bao/uploaded/i3/619727442/TB2ZSA.XNvxQeBjy0FiXXXioXXa_!!619727442.png\",\"PostFee\":\"0.00\",\"Created\":\"2020-03-25 15:42:50\",\"TradeFrom\":\"WAP,WAP\",\"Orders\":[{\"Oid\":908706240358624821,\"NumIid\":537279953649,\"OuterIid\":null,\"OuterSkuId\":null,\"Title\":\"老客户续费连接\",\"Price\":\"1.00\",\"Num\":6,\"TotalFee\":\"6.00\",\"Payment\":\"6.00\",\"PicPath\":\"https://img.alicdn.com/bao/uploaded/i3/619727442/TB2ZSA.XNvxQeBjy0FiXXXioXXa_!!619727442.png\",\"SkuId\":\"3208012025040\",\"SkuPropertiesName\":\"付费方式:月付;服务器套餐:套餐1;对应金额:1元选项\",\"DivideOrderFee\":null,\"PartMjzDiscount\":null}],\"SellerMemo\":null,\"SellerFlag\":0,\"CreditCardFee\":null}";
            

            var dictParams = new Dictionary<string, string>();
            dictParams.Add("timestamp", timestamp.ToString());
            dictParams.Add("json", json);
            var checkSign = Sign(dictParams, appSecret);
            if (!string.Equals(checkSign, sign))
            {
                LogHelper.Error("淘宝回调验签失败", checkSign);
                return "验签失败";
            }
            return "";
        }

    }
}
