
package com.tmerclub.cloud.user.controller.app;


import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.TokenInfoVO;
import com.tmerclub.cloud.api.biz.feign.NotifyFeignClient;
import com.tmerclub.cloud.api.user.bo.UidAndUserIdBO;
import com.tmerclub.cloud.api.user.dto.UserRegisterDTO;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * 用户信息
 *
 * @author tmerclub
 */
@RestController
@RequestMapping("/ua/user/register")
@Tag(name = "app-用户注册接口")
public class UserRegisterController {

    @Autowired
    private UserService userService;
    @DubboReference
    private AccountFeignClient accountFeignClient;
    @DubboReference
    private NotifyFeignClient notifyFeignClient;

    /**
     * 注册的头像昵称有几个值得注意的地方：
     * 1. 如果是微信公众号 or 小程序注册，在注册之前，也就是在进入页面之前，需要调用SocialLoginController 这里面的尝试登录的接口，如果可以登录就直接登录了。
     * 2. 关于发送验证码
     * 1) 如果用邮箱进行注册就发送邮箱验证码
     * 2) 手机号注册,要发送验证码
     * 3. 当注册成功的时候，已经返回token，相对来说，已经登录了
     */
    @Operation(summary = "注册")
    @PostMapping
    public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterDTO param) {
        // 手机号校验
        ServerResponseEntity<Boolean> validCodeResponse = notifyFeignClient.checkValidCodeByFlag(param.getMobile(), param.getCheckRegisterSmsFlag());
        if (!validCodeResponse.isSuccess() || !validCodeResponse.getData()) {
            return ServerResponseEntity.fail(ResponseEnum.VERIFICATION_CODE_ERROR);
        }
        // 1. 保存账户信息
        UidAndUserIdBO uidAndUserIdBO = userService.save(param.getMobile(), param.getPassword(), null);


        UidInfoBO uidInfoBO = new UidInfoBO();
        uidInfoBO.setAccountUid(uidAndUserIdBO.getUid());
        uidInfoBO.setUserId(uidAndUserIdBO.getUserId());
        uidInfoBO.setSysType(SysTypeEnum.ORDINARY.value());
        uidInfoBO.setIsAdmin(0);
        // 2. 登录
        return accountFeignClient.storeTokenAndGetVo(uidInfoBO);
    }

}
