package com.hfkj.service.pay;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.model.order.OrderModel;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

/**
 * @className: HuiPayService
 * @author: HuRui
 * @date: 2024/5/7
 **/
public class HuiPayService {
    static Logger log = LoggerFactory.getLogger(HuiPayService.class);
    // 请求地址
    private final static String REQUEST_URL = "https://pay.dctpay.com/openApi/v1/";
    public final static String DEFAULT_MER_NO = "2023041916292112804";
    private final static String DEFAULT_MER_KEY = "2jLO2WjXcSRSzTCaca0Kmv0OFrfYBbrA";

    /**
     * JSAPI支付
      * @param openId
     * @param order
     * @return
     * @throws Exception
     */
    public static Map<Object, Object> preorder(String merNo,String merKey,String appId,String openId,OrderModel order) throws Exception {
        try {
            log.info("=============== start 惠支付 start ==================");
            Map<String, Object> param = new HashMap<>();
            param.put("merchantNo", merNo);
            param.put("outTradeNo", order.getOrderNo());
            param.put("transType", "JSAPI");
            if (OrderPayTypeEnum.type1.getCode() == order.getPayType()) {
                param.put("payMode", "WECHAT");
            } else if (OrderPayTypeEnum.type2.getCode() == order.getPayType()) {
                param.put("payMode", "ALIPAY");
            }
            if (StringUtils.isNotBlank(appId)) {
                param.put("subAppid", appId);
            }
            param.put("totalAmount", order.getPayRealPrice());
            param.put("profitSharing", "0");
            param.put("subject", "购买产品");
            param.put("userId", openId);
            param.put("notifyUrl", CommonSysConst.getSysConfig().getHuiPayPreorderNotifyUrl());
            param.put("sign", SignatureUtil.createSign(param, merKey));

            log.info("请求地址：" + (REQUEST_URL + "trade/preorder"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "trade/preorder", param, new HashMap<>());
            log.info("响应参数：" + response.toJSONString());

            if (response != null && response.getString("return_code").equals("000000")) {
                JSONObject payParam = response.getJSONObject("return_data").getJSONObject("payParam");
                SortedMap<Object, Object> sortedMap = new TreeMap<>();
                sortedMap.put("appId", payParam.get("app_id"));
                sortedMap.put("nonceStr", payParam.get("nonce_str"));
                sortedMap.put("timeStamp", payParam.get("time_stamp"));
                sortedMap.put("signType", "MD5");
                sortedMap.put("package", payParam.get("package"));
                sortedMap.put("prepay_id", payParam.get("prepay_id"));
                sortedMap.put("sign", payParam.get("pay_sign"));
                return sortedMap;

            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("return_msg"));

        } catch (Exception e) {
            log.info("出现异常：" + e.getMessage());
            throw e;
        } finally {
            log.info("=============== end 惠支付 end ==================");
        }
    }

    /**
     * 退款
     * @param merNo
     * @param outTradeNo
     * @param refundTradeNo
     * @param refundAmount
     * @return
     * @throws Exception
     */
    public static JSONObject refund(String merNo,String merKey,String outTradeNo,String refundTradeNo, BigDecimal refundAmount) {
        try {
            log.info("=============== start 惠支付退款 start ==================");
            Map<String,Object> param = new HashMap<>();
            param.put("merchantNo", merNo);
            param.put("outTradeNo", outTradeNo);
            param.put("refundTradeNo", refundTradeNo);
            param.put("refundAmount", refundAmount);
            param.put("sign" , SignatureUtil.createSign(param, merKey));
            log.info("请求地址：" + (REQUEST_URL + "trade/preorder"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "trade/refund", param, new HashMap<>());
            log.info("响应参数：" + response.toJSONString());
            return response;
        } catch (Exception e) {
            log.info("出现异常"+ e.getMessage());
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款异常");
        } finally {
            log.info("=============== end 惠支付退款 end ==================");
        }
    }
}
