package org.springblade.gateway.client_gateway.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.bbc.config.LdtBbcConfig;
import org.springblade.bbc.request.SignAuthenticationRequest;
import org.springblade.bbc.util.BbcSignUtil;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.enums.ResCode;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.gateway.client_gateway.entity.dto.LoginDto;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * @author: lianghanqiang
 * @description:
 * @since: 8/24/21 -- 3:10 PM
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/client/user")
@AllArgsConstructor
public class ClientUserController {

	private ILoginUserService loginUserService;
	private IBillsService billsService;
	private LdtBbcConfig ldtBbcConfig;

	@PostMapping("/login")
	@ApiOperation("C端小程序用户登录")
	@SneakyThrows
	public R userLogin(@RequestBody LoginDto loginDto) {
		LoginUser user = loginUserService.getOne(new QueryWrapper<LoginUser>().lambda().eq(LoginUser::getOpenid, loginDto.getOpenid()));
		if (user == null) {
			user = new LoginUser();
			user.setUserType(AppConstant.USER_TYPE.普通用户.name());
			user.setAvatar(loginDto.getAvatar());
			user.setBalance(BigDecimal.ZERO);
			user.setChannelPoint(BigDecimal.ZERO);
			user.setNickName(loginDto.getNickName());
			user.setOpenid(loginDto.getOpenid());
			user.setSex(StringUtil.isBlank(loginDto.getGender()) ? "0" : loginDto.getGender());
			Assert.isTrue(loginUserService.save(user), () -> {
				throw new ServiceException(ResCode.PAY_SCENE_ERROR);
			});
		}
		return R.data(user);
	}

	/**
	 * 获取BBC H5 商城认证链接
	 */
	@GetMapping("/getBccH5SignAuthentication")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "获取BBC_H5商城认证链接", notes = "传入signAuthenticationRequest")
	public R<String> getBccH5SignAuthentication(SignAuthenticationRequest signAuthenticationRequest) {
		//设置APP
		signAuthenticationRequest.setType(ldtBbcConfig.getType());

		//进行参数签名
		BbcSignUtil.paramsSignAuthentication(signAuthenticationRequest);

		//拼接参数
		String params = URLUtil.buildQuery(BeanUtil.beanToMap(signAuthenticationRequest), StandardCharsets.UTF_8);

		//返回链接
		return R.data(new StringBuilder(ldtBbcConfig.getUrl()).append("?").append(params).toString());
	}

}
