package com.ssj.alipay.utils;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class AlipayOrderHelper {
    private static Logger logger = LoggerFactory.getLogger(AlipayOrderHelper.class);

    private static final String ALIPAY_WAP = "WAP";
    private static final String ALIPAY_APP = "APP";

    /**
     * 支付宝APP支付
     * @param orderMoney 金额,
     * @param order_no   订单编号
     * @param title      商品的标题/交易标题/订单标题/订单关键字等。
     * @param body       支付提示语
     * @return
     * @throws Exception 创建人：wuwen
     *                   2019年4月23日11:45:12
     * @Map<String,Object>
     */
    public static Map<String, String> reqestAPPAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body) throws Exception {
        String url = SystemResourceLocator.getValue("sys_url") + "/pay/payment/order_alipay_callback.html";
        Map<String, String> data = requestAliPayOrder(orderMoney, order_no, title, body, url, "APP");
        return data;
    }
    /**
     * 支付宝手机网页支付
     * @param orderMoney
     * @param order_no
     * @param title
     * @param body
     * @return
     * @throws Exception
     */
    public static Map<String, String> reqestWapAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body) throws Exception {
        String url = SystemResourceLocator.getValue("sys_url") + "/pay/payment/order_alipay_callback.html";
        Map<String, String> data = requestAliPayOrder(orderMoney, order_no, title, body, url, "WAP");
        return data;
    }

    public static Map<String, String> requestAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body, String url, String payType) throws Exception {
        TokenManager tokenManager = SystemResourceLocator.getBean(TokenManager.class, "tokenManager");
        String key = payType + order_no;
        Map<String, String> prepaymap = tokenManager.hget(key);
        logger.info("key=" + key);
        if (!prepaymap.isEmpty()) {
            logger.info("===返回支付宝orderString参数redis获取:" + prepaymap);
            return prepaymap;
        }
        String orderString = "";
        // 支付宝统一下单接口
        AlipayClient alipayClient = AlipayClientFactory.getAlipayClient();

        if (ALIPAY_WAP.equals(payType)) {
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.wap.pay
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeWapPayModel wapPayModel = new AlipayTradeWapPayModel();
            //设置未付款支付宝交易的超时时间
            wapPayModel.setTimeoutExpress(AlipayPayConfig.TIMEOUTEXPRESS);
            //为固定值QUICK_MSECURITY_PAY
            wapPayModel.setProductCode(AlipayPayConfig.QUICK_MSECURITY_PAY);
            //商户网站唯一订单号
            wapPayModel.setOutTradeNo(order_no);
            //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
            wapPayModel.setBody(body);
            //商品的标题/交易标题/订单标题/订单关键字等。
            wapPayModel.setSubject(title);
            //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
            wapPayModel.setTotalAmount(orderMoney.toString());

            request.setBizModel(wapPayModel);
            //页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址
            request.setReturnUrl("");
            //服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
            request.setNotifyUrl(url);

            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理。
            orderString = response.getBody();
        } else if (ALIPAY_APP.equals(payType)) {
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel appPayModel = new AlipayTradeAppPayModel();

            //设置未付款支付宝交易的超时时间
            appPayModel.setTimeoutExpress(AlipayPayConfig.TIMEOUTEXPRESS);
            //为固定值QUICK_MSECURITY_PAY
            appPayModel.setProductCode(AlipayPayConfig.QUICK_MSECURITY_PAY);
            //商户网站唯一订单号
            appPayModel.setOutTradeNo(order_no);
            //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
            appPayModel.setBody(body);
            //商品的标题/交易标题/订单标题/订单关键字等。
            appPayModel.setSubject(title);
            //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
            appPayModel.setTotalAmount(orderMoney.toString());

            request.setBizModel(appPayModel);
            //支付宝服务器主动通知商户服务器里指定的页面
            request.setNotifyUrl(url);
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理。
            orderString = response.getBody();
        }
        Map<String, String> data = new HashMap<>(16);
        data.put("orderString", orderString);
        logger.info("===返回支付宝orderString参数:" + data);
        if (!data.isEmpty()) {
            tokenManager.hset(key, data, 1800);
        }
        return data;
    }
}
