package com.ruoyi.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.core.domain.AjaxResult;
import com.ruoyi.common.core.core.domain.model.LoginUser;
import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.*;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.core.core.domain.model.LoginBody;
import com.ruoyi.common.core.core.domain.model.RegisterBody;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysClient;
import com.ruoyi.web.service.IAuthStrategy;
import com.ruoyi.web.service.SysLoginService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

import static com.ruoyi.system.domain.table.SysClientTableDef.SYS_CLIENT;


/**
 * 认证
 *
 * @author Lion Li
 */
@Slf4j
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
public class AuthController {

    @Resource
    private final SysLoginService loginService;
    @Resource
    private final ISysClientService clientService;
    @Resource
    private final ISysUserService sysUserService;
    @Resource
    private final ISysPermissionService permissionService;
    @Resource
    private ISysMenuService menuService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginBody loginBody) {

        AjaxResult ajax = AjaxResult.success();
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        QueryWrapper query=QueryWrapper.create().from(SYS_CLIENT).where(SYS_CLIENT.CLIENT_ID.eq(clientId));
        SysClient client = clientService.getOne(query);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return AjaxResult.error(MessageUtils.message("auth.grant.type.error"));
        }

        // TODO:校验租户
        //loginService.checkTenant(loginBody.getTenantId());

        // 生成令牌
        String token =IAuthStrategy.login(loginBody, client);
        ajax.put(Constants.TOKEN, token);

        // 登录
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {

        LoginUser loginUser = LoginHelper.getLoginUser();

        //TODO:多租户 超级管理员 如果重新加载用户信息需清除动态租户

        SysUser user = sysUserService.selectUserById(loginUser.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user.getUserId());

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = LoginHelper.getLoginUser();
        // 用户信息
        SysUser user = sysUserService.selectUserById(loginUser.getUserId());
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public AjaxResult logout() {
        loginService.logout();
        return AjaxResult.success("退出成功！");
    }

    /**
     * 用户注册
     */
    @PostMapping("LoginHelper.getUserId()")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        //if (!configService.selectRegisterEnabled(user.getTenantId())) // TODO：注册代码
        {
            return R.fail("当前系统没有开启注册功能！");
        }
//        registerService.register(user);
//        return R.ok();
    }


}
