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

import cn.hutool.json.JSONUtil;
import com.hzs.common.core.enums.EPayChannel;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.third.pay.config.JdPayConfig;
import com.hzs.third.pay.constants.JdPayConstants;
import com.hzs.third.pay.controller.base.JdBaseController;
import com.hzs.third.pay.jdpay.dto.JdPayRefundSuccessNotify;
import com.hzs.third.pay.jdpay.sdk.JdPay;
import com.hzs.third.pay.jdpay.util.GsonUtil;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 京东退填回调控制器
 * @Author: jiang chao
 * @Time: 2023/8/17 15:50
 * @Classname: JdRefundNotifyController
 * @PackageName: com.hzs.third.pay.controller.notify
 */
@Slf4j
@RestController
@RequestMapping("/jd-refund")
public class JdRefundNotifyController extends JdBaseController {

    @Autowired
    private JdPayConfig jdPayConfig;
    @Autowired
    private IRefundService iRefundService;

    /**
     * 京东退款回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String refundNotify(HttpServletRequest request) {
        try {
            String reqBody = this.getRequestBody(request);
            log.info("京东退款回调！ body： {}", reqBody);

            if (this.checkToken(request, reqBody, jdPayConfig.getSecretKey())) {
                // 签名校验通过
                Map<String, String> dataMap = JSONUtil.toBean(reqBody, HashMap.class);

                // 退款编号
                String refundCode = dataMap.get("refundRequestNum");
                // 京东交易流水号
                String refundNumber = dataMap.get("orderNum");
                // 退款完成时间
                Date finishTime = DateUtils.parseDate(dataMap.get("refundSuccessTime"), DateUtils.YYYY_MM_DD_HH_MM_SS);
                // 退款金额
                BigDecimal finishMoney = new BigDecimal(dataMap.get("refundAmount"));

                if (JdPayConstants.ORDER_SUCCESS.equals(dataMap.get("refundStatus"))) {
                    // 退款成功
                    // 退款后续业务处理
                    if (iRefundService.notifyHandle(EPayChannel.JD, refundCode, refundNumber, finishTime, finishMoney)) {
                        return JdPayConstants.RETURN_SUCCESS;
                    }
                } else {
                    // 退款失败
                    log.error("京东退款失败： {}", dataMap.get("failReason"));

                    if (iRefundService.notifyErrorHandle(EPayChannel.JD, refundCode, refundNumber, dataMap.get("failReason"))) {
                        return JdPayConstants.RETURN_SUCCESS;
                    }
                }
            } else {
                log.error("京东支付回调签名校验失败！");
            }
        } catch (Exception e) {
            log.error("京东支付回调处理异常", e);
        }
        return JdPayConstants.RETURN_FAIL;
    }


    @Resource(name = "jdPayBank")
    private JdPay jdPay;

    /**
     * 京东收银台处理成功返回
     */
    private static final String SUCCESS = "SUCCESS";
    /**
     * 京东收银台处理失败返回
     */
    private static final String ERROR = "ERROR";

    /**
     * 京东收银台退款异步支付回调
     *
     * @param reqText
     * @return 成功返回"SUCCESS",  失败返回"ERROR",退款通知会再次发起通知，通知频次见接口文档。
     */
    @PostMapping("/trade-notify")
    public String tradeNotify(@RequestBody String reqText) {
        log.info("京东收银台退款异步回调！ reqText： {}", reqText);
        try {
            // 验证签名与解密
            String interData = jdPay.verifyResponse(reqText);
            JdPayRefundSuccessNotify successNotify = GsonUtil.fromJson(interData, JdPayRefundSuccessNotify.class);
            if (null != successNotify) {
                if ("FINI".equals(successNotify.getTradeStatus())) {

                    // 退款编号
                    String refundCode = successNotify.getOutTradeNo();
                    // 京东交易流水号
                    String refundNumber = successNotify.getTradeNo();
                    // 退款完成时间
                    Date finishTime = DateUtils.parseDate(successNotify.getFinishDate(), DateUtils.YAMMERERS);
                    // 退款金额
                    int tradeAmount = Integer.parseInt(successNotify.getTradeAmount());
                    BigDecimal finishMoney = new BigDecimal(tradeAmount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);

                    // 退款后续业务处理
                    if (iRefundService.notifyHandle(EPayChannel.JD, refundCode, refundNumber, finishTime, finishMoney)) {
                        return SUCCESS;
                    }
                } else {
                    log.error("京东收银台退款异步回调失败，resultDesc: {}", successNotify.getResultDesc());
                }
            } else {
                log.error("京东收银台退款异步回调解密为空");
            }
        } catch (Exception e) {
            log.error("京东收银台退款异步回调异常", e);
        }
        return ERROR;
    }

}
