package com.bohuikeji.delivery.backstage.pay;

import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.baidu.BaiDuBizInfo;
import com.bohuikeji.delivery.backstage.entity.baidu.BaiDuConfig;
import com.bohuikeji.delivery.backstage.entity.baidu.BaiDuOrderInfo;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.baidu.RSASign;
import jodd.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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

@Slf4j
public class BaiduPay {
    private static final String getBaiDuOpenIdUrl = "https://spapi.baidu.com/oauth/jscode2sessionkey";//百度小程序获取openId地址

    @Autowired
    ITOrderService orderService;

    /**
     * 百度获取code
     * @return
     */
    public static String getBaiDuOpenId(String code) {//pay.getPayExpectPrice().multiply(new BigDecimal(100)).longValue()
        Map<String, String> data = new HashMap<>();
        //code是前端会传的
        data.put("code", code);
        data.put("client_id", BaiDuConfig.APP_KEY);
        data.put("sk", BaiDuConfig.APP_SECRET);
        String resultJson = HttpRequest.get(getBaiDuOpenIdUrl).query(data).send().bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        log.info("登陆返回：[{}]",res);
        // 获取参数返回的
        String sessionKey = res.get("session_key").toString();
        String openId = res.get("openid").toString();
        return openId;
    }


    /**
     * 百度预支付订单
     * @param payNum
     * @param merchantNum
     * @param payExpectPrice
     * @return
     */
    public static BaiDuOrderInfo getBaiDuOrderInfo(String payNum,String merchantNum,BigDecimal payExpectPrice) {
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@百度小程序支付@@@@@@@@@@@@@@@@@@@@@@@@");
        //百度收银台创建
        BaiDuOrderInfo orderInfo = new BaiDuOrderInfo();
        orderInfo.setAppKey(BaiDuConfig.APP_KEY_PAY);
        orderInfo.setDealId(BaiDuConfig.DEAL_ID);
        orderInfo.setDealTitle("同城急送");
        orderInfo.setTotalAmount(String.valueOf(payExpectPrice.multiply(new BigDecimal(100)).longValue()));//"订单金额，单位为分" tOrder.getOrderExpectPrice().multiply(new BigDecimal(100)).toString()
        orderInfo.setTpOrderId(payNum);
        orderInfo.setSignFieldsRange("1");

        //百度支付签名
        Map<String, Object> data = new HashMap<>();
        data.put("appKey", orderInfo.getAppKey());
        data.put("dealId", BaiDuConfig.DEAL_ID);
        data.put("totalAmount", orderInfo.getTotalAmount());
        data.put("tpOrderId", payNum);

        //签名使用的类是百度签名Demo里的，自行下载即可
        String sign = null;
        try {
            sign = RSASign.sign(data, BaiDuConfig.PRIVATE_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("百度收银台支付签名:[{}]",sign);
        if (StringUtils.isBlank(sign)) {
            log.error("百度收银台支付签名错误");
            return null;
        }
        orderInfo.setRsaSign(sign);
        BaiDuBizInfo bizInfo = new BaiDuBizInfo();
        bizInfo.setAppKey(orderInfo.getAppKey());
        bizInfo.setDealld(BaiDuConfig.DEAL_ID);
        bizInfo.setTotalAmount(orderInfo.getTotalAmount());
        bizInfo.setTpOrderId(merchantNum);

        orderInfo.setBaiDuBizInfo(bizInfo);
        return orderInfo;
    }


    /**
     * 百度小程序申请退款
     * @param pay
     * @return
     */
    public static JSONObject applyOrderRefund(TPay pay,BigDecimal price) {
        JSONObject jsonObject = null;
        JSONObject object = JSONObject.parseObject(pay.getPayChannelNum());
        Map<String, String> map = new HashMap<>();
        map.put("access_token",getBaiduAccessToken());
        map.put("applyRefundMoney", price.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString());
        map.put("bizRefundBatchId", NumberUtils.getRandom(11));
        map.put("isSkipAudit", "1");
        map.put("orderId", object.get("orderId").toString());
        map.put("refundReason", "业务退款");
        map.put("refundType", "1");
        map.put("tpOrderId", pay.getPayNum());
        map.put("userId", object.get("userId").toString());
        map.put("pmAppKey", BaiDuConfig.APP_KEY_PAY);
        //参数也是得以map形式传递，这里当你发送请求，然后判断他的返回值是否正确即可，具体怎么用具体情况具体对待
        String postJson = HttpRequest.post("https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/applyOrderRefund").query(map).send().bodyText();
        jsonObject= JSONObject.parseObject(postJson);
        return jsonObject;
    }

    public static String getBaiduAccessToken() {
        String url = "https://openapi.baidu.com/oauth/2.0/token";
        Map<String, String> data = new HashMap<>();
        //code是前端会传的
        data.put("grant_type", "client_credentials");
        data.put("client_id", BaiDuConfig.APP_KEY);
        data.put("client_secret", BaiDuConfig.APP_SECRET);
        data.put("scope", "smartapp_snsapi_base");
        String resultJson = HttpRequest.get(url).query(data).send().bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        //log.info("获取开发者服务权限说明（access_token）：[{}]",res);
        // 获取参数返回的
        String accessToken = res.get("access_token").toString();
        return accessToken;
    }
}
