package com.starry.admin.modules.system.controller;

import com.starry.admin.common.component.JwtToken;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.modules.system.module.entity.SysMenuEntity;
import com.starry.admin.modules.system.module.entity.SysUserEntity;
import com.starry.admin.modules.system.service.LoginService;
import com.starry.admin.modules.system.service.SysMenuService;
import com.starry.admin.modules.system.vo.LoginVo;
import com.starry.admin.modules.system.vo.RouterVo;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.redis.CaptchaService;
import com.starry.common.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
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.RestController;

/**
 * @author admin
 */
@Api(tags = "登录管理", description = "用户登录及认证相关接口")
@RestController
public class LoginController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value(value = "${xl.login.authCode.enable}")
    private boolean needAuthCode;
    @Resource
    private LoginService loginService;
    @Resource
    private SysMenuService menuService;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private JwtToken jwtToken;

    @ApiOperation(value = "旧版登录", notes = "用户登录接口，返回Token")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Map.class),
            @ApiResponse(code = 500, message = "登录失败，用户名或密码错误")})
    @PostMapping(value = "old-login")
    public R login(@ApiParam(value = "登录信息", required = true) @RequestBody LoginVo loginVo) {
        // 只有开启了验证码功能才需要验证
        if (needAuthCode) {
            String msg = captchaService.checkImageCode(loginVo.getNonceStr(), loginVo.getValue());
            if (StringUtils.isNotBlank(msg)) {
                return R.error(msg);
            }
        }
        String token = loginService.login(loginVo.getUserName(), loginVo.getPassWord());
        if (StringUtils.isBlank(token)) {
            return R.error("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return R.ok(tokenMap);
    }

    @ApiOperation(value = "获取用户信息", notes = "登录后获取当前用户的详细信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Map.class),
            @ApiResponse(code = 401, message = "未授权")})
    @GetMapping("get-info")
    public R getInfo() {
        SysUserEntity user = SecurityUtils.getLoginUser().getUser();
        if (user == null) {
            return R.unauthorized();
        }
        // 权限集合
        Set<String> permissions = loginService.getMenuPermission(user);
        // 角色集合
        Set<String> roles = loginService.getRolePermission(user);
        Map<String, Object> data = new HashMap<>();
        data.put("userCode", user.getUserCode());
        data.put("name", user.getRealName());
        data.put("avatar", user.getAvatar());
        data.put("roles", roles);
        data.put("permissions", permissions);
        return R.ok(data);
    }

    @ApiOperation(value = "获取路由信息", notes = "登录后获取当前用户的菜单路由信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = RouterVo.class, responseContainer = "List")})
    @GetMapping("get-routers")
    public R getRoutes() {
        List<SysMenuEntity> menus = menuService.selectMenuTreeByUserId(SecurityUtils.getUserId());
        List<RouterVo> routerVos = menuService.buildMenus(menus);
        return R.ok(routerVos);
    }

    @ApiOperation(value = "新版登录", notes = "新版用户登录接口，支持租户")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Map.class),
            @ApiResponse(code = 500, message = "登录失败，验证码错误或用户名密码错误")})
    @PostMapping(value = "login")
    public R newLogin(@ApiParam(value = "登录信息", required = true) @RequestBody LoginVo loginVo) {
        // 只有开启了验证码功能才需要验证
        if (needAuthCode) {
            String msg = captchaService.checkImageCode(loginVo.getNonceStr(), loginVo.getValue());
            if (StringUtils.isNotBlank(msg)) {
                return R.error(msg);
            }
        }
        // 用户登录
        LoginUser userInfo = loginService.newLogin(loginVo.getUserName(), loginVo.getPassWord(),
                loginVo.getTenantKey());
        Map<String, Object> tokenMap = jwtToken.createToken(userInfo);
        return R.ok(tokenMap);
    }

    // @ApiOperation(value = "租户登录")
    // @PostMapping(value = "tenant/login")
    // public R TenantLoginVo(@RequestBody TenantLoginVo loginVo) {
    // // 只有开启了验证码功能才需要验证
    // if (needAuthCode) {
    // String msg = captchaService.checkImageCode(loginVo.getNonceStr(),
    // loginVo.getValue());
    // if (StringUtils.isNotBlank(msg)) {
    // return R.error(msg);
    // }
    // }
    // // 用户登录
    // LoginUser userInfo = loginService.tenantLogin(loginVo.getTenantkey(),
    // loginVo.getUserName(), loginVo.getPassWord());
    // Map<String, Object> tokenMap = jwtToken.createToken(userInfo);
    // return R.ok(tokenMap);
    // }
}
