using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;
using System.IO;
using Aop.Api.Util;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/[controller]/[action]")]
    public class AlipayController : BaseController
    {
        public AlipayController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }


        #region 支付宝服务平台支付回调
        public string Notice()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            function.WriteLog(DateTime.Now.ToString() + "\r\n" + requestMes + "\r\n\r\n", "支付宝服务平台支付回调");
            return PayCallBack(new AlipayFunction(_accessor.HttpContext).AlipayPublicKey, requestMes);
        }

        public string PayCallBack(string publickey, string requestMes, bool IsRedis = false)
        {
            // Library.function.WriteLog(requestMes, "支付宝回调日志");
            var result = "fail";
            var sPara = GetRequestPost(requestMes);
            if (sPara.Count > 0) //判断是否有带返回参数
            {
                // Library.function.WriteLog("有参数", "支付宝回调日志");
                bool verifyResult = false;
                var aliNotify = new Com.Alipay.Notify();
                string signtype = sPara["sign_type"];
                var total_fee = 0m;
                string strPrice = sPara["total_amount"];//金额
                decimal.TryParse(strPrice, out total_fee);
                verifyResult = AlipaySignature.RSACheckV1(sPara, publickey, "UTF-8", signtype, false);
                // Library.function.WriteLog(verifyResult.ToString(), "支付宝回调日志");
                if (verifyResult) //验证成功
                {
                    // Library.function.WriteLog("验证成功\r\n\r\n", "支付宝回调日志");
                    //商户订单号
                    string out_trade_no = sPara["out_trade_no"];
                    //支付宝交易号
                    string trade_no = sPara["trade_no"];
                    //交易状态 TRADE_SUCCESS
                    string trade_status = sPara["trade_status"];

                    //交易成功
                    if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS")
                    {
                        RedisDbconn.Instance.AddList("PayCallBack", "{\"out_trade_no\":\"" + out_trade_no + "\",\"transaction_id\":\"" + trade_no + "\",\"total_fee\":\"" + total_fee + "\",\"pay_mode\":\"1\",\"openid\":\"\",\"attach\":\"\"}");
                        result = "success";
                    }
                }
            }
            return result;
        }

        public string MerAuth(string app_auth_code)
        {
            function.WriteLog(DateTime.Now.ToString() + "\n" + Request.QueryString.ToString(), "支付宝代商家授权回调日志");
            string result = new AlipayFunction().GetToken(app_auth_code);
            function.WriteLog(result, "支付宝代商家授权回调日志");
            //{"alipay_open_auth_token_app_response":{"code":"10000","msg":"Success","app_auth_token":"202306BB5e2aa2157bef47b7a8d918cadb0f1X25","app_refresh_token":"202306BB57fdb346273840b7aca1d63b34110D25","auth_app_id":"2021004102667228","expires_in":31536000,"re_expires_in":32140800,"tokens":[{"app_auth_token":"202306BB5e2aa2157bef47b7a8d918cadb0f1X25","app_refresh_token":"202306BB57fdb346273840b7aca1d63b34110D25","auth_app_id":"2021004102667228","expires_in":31536000,"re_expires_in":32140800,"user_id":"2088402028451259"}],"user_id":"2088402028451259"},"sign":"NLGZMLHbvb39KXeTBj0UPMVCeIYdxKymSXSBJAdRnuE8zCdJJTkk+flaclj63ljhK2WC/KOue/K1RSAjCepjtLVJaQxBfnTD/YXWHMRwcd8MM3aOX2D/wfl4VBgvzMJ2/fNAgycZ7ps2TiWyDrLz82DXtWpvXIRq0/NuZ6gILIdIl1jS/h4rgUB44ld+23ihNUuyqn1zV2EEm8ZZScEObnwg48sZ7Kd0PfOoXTJX/vfotFm3QXOzUwMNRDm6I2q+UvCGA355QaUvZhUzHOVUldvM4MaZom2TQDvpYf5EFTxSOZ7OglWjvJim1/ZcjUbqY00mTgoMoorrOH7p0OQyfA=="}
            JsonData jsonObj = JsonMapper.ToObject(result);
            if(jsonObj["alipay_open_auth_token_app_response"]["code"].ToString() == "10000")
            {
                string app_auth_token = jsonObj["alipay_open_auth_token_app_response"]["app_auth_token"].ToString();
                MerchantAddInfo addInfo = maindb.MerchantAddInfo.FirstOrDefault(m => m.Id == 0);
                if(addInfo != null)
                {
                    addInfo.AlipayAuthToken = app_auth_token;
                    maindb.SaveChanges();
                }
            }

            return "授权成功";
        }
        
        private SortedDictionary<string, string> GetRequestPost(string canshu)
        {
            var sArray = new SortedDictionary<string, string>();
            string[] canshulist = canshu.Split('&');
            foreach (var substring in canshulist)
            {
                string[] datalist = substring.Split('=');
                sArray.Add(datalist[0], HttpUtility.UrlDecode(datalist[1]));
            }
            return sArray;
        }
        #endregion
        

        #region 提交审核小程序

        public string MiniProgramApply(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string Detail = data["Detail"].ToString();
            string Version = data["Version"].ToString();
            return new AlipayFunction().MiniProgramApply(Version, Detail);
        }

        #endregion

        #region 小程序上线

        public string MiniProgramOnline(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string Version = data["Version"].ToString();
            return new AlipayFunction().MiniProgramOnline(Version);
        }

        #endregion

        #region 小程序退回开发状态

        public string MiniProgramCancel(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string Version = data["Version"].ToString();
            return new AlipayFunction().MiniProgramCancel(Version);
        }

        #endregion


    }
}
