package com.hzs.third.pay.controller.notify;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huifu.bspay.sdk.opps.core.utils.RsaUtils;
import com.hzs.common.core.enums.EPayChannel;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.third.pay.config.HuiFuConfig;
import com.hzs.third.pay.constants.HuiFuPayConstants;
import com.hzs.third.pay.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description: 汇付新支付回调控制器
 * @Author: jiang chao
 * @Time: 2024/12/5 10:34
 * @Classname: HuiFuNotifyController
 * @PackageName: com.hzs.third.pay.controller.notify
 */
@Slf4j
@RestController
@RequestMapping("/huifu")
public class HuiFuNotifyController {

    @Autowired
    private HuiFuConfig huiFuConfig;
    @Autowired
    private IPayService iPayService;

    /**
     * 支付回调
     *
     * @param request
     * @return
     */
    @PostMapping("/notify")
    public AjaxResult payNotify(HttpServletRequest request) {
        try {
            // 返回验签sign
            String sign = request.getParameter("sign");
            // 返回数据data
            String data = request.getParameter("resp_data");

            log.info("新汇付支付回调 sign： {}", sign);
            log.info("新汇付支付回调 data： {}", data);

            if (RsaUtils.verify(data, huiFuConfig.getRsaPublicKey(), sign)) {
                // 验证通过，返回数据
                JSONObject dataObj = JSONUtil.parseObj(data);

                if (HuiFuPayConstants.SUCCESS_CODE.equals(dataObj.getStr("resp_code"))) {
                    // 业务返回成功
                    if (HuiFuPayConstants.TRANS_SUCCESS.equals(dataObj.getStr("trans_stat"))) {
                        // 交易状态成功

                        // 汇付商户订单号
                        String payNumber = dataObj.getStr("hf_seq_id");
                        // 渠道流水号
                        String channelNumber = dataObj.getStr("out_trans_id");
                        // 支付完成时间
                        Date payTime = DateUtils.parseDateOne(dataObj.get("end_time"), DateUtils.YAMMERERS);
                        // 支付扩展类型
                        String type = dataObj.get("remark").toString();

                        // 回调订单编号
                        String thirdOrderCode = dataObj.getStr("req_seq_id");
                        // 订单编号
                        String orderCode = thirdOrderCode;
                        // 处理订单号以及扩展类型
                        if (thirdOrderCode.indexOf("-") > 0) {
                            // 带有分隔，需要处理
                            orderCode = thirdOrderCode.split("-")[0];
                        }
                        // 订单金额
                        BigDecimal payMoney = new BigDecimal(dataObj.getStr("trans_amt"));

                        // 支付后续业务处理
                        if (iPayService.notifyHandle(type, orderCode, thirdOrderCode, payNumber, payTime, payMoney, EPayChannel.HUIFU, channelNumber)) {
                            return AjaxResult.success();
                        }
                    } else {
                        log.error("新汇付支付交易状态异常: {}", dataObj.getStr(("resp_desc")));
                    }
                } else {
                    log.error("新汇付支付回调状态异常: {}", dataObj.getStr(("resp_desc")));
                }
            } else {
                log.error("新汇付支付回调签名验证失败");
            }
        } catch (Exception e) {
            log.error("新汇付支付回调处理异常", e);
        }
        throw new BaseException("新汇付支付回调处理失败");
    }

}
