package com.hfkj.pay;

import com.alibaba.fastjson.JSONArray;
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.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsOrderSettle;
import com.hfkj.entity.BsOrderSettleLedger;
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 java.math.BigDecimal;
import java.util.*;

/**
 * @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/";

    /**
     * JSAPI支付
      * @param openId
     * @param order
     * @return
     * @throws Exception
     */
    public static Map<Object, Object> preorder(String merNo,String merKey,String appId,String openId,boolean profitSharing,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", "ALIPAY");
            } else if (OrderPayTypeEnum.type2.getCode() == order.getPayType()) {
                param.put("payMode", "WECHAT");
            }
            param.put("totalAmount", order.getPayRealPrice());
            param.put("profitSharing", profitSharing?1:0);
            if (StringUtils.isNotBlank(appId)) {
                param.put("subAppid", appId);
            }
            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/refund"));
            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 ==================");
        }
    }


    /**
     * 发起分账
     * @param orderSettle
     * @param settleLedgerList
     * @return
     */
    public static JSONObject profitSharingSeparate(BsOrderSettle orderSettle, List<BsOrderSettleLedger> settleLedgerList) {
        try {
            log.info("=============== start 惠支付分账 start ==================");
            Map<String,Object> param = new HashMap<>();
            param.put("merchantNo", orderSettle.getSettleMerNo());
            param.put("outTradeNo", orderSettle.getOrderNo());
            param.put("outSeparateNo", orderSettle.getLedgerOrderNo());
            param.put("totalAmount", orderSettle.getLedgerAmount().toString());

            JSONArray recvDatas = new JSONArray();
            for (BsOrderSettleLedger settleLedger : settleLedgerList) {
                JSONObject obj = new JSONObject();
                obj.put("recvMerchantNo", settleLedger.getReceiverMerNo());
                obj.put("separateAmount", settleLedger.getReceiverAmount().toString());
                recvDatas.add(obj);
            }
            param.put("recvDatas", recvDatas);

            param.put("sign" , SignatureUtil.createSign(param, orderSettle.getSettleMerKey()));
            log.info("请求地址：" + (REQUEST_URL + "profitSharing/separate"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "profitSharing/separate", 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 ==================");
        }
    }

    /**
     * 分账查询
     * @param orderSettle
     * @return
     */
    public static JSONObject profitSharingQuery(BsOrderSettle orderSettle) {
        try {
            log.info("=============== start 惠支付分账查询 start ==================");
            Map<String,Object> param = new HashMap<>();
            param.put("merchantNo", orderSettle.getSettleMerNo());
            param.put("outSeparateNo", orderSettle.getLedgerOrderNo());
            param.put("sign" , SignatureUtil.createSign(param, orderSettle.getSettleMerKey()));
            log.info("请求地址：" + (REQUEST_URL + "profitSharing/query"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "profitSharing/query", 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 ==================");
        }
    }

    /**
     * 分账撤销
     * @param orderSettle
     * @return
     */
    public static JSONObject profitSharingCancel(BsOrderSettle orderSettle) {
        try {
            log.info("=============== start 惠支付分账撤销 start ==================");
            Map<String,Object> param = new HashMap<>();
            param.put("merchantNo", orderSettle.getSettleMerNo());
            param.put("originOutSeparateNo", orderSettle.getLedgerOrderNo());
            param.put("outSeparateNo", orderSettle.getRevokeOrderNo());
            param.put("totalAmount", orderSettle.getLedgerAmount());
            param.put("sign" , SignatureUtil.createSign(param, orderSettle.getSettleMerKey()));
            log.info("请求地址：" + (REQUEST_URL + "profitSharing/cancel"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "profitSharing/cancel", 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 ==================");
        }
    }

    /**
     * 查询可分账余额
     * @param orderSettle
     * @return
     */
    public static JSONObject queryAmt(BsOrderSettle orderSettle) {
        try {
            log.info("=============== start 惠支付查询可分账余额 start ==================");
            Map<String,Object> param = new HashMap<>();
            param.put("merchantNo", orderSettle.getSettleMerNo());
            param.put("outTradeNo", orderSettle.getOrderNo());
            param.put("sign" , SignatureUtil.createSign(param, orderSettle.getSettleMerKey()));
            log.info("请求地址：" + (REQUEST_URL + "profitSharing/queryAmt"));
            log.info("请求参数：" + JSONObject.toJSONString(param));

            JSONObject response = HttpsUtils.doPost(REQUEST_URL + "profitSharing/queryAmt", 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 ==================");
        }
    }


}
