package com.heketai.website.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heketai.website.common.result.BaseResult;
import com.heketai.website.entity.*;
import com.heketai.website.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xjl
 * @since 2019-11-13
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysRoleMenuService roleMenuService;
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;
    private String fKey = "4BAF93F9-FE61-8F5E7435-501C2D5011C2";

    @RequestMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    public BaseResult<SysUser> getUserInfo(@RequestParam Integer id) {

        String key ="97A87D66-4754-EC4E-8A0B-EE933EAD22B4";
        Object obj = redisTemplate.boundHashOps(fKey).get(key);
        if (null != obj){
            SysUser sysUser1 =  JSON.parseObject(obj.toString(), SysUser.class);
            return BaseResult.successWithData(sysUser1);
        }

        SysUser sysUser1 = sysUserService.selectById(id);
        List<SysUserRole> userRoles = userRoleService.selectList(
                new EntityWrapper<SysUserRole>().eq("sys_user_id", sysUser1.getId())
        );
        List<Integer> roleIds = userRoles.stream().map(SysUserRole::getSysRoleId).collect(Collectors.toList());
        List<SysRole> sysRoles = roleService.selectBatchIds(roleIds);
        List<SysRoleMenu> roleMenus = roleMenuService.findByRoleIds(roleIds);
        List<Integer> menuIds = roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        List<SysMenu> menus = menuService.selectBatchIds(menuIds);
        sysUser1.setRoleList(sysRoles);
        sysUser1.setMenuList(menus);

        redisTemplate.boundHashOps(fKey).put(key,JSON.toJSONString(sysUser1));
        return BaseResult.successWithData(sysUser1);
    }
}
