package com.ruoyi.web.modules.app.controller;

import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.app.domain.AppUserRegisterBody;
import com.ruoyi.web.modules.app.service.IAppUserRegisterService;

/**
 * 小程序认证（注册等，匿名访问）
 */
@Anonymous
@RestController
@RequestMapping("/app/auth")
public class AppAuthController extends BaseController
{
    @Autowired
    private IAppUserRegisterService appUserRegisterService;

    /**
     * 校验登录名是否可用
     */
    @GetMapping("/usernameAvailable")
    public AjaxResult usernameAvailable(@RequestParam("userName") String userName)
    {
        if (StringUtils.isEmpty(userName))
        {
            return error("用户名不能为空");
        }
        boolean available = appUserRegisterService.isUsernameAvailable(userName);
        Map<String, Object> data = new HashMap<>(2);
        data.put("userName", userName.trim());
        data.put("available", available);
        return success(data);
    }

    /**
     * 用户注册（昵称、用户名、密码；默认角色 role_id=2）
     */
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody AppUserRegisterBody body)
    {
        Long userId = appUserRegisterService.register(body);
        Map<String, Object> data = new HashMap<>(2);
        data.put("userId", userId);
        data.put("userName", body.getUserName().trim());
        return AjaxResult.success("注册成功", data);
    }
}
