package org.springblade.modules.payment.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.PaymentScene;
import org.springblade.common.enums.PaymentType;
import org.springblade.common.enums.ResCode;
import org.springblade.common.exception.BizException;
import org.springblade.core.tool.api.R;
import org.springblade.modules.payment.entity.PayParam;
import org.springblade.modules.payment.entity.SuccessParams;
import org.springblade.modules.payment.plugin.Payment;
import org.springblade.modules.payment.plugin.PaymentBuilder;
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: lianghanqiang
 * @description:  支付模块控制器
 * @since: 7/29/21 -- 1:55 PM
 */
@Api(tags = "支付模块")
@RestController
@RequestMapping("/payment")
public class PaymentController {

	@Autowired
	PaymentBuilder paymentBuilder;

	@ApiOperation("订单支付")
	@GetMapping("/payOrder/{paymentType}/{paymentScene}")
	public R payOrder(
		@PathVariable String paymentType,
		@PathVariable String paymentScene,
		@Validated PayParam payParam
	){
		//获取支付插件
		Payment payment =  pluginBuild(paymentType);
		//解析支付场景
		PaymentScene scene = Optional.ofNullable(PaymentScene.valueOf(paymentScene))
				.orElseThrow(()-> new BizException(ResCode.PAY_SCENE_ERROR));
		switch (scene){
			case PAY_CODE:
				return payment.payCode(payParam);
			case SCAN_CODE:
				return payment.nativePay(payParam);
			case TRANSFER:
				return payment.transfer(payParam);
			case MINI_PROGRAM:
				return payment.miniProgram(payParam);
			default:
		}
		return null;
	}

	@GetMapping("support")
	@ApiOperation("获取支付类型列表")
	public R<PaymentType[]> getSupportList(){
		return R.data(PaymentType.values());
	}


	@ApiOperation(value = "支付回调")
	@RequestMapping(value = "/callback/{paymentType}", method = {RequestMethod.GET, RequestMethod.POST})
	public R  callback(HttpServletRequest request, @PathVariable String paymentType) {
		System.out.println("我是回调:");
		//获取支付插件
		Payment payment = pluginBuild(paymentType);
		payment.callback(request);
		return R.success("操作成功");
	}


	private Payment pluginBuild(String paymentType){
		return paymentBuilder.fetchPaymentPlugin(
			Optional.ofNullable(PaymentType.valueOf(paymentType))
				.orElseThrow(()-> new BizException(ResCode.PAY_TYPE_ERROR))
		);
	}
}
