package cn.ezhizao.project.system.controller;

import cn.ezhizao.common.constant.Constants;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.security.LoginBody;
import cn.ezhizao.framework.security.service.SysLoginService;
import cn.ezhizao.framework.security.service.SysPermissionService;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.domain.SysDeptUser;
import cn.ezhizao.project.system.domain.SysMenu;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysDeptUserService;
import cn.ezhizao.project.system.service.ISysMenuService;
import cn.ezhizao.project.tenant.domain.BizTenant;
import cn.ezhizao.project.tenant.service.IBizTenantService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

    @Resource
    private IBizTenantService tenantService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;
    @Resource
    private ISysDeptUserService deptUserService;
    @Resource
    private ISysDeptService deptService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Log(title = "登录", businessType = BusinessType.SELECT)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 正常登录
        Map<String, Object> loginResult = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, loginResult.get(Constants.TOKEN));
        ajax.put(Constants.TENANT_ID, loginResult.get(Constants.TENANT_ID));
        ajax.put(Constants.TENANT_NAME, loginResult.get(Constants.TENANT_NAME));
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @Log(title = "用户信息查询", businessType = BusinessType.SELECT)
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        List<SysDeptUser> userDepts = deptUserService.query().eq("user_id", user.getUserId()).list();
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts = depts.stream().filter(e -> userDepts.stream().anyMatch(t -> t.getDeptId().equals(e.getDeptId()))).collect(Collectors.toList());
        ajax.put("depts", depts);
        return ajax;
    }

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

    /**
     * 根据用户名获取租户列表
     *
     * @param userName
     * @return
     */
    @Log(title = "根据用户名获取租户列表", businessType = BusinessType.SELECT)
    @GetMapping("/snms/getTenantList/{userName}")
    public AjaxResult getTenantList(@PathVariable("userName") String userName) {
        List<BizTenant> bizTenantList = loginService.getTenantList(userName);
        if (bizTenantList == null || bizTenantList.size() == 0) {
            return error("未找到企业信息！请先注册并认证企业信息");
        } else {
            return success(bizTenantList);
        }
    }

    /**
     * 根据企业名称 模糊查询租户
     *
     * @param orgName
     * @return
     */
    @Log(title = "根据企业名称 模糊查询租户", businessType = BusinessType.SELECT)
    @GetMapping("/snms/getTenantListByOrgName/{orgName}")
    public AjaxResult getTenantListByOrgName(@PathVariable("orgName") String orgName) {
        return success(tenantService.query().like("org_name", orgName).list());
    }
}
