package com.hfkj.service.pay.huift;

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.utils.HttpsUtils;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsOrder;
import com.hfkj.entity.BsOrderChild;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.pay.huift.config.HuiftConfig;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import com.hfkj.sysenum.order.OrderStatusEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: TradeService
 * @author: HuRui
 * @date: 2024/4/7
 **/
@Component
public class TradeService {

    @Resource
    private BsOrderService orderService;

    /**
     * 交易-预下单
     * @param order
     * @return
     * @throws Exception
     */
    public JSONObject thirdPreOrder(OrderModel order , String shopCode , String signSecret) throws Exception {
        Map<String,Object> param = new HashMap<>();
        param.put("shopCode", shopCode);
        param.put("outTradeNo", order.getOrderNo()+"_"+RandomUtils.number(3,true));
        param.put("transAmt", order.getPayRealPrice().multiply(new BigDecimal("100")).intValue());
        param.put("callbackUrl", CommonSysConst.getSysConfig().getDomainName() + "/order/notify/huiftPay");
        // param.put("remark", ""); // 备注
        // param.put("outAppId", "");
        param.put("outRedirectPath", CommonSysConst.getSysConfig().getDomainName()+"/cweb/#/order/order/orderList");
        param.put("sign", HuiftConfig.md5Encode(HuiftConfig.paramSort(param, signSecret).getBytes()).toLowerCase());
        JSONObject response = HttpsUtils.doPost(HuiftConfig.reqUrl + "/hfq/v1/thirdPay/thirdPreOrder", JSONObject.toJSONString(param));
        if (response.getString("status").equals("ok")) {
            return response.getJSONObject("data");
        }
        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , response.getString("message"));
    }

    /**
     * 查询交易结果
     * @param preOrderNo
     * @return
     * @throws Exception
     */
    public JSONObject thirdPayResult(String preOrderNo  , String shopCode , String signSecret) throws Exception {
        Map<String,Object> param = new HashMap<>();
        param.put("shopCode", shopCode);
        param.put("preOrderNo", preOrderNo);
        param.put("sign", HuiftConfig.md5Encode(HuiftConfig.paramSort(param, signSecret).getBytes()).toLowerCase());
        JSONObject response = HttpsUtils.doPost(HuiftConfig.reqUrl + "/hfq/v1/thirdPay/thirdPayResult", JSONObject.toJSONString(param));
        if (response.getString("status").equals("ok")) {
            return response.getJSONObject("data");
        }
        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , response.getString("message"));
    }

    /**
     * 交易退款
     * @param refundOrderNo 退款订单号
     * @param refundPrice  退款金额
     * @param orderNo      订单号
     * @return
     * @throws Exception
     */
    public JSONObject thirdPayRefund(String refundOrderNo, BigDecimal refundPrice, String orderNo) throws Exception {
        // 查询订单
        BsOrder order = orderService.getOrder(orderNo);
        OrderModel orderModel = orderService.getDetail(orderNo);
        if (order == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的的订单");
        }
        if (!order.getOrderStatus().equals(OrderStatusEnum.status2.getCode())
                && !order.getOrderStatus().equals(OrderStatusEnum.status3.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "订单当前状态无法退款");
        }
        if (!order.getPayType().equals(OrderPayTypeEnum.type3.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付方式错误");
        }
        Map<String,Object> param = new HashMap<>();
        param.put("shopCode", orderModel.getOrderChildList().get(0).getSettleAccount());
        param.put("preOrderNo", order.getPayChannelOrderNo());
        param.put("outRefundNo", refundOrderNo);
        param.put("refundAmt", refundPrice.multiply(new BigDecimal("100")).intValue());
        param.put("sign", HuiftConfig.md5Encode(HuiftConfig.paramSort(param, orderModel.getOrderChildList().get(0).getSettleAccountKey()).getBytes()).toLowerCase());
        JSONObject response = HttpsUtils.doPost(HuiftConfig.reqUrl + "/hfq/v1/thirdPay/thirdPayRefund", JSONObject.toJSONString(param));
        if (response.getString("status").equals("ok")) {
            return response.getJSONObject("data");
        }
        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , response.getString("message"));
    }

}
