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.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.liquidnet.commons.lang.util.DateUtil;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
public class AlipayUtil {

    private static final Logger logger = LoggerFactory.getLogger(AlipayUtil.class);

    private AlipayUtil() {

    }

    /**
     * 支付宝支付
     * @param alipayTradePayReq
     * @return
     */
    public static Map<String, Object> tradeWapPay(AlipayTradePayReq alipayTradePayReq) {
        logger.info("AlipayUtil.tradePay-->> 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("https://testpay.zhengzai.tv");
//        request.setTimestamp(DateUtil.now());
        logger.info("bizContent :{}",JSONObject.toJSONString(paramMap));
        request.setBizContent(JSONObject.toJSONString(paramMap));
        try {
            AlipayTradeWapPayResponse response = alipayClient.sdkExecute(request);
            if(response.isSuccess()){

            }
            JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
            logger.info("支付宝返回结果:{}", responseJSON);
            return responseJSON;
        } catch (AlipayApiException e) {
            logger.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) {
        logger.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));
            logger.info("支付宝订单查询返回结果:{}", responseJSON);
            return responseJSON;
        } catch (AlipayApiException e) {
            logger.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");
    }
}

