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

import cn.hutool.json.JSONUtil;
import com.huifu.adapay.core.util.AdapaySign;
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.third.pay.config.AdaPayConfig;
import com.hzs.third.pay.constants.AdaPayConstants;
import com.hzs.third.pay.service.IRefundService;
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;
import java.util.HashMap;

/**
 * 汇付退款回调控制器
 */
@Slf4j
@RestController
@RequestMapping("/ada-refund")
public class AdaRefundNotifyController {

    @Autowired
    private AdaPayConfig adaPayConfig;
    @Autowired
    private IRefundService iRefundService;

    /**
     * 汇付退款回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String refundNotify(HttpServletRequest request) {
        try {
            // 返回数据data
            String data = request.getParameter("data");
            // 返回验签sign
            String sign = request.getParameter("sign");

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

            if (AdapaySign.verifySign(data, sign, adaPayConfig.getPublicKey())) {
                // 验证通过
                // 返回数据map
                HashMap<String, String> dataMap = JSONUtil.parseObj(data).toBean(HashMap.class);

                // 宝付交易流水号
                String refundNumber = dataMap.get("id");
                // 退款完成时间
                Date finishTime = new Date(Long.parseLong(dataMap.get("created_time")));
                // 退款金额
                BigDecimal finishMoney = new BigDecimal(dataMap.get("refund_amt"));

                if (AdaPayConstants.SUCCESS.equals(dataMap.get("status"))) {
                    // 交易成功
                    // 退款后续业务处理
                    if (iRefundService.notifyHandle(EPayChannel.ADAPAY, null, refundNumber, finishTime, finishMoney)) {
                        return "OK";
                    }
                } else {
                    // 退款失败
                    log.error("汇付退款失败: {}", dataMap.get("error_msg"));

                    if (iRefundService.notifyErrorHandle(EPayChannel.ADAPAY, null, refundNumber, dataMap.get("error_msg"))) {
                        return "OK";
                    }
                }
            } else {
                log.error("汇付退款回调签名验证失败");
            }
        } catch (Exception e) {
            log.error("汇付退款回调处理异常", e);
        }
        throw new BaseException("汇付退款回调处理失败");
    }

    public static void main(String[] args) {
        System.out.println();
    }

}
