package org.springblade.gateway.shop_gateway.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.enums.ResCode;
import org.springblade.common.utils.OtpUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.payment.handle.Trade;
import org.springblade.payment.handle.entity.Order;
import org.springblade.gateway.shop_gateway.entity.dto.CodeOrder;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author: lianghanqiang
 * @description:
 * @since: 8/25/21 -- 6:23 PM
 */
@RestController
@RequestMapping("/shopTrade")
@Api(tags = "小B端交易模块")
@AllArgsConstructor
public class ShopTradeController {

	private ILoginUserService loginUserService;
	private Trade trade;

	@ApiOperation("授权码下单")
	@PostMapping("initOrderByCode")
//	@SneakyThrows
	public R initOrderByCode(@RequestBody CodeOrder codeOrder){

		//解析校验授权码
		Map<String, String> decodeParams = OtpUtils.decodeParams(codeOrder.getAuthCode());

//		Assert.isTrue(OtpUtils.validate(decodeParams.get(OtpUtils.PARAMS_ID),decodeParams.get(OtpUtils.PARAMS_SECRET)),
//			()->{ throw new ServiceException(ResCode.SECRET_VALIDATE_ERROR); });

		LoginUser loginUser = loginUserService.getById(decodeParams.get(OtpUtils.PARAMS_ID));
		Assert.notNull(loginUser,() -> {throw  new ServiceException(ResCode.USER_NOT_FOUNT);});

		//处理订单
		Order order = Order.builder()
			.appId(codeOrder.getAppId())
			.billsTitle(codeOrder.getBillsTitle())
			.loginUser(loginUser)
			.money(codeOrder.getMoney())
			.expireTime(codeOrder.getExpireTime())
			.secret(codeOrder.getSecret())
			.shopId(codeOrder.getShopId())
			.openId(codeOrder.getOpenId())
			.build();


		try {
			trade.trade(order,codeOrder.getChannelId());
		} catch (Exception e) {
			e.printStackTrace();
			throw  new ServiceException(ResCode.TRADE_ERROR);
		}

		return R.success("交易成功！");

	}

}
