package org.springblade.gateway.client_gateway.controller;

import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.enums.*;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.client_gateway.entity.dto.ClientTradeDto;
import org.springblade.gateway.shop_gateway.service.IAppShopService;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.payment.handle.Trade;
import org.springblade.payment.handle.entity.Order;
import org.springblade.payment.handle.handler.CancelTradeHandle;
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.math.BigDecimal;

/**
 * @author: lianghanqiang
 * @description: 用户交易模块
 * @since: 9/1/21 -- 11:16 AM
 */

@Api(tags = "用户交易模块")
@RestController
@RequestMapping("/client/trade")
@AllArgsConstructor
public class ClientTradeController {

	private ILoginUserService loginUserService;
	private IBillsService billsService;
	private Trade trade;
	private IAppShopService appShopService;
	private CancelTradeHandle cancelTradeHandle;

	@ApiOperation("用户扫商家二维码下单")
	@PostMapping("/scanPay")
	public R scanPay(@RequestBody ClientTradeDto clientTradeDto) {
		synchronized (clientTradeDto.getUserId().toString().intern()) {
			LoginUser loginUser = loginUserService.getById(clientTradeDto.getUserId());
			Assert.notNull(loginUser, () -> {
				throw new ServiceException(ResCode.USER_NOT_FOUNT);
			});

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

		/*SuccessParams successParams = null;

		try {
			successParams = trade.tradeForScanPay(order, clientTradeDto.getChannelId());
		} catch (Exception e) {
			e.printStackTrace();
			throw new TradeException(ResCode.TRADE_ERROR, successParams);
		}*/
			SuccessParams successParams = trade.tradeForScanPay(order, clientTradeDto.getChannelId());
			return R.data(successParams);
		}
	}

	@ApiOperation("取消支付交易")
	@PostMapping("/cancelTrade")
	public R cancelTrade(@RequestBody SuccessParams successParams) {
		cancelTradeHandle.handle(successParams);
		return R.status(true);
	}

	@ApiOperation("用户扫商家二维码微信下单")
	@PostMapping("/scanPayByWeChat")
	public R scanPayByWeChat(@RequestBody ClientTradeDto clientTradeDto) {
		String tenantId = appShopService.getTenantId(clientTradeDto.getShopId());

		Bills bills = new Bills();
		bills.setPointNum(BigDecimal.ZERO);
		bills.setFee(BigDecimal.ZERO);
		bills.setPointFee(BigDecimal.ZERO);
		bills.setBalanceNum(BigDecimal.ZERO);
		bills.setPrice(clientTradeDto.getMoney());
		bills.setPayPlugin(PaymentType.YEE_PAY.name());
		bills.setReceiveId(clientTradeDto.getShopId());
		bills.setTitle("扫码付款");
		bills.setExTime(clientTradeDto.getExpireTime());
		bills.setPayStatus(AppConstant.BillPayStatus.待付款.name());
		bills.setPayScene(PaymentScene.SCAN_CODE.name());
		bills.setCost(clientTradeDto.getMoney());
		bills.setType(OrderType.WECHAT_PAY.name());
		bills.setDiscount(BigDecimal.ONE);
		bills.setTenantId(tenantId);


		Assert.isTrue(billsService.saveOrUpdate(bills), () -> {
			throw new ServiceException("订单异常！");
		});

		//支付参数
		SuccessParams successParams = SuccessParams.builder()
			.orderType(OrderType.USER_PAY.name())
			.status(AppConstant.BillPayStatus.待付款.name())
			.totalPrice(bills.getTotalPrice())
			.bills(bills)
			.shopId(bills.getReceiveId())
			.tenantId(bills.getTenantId())
			.build();

		PaymentCache.putSuccessParams(Convert.toStr(successParams.getBills().getId()), successParams);
		return R.data(bills);
	}

}
