package com.liquidnet.service.dragon.channel.alipay.biz;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.dragon.channel.alipay.req.AlipayTradePayReq;
import com.liquidnet.service.dragon.channel.alipay.sign.MD5;
import com.liquidnet.service.dragon.utils.ObjectUtil;
import com.liquidnet.service.dragon.utils.PayAlipayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: AlipayBiz
 * @Package com.liquidnet.service.dragon.channel.alipay.biz
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/10 16:21
 */
@Slf4j
@Component
public class AlipayBiz{
    /**
     * 支付宝支付
     * @param alipayTradePayReq
     * @return
     */
    public static Map<String, Object> tradeWapPay_yace(AlipayTradePayReq alipayTradePayReq) {
        log.info("AlipayBiz.tradeWapPay-->> req : {}",alipayTradePayReq.toString());
        String timeExpress = "5m";// 支付超时，线下扫码交易定义为5分钟

        AlipayClient alipayClient = PayAlipayUtils.getInstance().getHttpClient();

        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("product_code", alipayTradePayReq.getProductCode());
        paramMap.put("total_amount", alipayTradePayReq.getTotalAmount().toString());
        paramMap.put("subject", alipayTradePayReq.getSubject());
        paramMap.put("body", alipayTradePayReq.getBody());
        paramMap.put("out_trade_no", alipayTradePayReq.getOutTradeNo());
        paramMap.put("timeout_express", timeExpress);


        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(alipayTradePayReq.getNotifyUrl());
//        request.setTimestamp(DateUtil.now());
        log.info("bizContent :{}", JSONObject.toJSONString(paramMap));
        request.setBizContent(JSONObject.toJSONString(paramMap));
        try {
            long startTime = System.currentTimeMillis();
            AlipayTradeWapPayResponse response = new AlipayTradeWapPayResponse();
            response.setBody("alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2019082866535131&biz_content=%7B%22body%22%3A%22pay+%E5%8E%8B%E6%B5%8B-%E6%B5%8B%E8%AF%95%E7%A5%A8-07%E6%9C%8801%E6%97%A5%7E08%E6%9C%8831%E6%97%A5%22%2C%22out_trade_no%22%3A%22PAY2021072022223316428316%22%2C%22product_code%22%3A%22QUICK_WAP_PAY%22%2C%22subject%22%3A%2207%E6%9C%8801%E6%97%A5%7E08%E6%9C%8831%E6%97%A5%E6%B5%8B%E8%AF%95%E7%A5%A8-pay+%E5%8E%8B%E6%B5%8B%22%2C%22timeout_express%22%3A%225m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.wap.pay&notify_url=https%3A%2F%2Fdragon.zhengzai.tv%2Fdragon%2Fnotify%2Falipay%2Fwap&sign=MDiFk1Ut6keiE7mKiNzMg2eY01%2BbjcQFfjqBamPyAEAnTsLTh2u6xIiz5mWFVE%2B71qK95oetdQ%2B%2FMXOhc8fniHuef3JDRFkqjeJ0HPIIofndHHYKZYPsTkAnq6Axr3zrhvE%2BpzlWNxJS2Ci4cFFAkPPnTnHfT6tjIVbFE3HSnaWYWnWLfXkH%2Bn7QnxWsQAylq7gkAn67sCIXGNkI%2BZbhVLQnXkXJ5b88q3l%2B4Xaf9G5APsGPje7NKQ%2BuxgL%2BcAE7%2BVatfXQfB4%2BJ%2FW1xsOaS2fS545PpaD%2FI5R75vqBliMi0ed8UjAD7LUoZ8X8ZuxZY9zoyZDyhC9ssyek5%2FRpjpw%3D%3D&sign_type=RSA2&timestamp=2021-07-20+22%3A22%3A33&version=1.0");
            response.setSubCode("ACQ.TRADE_HAS_SUCCESS");
            log.info("alipay-alipayClient.sdkExecut->耗时:{}",(System.currentTimeMillis() - startTime)+"毫秒");
//            {"body":"alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2019082866535131&biz_content=%7B%22body%22%3A%22pay+%E5%8E%8B%E6%B5%8B-%E6%B5%8B%E8%AF%95%E7%A5%A8-07%E6%9C%8801%E6%97%A5%7E08%E6%9C%8831%E6%97%A5%22%2C%22out_trade_no%22%3A%22PAY2021072022223316428316%22%2C%22product_code%22%3A%22QUICK_WAP_PAY%22%2C%22subject%22%3A%2207%E6%9C%8801%E6%97%A5%7E08%E6%9C%8831%E6%97%A5%E6%B5%8B%E8%AF%95%E7%A5%A8-pay+%E5%8E%8B%E6%B5%8B%22%2C%22timeout_express%22%3A%225m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.wap.pay&notify_url=https%3A%2F%2Fdragon.zhengzai.tv%2Fdragon%2Fnotify%2Falipay%2Fwap&sign=MDiFk1Ut6keiE7mKiNzMg2eY01%2BbjcQFfjqBamPyAEAnTsLTh2u6xIiz5mWFVE%2B71qK95oetdQ%2B%2FMXOhc8fniHuef3JDRFkqjeJ0HPIIofndHHYKZYPsTkAnq6Axr3zrhvE%2BpzlWNxJS2Ci4cFFAkPPnTnHfT6tjIVbFE3HSnaWYWnWLfXkH%2Bn7QnxWsQAylq7gkAn67sCIXGNkI%2BZbhVLQnXkXJ5b88q3l%2B4Xaf9G5APsGPje7NKQ%2BuxgL%2BcAE7%2BVatfXQfB4%2BJ%2FW1xsOaS2fS545PpaD%2FI5R75vqBliMi0ed8UjAD7LUoZ8X8ZuxZY9zoyZDyhC9ssyek5%2FRpjpw%3D%3D&sign_type=RSA2&timestamp=2021-07-20+22%3A22%3A33&version=1.0","success":true}
//            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            Map<String,Object> responseJSON = JsonUtils.OM().convertValue(response,Map.class);
            log.info("AlipayUtil-->tradeWapPay-->支付宝返回结果:{}", JsonUtils.toJson(response));
            return responseJSON;
        } catch (Exception e) {
            log.error("支付宝支付异常:{}", e);
            JSONObject resultJSON = new JSONObject();
            resultJSON.put("outTradeNo", alipayTradePayReq.getOutTradeNo());
            resultJSON.put("totalAmount", alipayTradePayReq.getTotalAmount().toString());
            resultJSON.put("errorCode", "9999");
            return resultJSON;
        }
    }

    public static Map<String, Object> tradeWapPay(AlipayTradePayReq alipayTradePayReq) {
        log.info("AlipayBiz.tradeWapPay-->> req : {}",alipayTradePayReq.toString());
        String timeExpress = "5m";// 支付超时，线下扫码交易定义为5分钟

        AlipayClient alipayClient = PayAlipayUtils.getInstance().getHttpClient();

        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("product_code", alipayTradePayReq.getProductCode());
        paramMap.put("total_amount", alipayTradePayReq.getTotalAmount().toString());
        paramMap.put("subject", alipayTradePayReq.getSubject());
        paramMap.put("body", alipayTradePayReq.getBody());
        paramMap.put("out_trade_no", alipayTradePayReq.getOutTradeNo());
        paramMap.put("timeout_express", timeExpress);


        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(alipayTradePayReq.getNotifyUrl());
//        request.setTimestamp(DateUtil.now());
        log.info("bizContent :{}", JsonUtils.toJson(paramMap));
        request.setBizContent(JsonUtils.toJson(paramMap));
        try {
            long startTime = System.currentTimeMillis();
            AlipayTradeWapPayResponse response = alipayClient.sdkExecute(request);
            log.info("alipay-alipayClient.sdkExecut->耗时:{}",(System.currentTimeMillis() - startTime)+"毫秒");

//            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            Map<String,Object> responseJSON = JsonUtils.OM().convertValue(response,Map.class);
            log.info("AlipayUtil-->tradeWapPay-->支付宝返回结果:{}", JsonUtils.toJson(response));
            return responseJSON;
        } catch (AlipayApiException e) {
            log.error("支付宝支付异常:{}", e);
            JSONObject resultJSON = ObjectUtil.cloneJsonObjectObj();
            resultJSON.put("outTradeNo", alipayTradePayReq.getOutTradeNo());
            resultJSON.put("totalAmount", alipayTradePayReq.getTotalAmount().toString());
            resultJSON.put("errorCode", "9999");
            return resultJSON;
        }
    }

    /**
     * 支付宝支付
     * @param alipayTradePayReq
     * @return
     */
    public static Map<String, Object> tradeAppPay(AlipayTradePayReq alipayTradePayReq) {
        log.info("AlipayUtil.tradeAppPay-->> req : {}",alipayTradePayReq.toString());
        String timeExpress = "5m";// 支付超时，线下扫码交易定义为5分钟

        AlipayClient alipayClient = PayAlipayUtils.getInstance().getHttpClient();

        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("product_code", alipayTradePayReq.getProductCode());
        paramMap.put("total_amount", alipayTradePayReq.getTotalAmount().toString());
        paramMap.put("subject", alipayTradePayReq.getSubject());
        paramMap.put("body", alipayTradePayReq.getBody());
        paramMap.put("out_trade_no", alipayTradePayReq.getOutTradeNo());
        paramMap.put("timeout_express", timeExpress);


        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(alipayTradePayReq.getNotifyUrl());
//        request.setTimestamp(DateUtil.now());
        log.info("bizContent :{}",JSONObject.toJSONString(paramMap));
        request.setBizContent(JSONObject.toJSONString(paramMap));
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            Map<String,Object> responseJSON = JsonUtils.fromJson(JsonUtils.toJson(response), new TypeReference<Map<String,Object>>() {
            });
            log.info("AlipayUtil-->tradeAppPay-->支付宝返回结果:{}", responseJSON);
            return responseJSON;
        } catch (AlipayApiException e) {
            log.error("支付宝支付异常:{}", e);
            JSONObject resultJSON = new JSONObject();
            resultJSON.put("outTradeNo", alipayTradePayReq.getOutTradeNo());
            resultJSON.put("totalAmount", alipayTradePayReq.getTotalAmount().toString());
            resultJSON.put("errorCode", "9999");
            return resultJSON;
        }
    }


    /**
     * 订单查询
     *
     * @return
     */
    public static Map<String, Object> tradeQuery(String outTradeNo) {
        log.info("======>支付宝交易查询");
        AlipayClient alipayClient = PayAlipayUtils.getInstance().getHttpClient();

        SortedMap<String, Object> bizContentMap = new TreeMap<>();
        bizContentMap.put("out_trade_no", outTradeNo);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent(JSONObject.toJSONString(bizContentMap));
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            log.info("支付宝订单查询返回结果:{}", responseJSON);
            return responseJSON;
        } catch (AlipayApiException e) {
            log.error("支付宝交易查询异常:{}", e);
            return null;
        }
    }

    private static String getSign(SortedMap<String, String> paramMap, String key) {
        StringBuilder signBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            if (!"sign".equals(entry.getKey()) && !"sign_type".equals(entry.getKey()) && !StringUtil.isEmpty(entry.getValue())) {
                signBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        return MD5.sign(signBuilder.substring(0, signBuilder.length() - 1), key, "UTF-8");
    }

    public static Map<String , String> parseNotifyMsg(Map<String, String[]> requestParams){

        Map<String,String> params = new HashMap<String,String>();

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        return params;
    }
}
