package org.springblade.gateway.client_gateway.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
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.util.Objects;

/**
 * @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;

	@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);
	}

}
