package com.ruoyi.web.controller.system;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.framework.datasource.DynamicDataSourceService;
import com.ruoyi.web.primary.entity.DatabaseMetadata;
import com.ruoyi.web.primary.service.IDatabaseMetadataService;
import com.ruoyi.web.v2.v1.entity.UserAccount;
import com.ruoyi.web.v2.v1.service.IUserAccountService;
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.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

import javax.sql.DataSource;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IDatabaseMetadataService metadataService;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
//        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());

//        DatabaseMetadata databaseMetadata = databaseMetadataService.selectByName(loginBody.getDbName());
        DatabaseMetadata databaseMetadata = databaseMetadataService.selectByAccountId(loginBody.getUserId());
        if (ObjectUtil.isEmpty(databaseMetadata)){
            throw new Exception("账号不存在");
        }
        UserAccount userAccount = userAccountService.getOne(new QueryWrapper<UserAccount>().eq("user_id", databaseMetadata.getUserId()));
        //根据现场需求，去除验证码
        swichDb(databaseMetadata.getDbName());
        String token = loginService.loginNoCaptcha(loginBody.getUsername(), loginBody.getPassword(), databaseMetadata.getDbName()
                ,userAccount.getUserId(),userAccount.getAccountBalance(),userAccount.getExperienceBalance(),
                userAccount.getAnimalType() ,databaseMetadata.getVersionName(),databaseMetadata.getVersion());

        ajax.put(Constants.TOKEN, token);

        return ajax;
    }
    @Autowired
    private DynamicDataSourceService dynamicDataSourceService;
    @Autowired
    private IDatabaseMetadataService databaseMetadataService;
    @Autowired
    private IUserAccountService userAccountService;
    /**
     * 无验证码登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginNoCaptcha")
    public AjaxResult loginNoCaptcha(@RequestBody LoginBody loginBody ) throws Exception {

        DatabaseMetadata databaseMetadata = databaseMetadataService.selectByAccountId(loginBody.getUserId());
        UserAccount userAccount = userAccountService.getOne(new QueryWrapper<UserAccount>().eq("user_id", databaseMetadata.getUserId()));

        AjaxResult ajax = AjaxResult.success();
        swichDb(databaseMetadata.getDbName());
        // 生成令牌
        String token = loginService.loginNoCaptcha(loginBody.getUsername(), loginBody.getPassword(),databaseMetadata.getDbName()
                ,userAccount.getUserId(),userAccount.getAccountBalance(),userAccount.getExperienceBalance(),
                userAccount.getAnimalType(),databaseMetadata.getVersionName(),databaseMetadata.getVersion() );


        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    private void swichDb(String  dbName) throws Exception {
        DatabaseMetadata databaseMetadata = metadataService.selectByName(dbName);

        if (databaseMetadata == null || databaseMetadata.getDbStatus() ==0 ) {
            throw new Exception("数据库不存在或已禁用");
        }
        if (!dynamicDataSourceService.switchDataSource(dbName)) {

            throw new Exception("无法连接到用户数据库");
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }

        user.setAccountId(loginUser.getAccountId());
        user.setAccountBalance(loginUser.getAccountBalance());
        user.setExperienceBalance(loginUser.getExperienceBalance());
        user.setAnimalType(loginUser.getAnimalType());

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("version", loginUser.getVersion());
        ajax.put("versionName", loginUser.getVersionName());
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
