
package com.tmerclub.cloud.payment.controller.user;


import com.alipay.api.AlipayApiException;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.tmerclub.cloud.api.auth.bo.LoginInfoBO;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.auth.feign.TokenFeignClient;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BooleanUtil;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.payment.bo.PayInfoBO;
import com.tmerclub.cloud.payment.constant.PayEntry;
import com.tmerclub.cloud.payment.dto.PayInfoDTO;
import com.tmerclub.cloud.payment.manager.PayManager;
import com.tmerclub.cloud.payment.service.PayInfoService;
import com.tmerclub.cloud.payment.vo.PaySettlementConfigVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author tmerclub
 */
@RestController
@RequestMapping("/pay")
@Tag(name = "订单接口")
@RefreshScope
public class PayController {

    @Autowired
    private PayInfoService payInfoService;
    @Autowired
    private PayManager payManager;
    @DubboReference
    private TokenFeignClient tokenFeignClient;
    @DubboReference
    private ConfigFeignClient configFeignClient;
    @Value("${application.domainUrl}")
    private String domainUrl;

    /**
     * 支付接口
     */
    @PostMapping("/order")
    @Operation(summary = "根据订单号进行支付", description = "根据订单号进行支付")
    public ServerResponseEntity<?> pay(@Valid @RequestBody PayInfoDTO payParam) throws AlipayApiException, WxPayException {
        ServerResponseEntity<String> configResponse = configFeignClient.getConfig(Constant.PAY_SETTLEMENT_CONFIG);
        if (!configResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        PaySettlementConfigVO paySettlementConfigVO = Json.parseObject(configResponse.getData(), PaySettlementConfigVO.class);
        LoginInfoBO loginInfoBO = tokenFeignClient.getLoginInfo();
        Long userId = AuthUserContext.getUserId();
        String bizUserId = loginInfoBO.getBizUserId();
        PayInfoBO payInfo = payInfoService.pay(userId, payParam, bizUserId);
        payInfo.setBizUserId(bizUserId);
        payInfo.setPayType(payParam.getPayType());
        payInfo.setUserId(userId.toString());
//        // 回调地址
        payInfo.setApiNoticeUrl(domainUrl + "/ua/notice/pay/" + paySettlementConfigVO.getPaySettlementType() + "/" + PayEntry.ORDER.value() +"/" + payParam.getPayType());
        payInfo.setReturnUrl(payParam.getReturnUrl());
        payInfo.setSystemType(payParam.getSystemType());

        return payManager.doPay(payInfo);
    }

    /**
     * 支付预售订单尾款
     */
    @PostMapping("/payBalance")
    @Operation(summary = "根据订单号进行支付尾款", description = "根据订单号进行支付尾款")
    public ServerResponseEntity<?> payBalance(@Valid @RequestBody PayInfoDTO payParam) throws AlipayApiException, WxPayException {
        ServerResponseEntity<String> configResponse = configFeignClient.getConfig(Constant.PAY_SETTLEMENT_CONFIG);
        if (!configResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        PaySettlementConfigVO paySettlementConfigVO = Json.parseObject(configResponse.getData(), PaySettlementConfigVO.class);

        LoginInfoBO loginInfoBO = tokenFeignClient.getLoginInfo();
        Long userId = AuthUserContext.getUserId();

        PayInfoBO payInfo = payInfoService.payPreSaleBalance(userId, payParam);
        payInfo.setBizUserId(loginInfoBO.getBizUserId());
        payInfo.setPayType(payParam.getPayType());
        // 回调地址
        payInfo.setApiNoticeUrl(domainUrl + "/ua/notice/pay/" + paySettlementConfigVO.getPaySettlementType() + "/" + PayEntry.ORDER.value() + "/" + payParam.getPayType());
        payInfo.setReturnUrl(payParam.getReturnUrl());
        payInfo.setUserId(userId.toString());
        payInfo.setSystemType(payParam.getSystemType());
        return payManager.doPay(payInfo);
    }

    @GetMapping("/isPay/{payEntry}/{orderIds}/{payAmountType}")
    @Operation(summary = "根据订单号查询该订单是否已经支付", description = "根据订单号查询该订单是否已经支付")
    @Parameter(name = "payAmountType", description = "支付金额类型，0.付定金or普通订单付款 1.付尾款（定金预售订单独有）", required = true)
    public ResponseEntity<Boolean> isPay(@PathVariable Integer payEntry, @PathVariable String orderIds, @PathVariable Integer payAmountType) {
        Long userId = AuthUserContext.get().getUserId();

        Integer isPay = payInfoService.isPay(orderIds, userId, payEntry, payAmountType);
        return ResponseEntity.ok(BooleanUtil.isTrue(isPay));
    }


}
