
package com.tmerclub.cloud.payment.controller;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
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.common.response.ResponseEnum;
import com.tmerclub.cloud.payment.bo.PayInfoResultBO;
import com.tmerclub.cloud.payment.constant.PayEntry;
import com.tmerclub.cloud.payment.constant.PayStatus;
import com.tmerclub.cloud.payment.manager.PayManager;
import com.tmerclub.cloud.payment.manager.PayNoticeManager;
import com.tmerclub.cloud.payment.model.PayInfo;
import com.tmerclub.cloud.payment.model.RefundInfo;
import com.tmerclub.cloud.payment.service.PayInfoService;
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/pay")
public class PayNoticeController {

    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private PayManager payManager;

    @Autowired
    private PayNoticeManager payNoticeManager;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 支付异步回调
     */
    @RequestMapping("/{paySysType}/{payEntry}/{payType}")
    public ResponseEntity<String> notice(HttpServletRequest request,
                                         @PathVariable("paySysType") Integer paySysType,
                                         @PathVariable("payType") Integer payType,
                                         @PathVariable("payEntry") Integer payEntry,
                                         @RequestBody(required = false) String data) throws WxPayException, UnsupportedEncodingException, AlipayApiException {

        PayInfoResultBO payInfoResultBO = payManager.validateAndGetPayInfo(paySysType, request, PayType.instance(payType), data);
        if (Objects.nonNull(payInfoResultBO.getIsAliRefund()) && payInfoResultBO.getIsAliRefund()) {
            RefundInfo refundInfo;
            // 支付宝退款回调
            if(Objects.equals(paySysType, PaySysType.DEFAULT.value())) {
                // 支付宝退款查询预售的退款
                refundInfo = refundInfoService.getByRefundIdAndWxPay(payInfoResultBO.getRefundId());
            }else{
                refundInfo = refundInfoService.getByRefundId(payInfoResultBO.getRefundId());
            }
            if (!payInfoResultBO.getPaySuccess()) {
                if (StrUtil.isNotBlank(payInfoResultBO.getCallbackContent())) {
                    refundInfo.setCallbackContent(payInfoResultBO.getCallbackContent());
                    refundInfo.setCallbackTime(new Date());
                    refundInfoService.updateByIdPayId(refundInfo);
                }
                return ResponseEntity.ok(payInfoResultBO.getSuccessString());
            } else {
                refundInfoService.refundSuccess(refundInfo);
                return ResponseEntity.ok(payInfoResultBO.getSuccessString());
            }
        }

        // 校验订单参数异常，返回未授权
        if (!payInfoResultBO.getPaySuccess()) {
            return ResponseEntity.ok(payInfoResultBO.getSuccessString());
        }

        PayInfo payInfo = payInfoService.getByPayId(payInfoResultBO.getPayId());
        // 已经支付
        if (Objects.equals(payInfo.getPayStatus(), PayStatus.PAYED.value()) || Objects.equals(payInfo.getPayStatus(), PayStatus.REFUND.value())) {
            return ResponseEntity.ok(payInfoResultBO.getSuccessString());
        }
        // 支付金额不对
        if (!Objects.equals(payInfo.getPayAmount(), payInfoResultBO.getPayAmount())) {
            return ResponseEntity.ok(ResponseEnum.UNAUTHORIZED.value());
        }
        if (Objects.equals(payEntry, PayEntry.ORDER.value())) {
            // 订单支付回调
            return payNoticeManager.noticeOrder(payInfoResultBO, payInfo, paySysType);
        } else if (Objects.equals(payEntry, PayEntry.RECHARGE.value())) {
            // 余额充值回调
            return payNoticeManager.noticeRecharge(payInfoResultBO, payInfo);
        } else if (Objects.equals(payEntry, PayEntry.VIP.value())) {
            // 购买会员回调
            return payNoticeManager.noticeBuyVip(payInfoResultBO, payInfo);
        } else if (Objects.equals(payEntry, PayEntry.SHOP_BALANCE_PAY_PURCHASE.value())) {
            // 商家余额支付采购金额(通联支付独有)
            return payNoticeManager.noticeBalancePay(payInfoResultBO, payInfo);
        } else if (Objects.equals(payEntry, PayEntry.SHOP_BALANCE_PAY_REFUND_SPREAD.value())) {
            // 商家余额支付退款自行处理费用(通联支付独有)
            return payNoticeManager.noticeShopBalancePayRefundSpread(payInfoResultBO, payInfo);
        } else if (Objects.equals(payEntry, PayEntry.ORDER_SETTLEMENT.value())) {
            // 订单结算(通联支付独有)
            return payNoticeManager.settlementOrderByAllinpay(payInfoResultBO, payInfo);
        }
        return ResponseEntity.ok(ResponseEnum.UNAUTHORIZED.value());
    }

}
