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

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: AlipayUtil
 * @Package com.liquidnet.service.dragon.channel.alipay.util
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/9 15:20
 */

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
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.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.dragon.channel.alipay.config.AlipayConfigUtil;
import com.liquidnet.service.dragon.channel.alipay.req.AlipayTradePayReq;
import com.liquidnet.service.dragon.channel.alipay.sign.MD5;
import com.liquidnet.service.dragon.utils.PayAlipayUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Slf4j
public class AlipayUtil {
    /**
     * 支付宝支付
     * @param alipayTradePayReq
     * @return
     */
    public static Map<String, Object> tradeWapPay(AlipayTradePayReq alipayTradePayReq) {
        log.info("AlipayUtil.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 {
            AlipayTradeWapPayResponse response = alipayClient.sdkExecute(request);
            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            log.info("AlipayUtil-->tradeWapPay-->支付宝返回结果:{}", 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;
        }
    }

    /**
     * 支付宝支付
     * @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));
            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("======>支付宝交易查询");
        String charset = "UTF-8";
        String format = "json";
        String signType = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.trade_query_url, AlipayConfigUtil.app_id, AlipayConfigUtil.mch_private_key, format, charset, AlipayConfigUtil.ali_public_key, signType);

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

