package org.springblade.gateway.common_gateway.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.PaymentType;
import org.springblade.common.enums.ResCode;
import org.springblade.common.enums.WithdrawType;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.api.R;
import org.springblade.payment.entity.PayParam;
import org.springblade.payment.plugin.PaymentBuilder;
import org.springblade.payment.plugin.Withdraw;
import org.springblade.yeePay.service.YeePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @Author July
 * @Description 提现模式
 * @Date 2021/10/22 16:23
 */
@Slf4j
@Api(tags = "提现模块")
@RestController
@RequestMapping("/withdraw")
public class WithdrawController {

	@Autowired
	PaymentBuilder paymentBuilder;
	@Autowired
	YeePayService yeePayService;
	@Autowired
	BladeLogger bladeLogger;

	@ApiOperation("提现")
	@GetMapping("/{type}/{withdrawType}")
	public R payOrder(@PathVariable String type, @PathVariable String withdrawType, @Validated PayParam payParam) {
		//获取支付插件
		Withdraw withdraw = pluginBuild(type);
		//解析支付场景
		WithdrawType scene = Optional.of(WithdrawType.valueOf(withdrawType))
			.orElseThrow(() -> new ServiceException(ResCode.PAY_SCENE_ERROR));
		switch (scene) {
			case BALANCE_WITHDRAW:
				return withdraw.userWithdraw(payParam);
			case POINT_WITHDRAW:
				return withdraw.userPointWithdraw(payParam);
			default:
				return null;
		}
	}

	@ApiLog
	@ApiOperation(value = "余额提现回调")
	@RequestMapping(value = "/csurl/{withdrawType}", method = {RequestMethod.GET, RequestMethod.POST})
	public String balanceCallback(HttpServletRequest request, @PathVariable String withdrawType) {
		bladeLogger.info(withdrawType + "余额提现回调", request.getParameterMap().toString());
		//获取支付插件
		Withdraw payment = pluginBuild(withdrawType);
		payment.csUrl(request);
		return "SUCCESS";
	}

	@ApiLog
	@ApiOperation(value = "积分提现回调")
	@RequestMapping(value = "/callback/{withdrawType}", method = {RequestMethod.GET, RequestMethod.POST})
	public String callback(HttpServletRequest request, @PathVariable String withdrawType) {
		bladeLogger.info(withdrawType + "积分提现回调", request.getParameterMap().toString());
		//获取支付插件
		Withdraw payment = pluginBuild(withdrawType);
		payment.callback(request);
		return "SUCCESS";
	}

	private Withdraw pluginBuild(String paymentType) {
		log.info("PaymentType枚举值：{}", PaymentType.values());
		return paymentBuilder.fetchWithdrawPlugin(
			Optional.of(PaymentType.valueOf(paymentType))
				.orElseThrow(() -> new ServiceException(ResCode.PAY_TYPE_ERROR))
		);
	}

}
