package com.bohuikeji.delivery.backstage.pay;

import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.kuaishou.KuaiShouConfig;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.TSettle;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.kuaishou.kuaishouSign;
import jodd.http.HttpRequest;
import jodd.net.MimeTypes;
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 KuaiShouPay {
    private static final String getAccessTokenUrl = "https://open.kuaishou.com/oauth2/access_token";//快手小程序获取access_token地址
    private static final String getOpenIdUrl = "https://open.kuaishou.com/oauth2/mp/code2session";//快手小程序获取OpenId地址
    private static final String getPreOrderUrl = "https://open.kuaishou.com/openapi/mp/developer/epay/create_order";//快手预下单支付
    private static final String OrderRefundUrl = "https://open.kuaishou.com/openapi/mp/developer/epay/apply_refund";//快手支付退款地址
    private static final String OrdersettleUrl = "https://open.kuaishou.com/openapi/mp/developer/epay/settle";//快手支付结算地址
    @Autowired
    ITOrderService orderService;

    /**
     * 快手获取token
     * @return
     */
    public static String getAccessToken() {//pay.getPayExpectPrice().multiply(new BigDecimal(100)).longValue()
        Map<String, String> map = new HashMap<>();
        map.put("app_id", KuaiShouConfig.App_ID);
        map.put("app_secret",KuaiShouConfig.APP_SECRET);
        map.put("grant_type","client_credentials");
        String res = HttpRequest.post(getAccessTokenUrl).query(map).send().contentType("x-www-form-urlencoded","utf-8").bodyText();
        JSONObject jsonObject= JSONObject.parseObject(res);
        log.info("接口调用凭证:{}",jsonObject);
        return jsonObject.getString("access_token");
    }

    /**
     * 快手获取openId
     * @param code
     * @return
     */
    public static String getOpenId(String code) {//pay.getPayExpectPrice().multiply(new BigDecimal(100)).longValue()
        Map<String, String> map = new HashMap<>();
        map.put("js_code",code);
        map.put("app_id",KuaiShouConfig.App_ID);
        map.put("app_secret",KuaiShouConfig.APP_SECRET);
        String res = HttpRequest.post(getOpenIdUrl).query(map).send().contentType("x-www-form-urlencoded","utf-8").bodyText();
        JSONObject jsonObject= JSONObject.parseObject(res);
        log.info("登陆授权返回地址:{}",jsonObject);
        return jsonObject.getString("open_id");
    }


    /**
     * 快手小程序预下单接口
     * @param payNum
     * @param payExpectPrice
     * @param openId
     * @return
     */
    public static JSONObject kuaishouOrder(String payNum,BigDecimal payExpectPrice,String openId) {//pay.getPayExpectPrice().multiply(new BigDecimal("100")).longValue()
        Map<String, Object> map = new HashMap<>();
        map.put("app_id",KuaiShouConfig.App_ID);
        map.put("out_order_no",payNum);
        map.put("open_id",openId);
        map.put("total_amount",payExpectPrice.multiply(new BigDecimal("100")).longValue());
        map.put("subject","同城急送");
        map.put("detail","下单支付");
        map.put("type",1288);
        map.put("expire_time",7200);
        map.put("notify_url","https://os.tcjskd.com/delivery/api/v2/kuaishou/pay/notify");
        map.put("sign", kuaishouSign.calcSign(map));
        String req = JSONObject.toJSONString(map);
        String res = HttpRequest.post(getPreOrderUrl).query("app_id",KuaiShouConfig.App_ID).query("access_token",getAccessToken()).bodyText(req,MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        JSONObject jsonObject= JSONObject.parseObject(res);
        log.info("快手小程序预支付订单返回:{}",jsonObject);
        return jsonObject.getJSONObject("order_info");
    }

    /**
     * 快手小程序订单退款接口
     * @param pay
     * @return
     */
    public static JSONObject kuaishouOrderRefund(TPay pay,BigDecimal price) {
        Map<String, Object> map = new HashMap<>();
        map.put("app_id",KuaiShouConfig.App_ID);
        map.put("out_order_no",pay.getPayNum());
        map.put("out_refund_no",NumberUtils.get("T"));
        map.put("reason","订单退款");
        map.put("notify_url","https://os.tcjskd.com/delivery/api/v2/kuaishou/pay/notify");
        map.put("refund_amount",price.multiply(new BigDecimal("100")).longValue());
        map.put("sign",kuaishouSign.calcSign(map));
        String req = JSONObject.toJSONString(map);
        String res = HttpRequest.post(OrderRefundUrl).query("app_id",KuaiShouConfig.App_ID).query("access_token",getAccessToken()).bodyText(req,MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        JSONObject jsonObject= JSONObject.parseObject(res);
        log.info("退款请求返回:{}",jsonObject);
        return jsonObject;
    }

    /**
     * 快手支付结算
     * @param settle
     * @return
     */
    public static JSONObject getOrderSettle(TSettle settle) {
        Map<String, Object> map = new HashMap<>();
        map.put("app_id",KuaiShouConfig.App_ID);
        map.put("out_order_no",settle.getPayNum());
        map.put("out_settle_no",settle.getSettleNum());
        map.put("reason","支付结算");
        map.put("notify_url","https://os.tcjskd.com/delivery/api/v2/kuaishou/get/pay/settle");
        map.put("sign",kuaishouSign.calcSign(map));
        String req = JSONObject.toJSONString(map);
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@map:{}",map);
        String res = HttpRequest.post(OrdersettleUrl).query("app_id",KuaiShouConfig.App_ID).query("access_token",getAccessToken()).bodyText(req,MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send().bodyText();
        JSONObject jsonObject= JSONObject.parseObject(res);
        return jsonObject;
    }


}
