package com.org.system.controller;

import cn.hutool.core.util.StrUtil;
import com.org.system.annotation.Log;
import com.org.system.entity.LoginBody;
import com.org.system.entity.vo.PersonVo;
import com.org.system.enums.BusinessType;
import com.org.system.service.SysLoginService;
import com.org.utils.AjaxResult;
import com.org.utils.Constants;
import com.org.utils.SecurityUtil;
import com.org.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
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.RestController;

import java.util.Map;

/** 登录验证 **/
@Slf4j
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @Log(title = "登陆系统", businessType = BusinessType.LOGIN)
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        log.info("SysLoginController - login loginBody:{}", loginBody);

        if(loginBody == null) throw new CustomException("未找到登陆信息");

        if(StrUtil.isEmpty(loginBody.getUsername()) || StrUtil.isEmpty(loginBody.getPassword()))
            throw new CustomException("用户名或密码不能为空");

        // 生成令牌
        Map<String, String> result = sysLoginService.login(loginBody, true);

        return AjaxResult.success().put(Constants.TOKEN, result.get("token"))
                                    .put("identity", result.get("identity"));
    }

    @PostMapping("/getLoginUser")
    @Log(title = "获取当前登录用户信息", businessType = BusinessType.LOGIN)
    public AjaxResult getLoginUser(){
        log.info("SysLoginController - getLoginUser userId:{}", SecurityUtil.getUserId());

        sysLoginService.setLoginUserRole();

        return AjaxResult.success(SecurityUtil.getLoginUser());
    }

    @PostMapping("/getUserInfo")
    @Log(title = "获取当前用户信息", businessType = BusinessType.LOGIN)
    public AjaxResult getUserInfo(){
        log.info("SysLoginController - getUserInfo userId:{}", SecurityUtil.getUserId());

        PersonVo personVo = sysLoginService.getUserInfo(SecurityUtil.getUserId());

        return AjaxResult.success(personVo);
    }

}
