
package com.tmerclub.cloud.payment.controller;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.common.constant.PayType;
import com.tmerclub.cloud.payment.bo.RefundInfoResultBO;
import com.tmerclub.cloud.payment.manager.PayManager;
import com.tmerclub.cloud.payment.model.RefundInfo;
import com.tmerclub.cloud.payment.service.RefundInfoService;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Objects;

/**
 * 退款成功通知，目前只有微信会有退款的回调
 *
 * @author tmerclub
 */
@Hidden
@RestController
@RequestMapping("/ua/notice/refund")
public class RefundNoticeController {

    @Autowired
    private PayManager payManager;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 退款结果通知
     */
    @RequestMapping("/order/{paySysType}/{payType}")
    public ResponseEntity<String> result(HttpServletRequest request, @RequestBody(required = false) String data, @PathVariable Integer payType, @PathVariable Integer paySysType) throws WxPayException, UnsupportedEncodingException {
        RefundInfoResultBO refundInfoResultBO = payManager.validateAndGetRefundInfo(request, paySysType, PayType.instance(payType), data);
        RefundInfo refundInfo;
        if(Objects.equals(paySysType, PaySysType.DEFAULT.value())) {
            // 如果普通支付是预售订单时，此处会有两个,此时会有两种情况
            // 情况1，都是微信支付此时只需要退款成功即可
            // 情况2，其中一个是余额支付，因为这是直接成功没有回调，所以同上
            refundInfo = refundInfoService.getByRefundIdAndWxPay(refundInfoResultBO.getRefundId());
        }else{
            refundInfo = refundInfoService.getByRefundId(refundInfoResultBO.getRefundId());
        }
        if (!refundInfoResultBO.getRefundSuccess()) {
            if (StrUtil.isNotBlank(refundInfoResultBO.getCallbackContent())) {
                refundInfo.setCallbackContent(refundInfoResultBO.getCallbackContent());
                refundInfo.setCallbackTime(new Date());
                refundInfoService.updateByIdPayId(refundInfo);
            }
            return ResponseEntity.ok(refundInfoResultBO.getSuccessString());
        }
        refundInfoService.refundSuccess(refundInfo);
        return ResponseEntity.ok(refundInfoResultBO.getSuccessString());
    }

}
