/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.base.api.entity.SysMenu;
import com.tofly.base.api.entity.User;
import com.tofly.base.entity.*;
import com.tofly.base.entity.System;
import com.tofly.base.service.*;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.*;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.auth.innerCall;
import com.tofly.common.oauth.util.SecurityUtils;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@RestController
@RequestMapping("/user")
@Api(tags="用户管理")
@Slf4j
public class UserController {

    @Value("${user.avatar}")
    private String avatarPath;

    @Autowired
    private   UserService userService;

    @Autowired
    private SourceService sourceService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private  CacheManager cacheManager;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private BaseSysmenuService baseSysmenuService;


    @GetMapping("/userSyslist" )
    @ApiOperation(value = "查询用户系统信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysId", value = "子系统id", required = true, dataType = "String")
    })
    public ResultRespone userlist(String sysId) {
        List<UserRole> list = userRoleService.list(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId, SecurityUtils.getUserId()));
        Set<String> set=new HashSet<>();
        if(list.isEmpty()){
            return ResultRespone.success(set);
        }
        List<Role> list1 = roleService.list(Wrappers.<Role>lambdaQuery()
                .eq(Role::getSysId, sysId)
                .in(Role::getId, list.stream().map(UserRole::getRoleId).collect(Collectors.toList())));
        list1.stream().forEach(role->{
            String sysids = role.getTreeValue();
            String[] split = sysids.split(",");
            set.addAll(Arrays.asList(split));
        });
        return ResultRespone.success(set);
    }

    @GetMapping("/userlistByTree" )
    @ApiOperation(value = "查询用户系统信息(树状结构)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysId", value = "子系统id", required = true, dataType = "String")
    })
    public ResultRespone userlistByTree(String sysId) {
        if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())){
            return ResultRespone.success(baseSysmenuService.getTreeSys(sysId));
        }
        List<UserRole> list = userRoleService.list(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId, SecurityUtils.getUserId()));
        Set<String> set=new HashSet<>();
        if(list.isEmpty()){
            return ResultRespone.success(set);
        }
        List<Role> list1 = roleService.list(Wrappers.<Role>lambdaQuery()
                .eq(Role::getSysId, sysId)
                .in(Role::getId, list.stream().map(UserRole::getRoleId).collect(Collectors.toList())));
        StringBuilder stringBuilder=new StringBuilder();
        list1.stream().forEach(role->{
            String sysids = role.getTreeValue();
            stringBuilder.append(sysids).append(",");
//            String[] split = sysids.split(",");
//            set.addAll(Arrays.asList(split));
        });

//        List<String> ll=new ArrayList<>();
//        ll.addAll(set);
//        List<BaseSysmenu> menuList=baseSysmenuService.list(Wrappers.<BaseSysmenu>lambdaQuery()
//                .in(BaseSysmenu::getPathId,set));
//        List<MySysMenu> children= JSONObject.parseArray(JSONObject.toJSONString(menuList), MySysMenu.class);
//        List<MySysMenu> children1 = JSONUtil.parTree(children, MySysMenu::getPathId, MySysMenu::getParentPathid, MySysMenu::getChildren);
        return ResultRespone.success(baseSysmenuService.getTreeSys(sysId,stringBuilder.toString()));
    }

    /**
    * 分页查询
    * @param page 分页对象
    * @param user 用户表
    * @return
    */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getUserPage(Page page, @ModelAttribute User user) {
        return ResultRespone.success(userService.page(page, Wrappers.query(user)
                .select(User.class, info -> !"password".equals(info.getColumn())
                        && !"salt".equals(info.getColumn()))));
    }

    /**
     * 分页查询
     * @param page 分页对象
     * @return
     */
    @GetMapping("/pageNew" )
    @ApiOperation(value = "分页查询-新")
    public ResultRespone getUserPageNew(Page page,@ModelAttribute User user) {
        return ResultRespone.success(userService.getUserPage(page,user));
    }

    /**
     * 通过id查询用户表
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
      return ResultRespone.success(userService.getUserById(id));
    }

    /**
     * 新增用户表
     * @param user 用户表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增用户表" )
    @ApiOperation(value = "新增用户表")
    @PostMapping
    public ResultRespone save(MultipartFile file, User user, HttpServletRequest request) {
        User quser=userService.getOne(Wrappers.<User>lambdaQuery()
        .eq(User::getUsername,user.getUsername()));
        if(quser!=null){
            return ResultRespone.failed("该用户名【"+user.getUsername()+"】已经存在，不能新增");
        }

        if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(user.getUserLevel())){
            return ResultRespone.failed("不能创建超级管理员级别的用户");
        }
//        if(checkHandler(user.getId())){
//            return ResultRespone.failed("当前用户不能修改其他人创建的用户");
//        }

        if(file!=null){
            //String filename=avatarPath+file.getOriginalFilename();
            String filename = avatarPath+IdWorker.getIdStr()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            boolean b= FtpUtil.uploadFile2Ftp(file,filename);
            if(b){
                user.setAvatar(filename);
                user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
                return ResultRespone.success(userService.save(user));
            }else{
                return ResultRespone.failed("上传到FTP失败");
            }
        }else{
            user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
            return ResultRespone.success(userService.save(user));
        }


//        user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
//        return ResultRespone.success(userService.save(user));
    }

    /**
     * 修改用户表
     * @param user 用户表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改用户表" )
    @ApiOperation(value = "修改用户表")
    @PutMapping
    public ResultRespone updateById(MultipartFile file, User user) {

        boolean updatePwd = false;
        String encodePassword=null;

        if(checkHandler(user.getId())){
            return ResultRespone.failed("当前用户不能修改其他人创建的用户");
        }

        if(!StringUtil.isEmpty(user.getPassword())){
            encodePassword=PasswordUtil.passwordEncode(user.getPassword());
            user.setPassword(encodePassword);
            updatePwd=true;
        }
        boolean p =false;
        if(file!=null){
            //String filename=avatarPath+file.getOriginalFilename();
            String filename = avatarPath+IdWorker.getIdStr()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            boolean b= FtpUtil.uploadFile2Ftp(file,filename);
            if(b){
                //查找以前的FTP并删除
                User oldUser=userService.getById(user.getId());
                user.setAvatar(filename);
                p =userService.updateById(user);
                //如果头像不为空，需要清空以前的头像
                if(!StringUtil.isEmpty(oldUser.getAvatar())){
                    FtpUtil.deleteFile(oldUser.getAvatar());
                }
                String username = user.getUsername();
                if(StringUtil.isEmpty(username)){
                    username = (userService.getUserById(user.getId())).getUsername();
                }

                    //调用清除缓存的方法
                    //updatePwd(username,encodePassword);
                updateCache(username,user);

                return ResultRespone.success(true);
            }else{
                return ResultRespone.failed("上传到FTP失败");
            }
        }else{
            p =userService.updateById(user);
            //if(p && updatePwd){
            String username = user.getUsername();
            if(StringUtil.isEmpty(username)){
                username = (userService.getUserById(user.getId())).getUsername();
            }
                //updatePwd(username,encodePassword);
            //}
            updateCache(username,user);
            return ResultRespone.success(true);
        }
      //return ResultRespone.success(userService.updateById(user));
    }

    /**
     * 通过id删除用户表
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除用户表" )
    @ApiOperation(value = "通过ID删除用户表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone removeById(@PathVariable Long id) {

        if(checkHandler(id)){
            return ResultRespone.failed("当前用户不能删除其他人创建的用户");
        }
        //非传统意义删除，修改禁用标志
        User user=new User();
        user.setId(id);
        user.setStatusFlag("0");

        return ResultRespone.success(userService.updateById(user));
    }

    /**
     * 查询当前用户基本信息
     * @return ResultRespone
     */
    @GetMapping("/getInfo" )
    @ApiOperation(value = "查询当前用户基本信息")
    public ResultRespone getInfo() {
        return ResultRespone.success(userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId, SecurityUtils.getUserId())
                .select(User.class, info -> !"password".equals(info.getColumn())
                        && !"salt".equals(info.getColumn()))));
    }



    /**
     * 锁定
     * @return ResultRespone
     */
    @ToFlyAppLog(title="锁定用户" )
    @ApiOperation(value = "锁定用户")
    @PutMapping("/lock")
    public ResultRespone lockUser(@RequestBody User user) {

        Long id=user.getId();
        if(checkHandler(user.getId())){
            return ResultRespone.failed("当前用户不能锁定其他人创建的用户");
        }
        User saveuser=new User();
        saveuser.setId(id);
        saveuser.setLockFlag(CommonConstants.USER_LOCK_LOCKED);
        return ResultRespone.success(userService.updateById(saveuser));
    }

    /**
     * 解锁
     * @return ResultRespone
     */
    @ToFlyAppLog(title="解锁用户" )
    @ApiOperation(value = "解锁用户")
    @PutMapping("/unlock")
    public ResultRespone unlockUser(@RequestBody User user) {
        Long id=user.getId();
        if(checkHandler(id)){
            return ResultRespone.failed("当前用户不能解锁级其他人创建的用户");
        }
        User saveuser=new User();
        saveuser.setId(id);
        saveuser.setLockFlag(CommonConstants.USER_LOCK_UNLOCK);
        saveuser.setPwderrtimes(Short.valueOf("0"));
        return ResultRespone.success(userService.updateById(saveuser));
    }


    /**
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改密码" )
    @ApiOperation(value = "修改密码")
    @PutMapping("/updatePassword")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "password", value = "修改后密码", required = true, dataType = "String")
    })
    public ResultRespone updatePassword(@RequestBody User user2) {

        Long id=user2.getId();
        String password=user2.getPassword();

        if(StringUtil.isEmpty(password)){
            return ResultRespone.failed("密码不能为空");
        }

        User user=new User();
        String username=null;
        if(id==null || id.longValue()== 0L){
            id=SecurityUtils.getUserId();
            username=SecurityUtils.getUserName();
        }else{
            if(checkHandler(id)){
                return ResultRespone.failed("当前用户不能修改其他人创建的用户");
            }
        }
        user.setId(id);
        String encodePassword=PasswordUtil.passwordEncode(password);
        user.setPassword(encodePassword);
        boolean b=userService.updateById(user);


        if(b){
            if(StringUtil.isEmpty(username)){
                username = (userService.getUserById(id)).getUsername();
            }
            updatePwd(username,encodePassword);
       }
        return ResultRespone.success(true);
    }


    @GetMapping("/getUserMenu" )
    @ApiOperation(value = "根据用户获取用户菜单信息（树状数据）")
    @SneakyThrows
    public ResultRespone getUserMenu(@ApiParam(value = "所属平台,1BS2CS",name = "platform",required = true,type = "String") String platform){
        List<Menu> menuList=userService.getMenuListByUser(platform);
        List<MenuChild> children= JSONObject.parseArray(JSONObject.toJSONString(menuList), MenuChild.class);
        List<MenuChild> children1 = JSONUtil.parTree(children, MenuChild::getId, MenuChild::getParentId, MenuChild::getChildren);
        return ResultRespone.success(children1);
    }


    /**
     * 查询用户子系统列表
     * @return ResultRespone
     */
    @GetMapping("/systemList" )
    @ApiOperation(value = "获取用户子系统列表")
    public ResultRespone systemList(@ApiParam(value = "所属平台,1BS2CS",name = "platform",required = true,type = "String") String platform) {
        return ResultRespone.success(userService.getSystemListByUser(platform));
    }

    /**
     * 查询用户菜单列表
     * @return ResultRespone
     */
    @GetMapping("/menuList" )
    @ApiOperation(value = "获取用户菜单列表")
    public ResultRespone menuList(@ApiParam(value = "所属平台,1BS2CS",name = "platform",required = true,type = "String") String platform) {
        return ResultRespone.success(userService.getMenuListByUser(platform));
    }

    /**
     * 查询用户资源列表
     * @return ResultRespone
     */
    @GetMapping("/sourceList" )
    @ApiOperation(value = "获取用户资源列表")
    public ResultRespone sourceList() {
        return ResultRespone.success(userService.getSourceByUser());
    }

    @GetMapping("/initData" )
    @ApiOperation(value = "初始化获取用户所有资源")
    @SneakyThrows
    public ResultRespone getInitData(@ApiParam(value = "所属平台,1BS2CS",name = "platform",required = true,type = "String") String platform){
        Long userId=SecurityUtils.getUserId();
        Long deptId=SecurityUtils.getUserDeptId();

        //资源列表
        List<Map> gisResources=sourceService.listSources(deptId);
        //List gisList=new ArrayList();
        List<Map> gisList=new ArrayList();
        List<Map> sourList;
        for (Map m:gisResources){
            List<Source> sourceList=sourceService.list(Wrappers.<Source>lambdaQuery()
                    .eq(Source::getPid,m.get("id"))
            .apply("exists (select 1\n" +
                    "          from  TF_SMPN_DEPARTMENTSOURCE_X\n" +
                    "         where TF_SMPN_DEPARTMENTSOURCE_X.source_id = TF_SMPN_SOURCE_X.id\n" +
                    "          and TF_SMPN_DEPARTMENTSOURCE_X.department_id={0})",deptId)
            );
            sourList=new ArrayList();
            for(Source source:sourceList){
               Map sourcemap=new HashMap();
               sourcemap.put("key",source.getCkey());
               sourcemap.put("groupname",m.get("GROUPNAME"));
               sourcemap.put("name",source.getName());
               sourcemap.put("url",source.getCval());
                sourList.add(sourcemap);
            };
            m.put("config",sourList);
            gisList.add(m);
        };
        //所有菜单
        List<Menu> menuList=userService.getMenuListByUser(platform);
        //子系统
        List<System> sysList=userService.getSystemListByUser(platform);

        List<Map> menubarwidgets=new ArrayList<>();
        List<Map> toolbarwidgets=new ArrayList<>();

        for(Menu m:menuList){
            if(CommonConstants.MENU_TYPE_MENU.equals(m.getType())){
                Map map=new HashMap();
                map.put("id",m.getCode());
                map.put("label",m.getName());
                map.put("icon",m.getIcon());
                map.put("icon2",m.getMouseIcon());

                List<Menu> menuList1= menuService.list(Wrappers.<Menu>lambdaQuery()
                        .eq(Menu::getParentId,m.getId()).orderByAsc(Menu::getSort)
                .apply("exists\n" +
                        " (select 1\n" +
                        "          from TF_SMPN_USERROLE_X, TF_SMPN_ROLEMENU_X\n" +
                        "         where TF_SMPN_USERROLE_X.role_id = TF_SMPN_ROLEMENU_X.role_id\n" +
                        "           and TF_SMPN_ROLEMENU_X.menu_id = TF_SMPN_MENU_X.id\n" +
                        "           and TF_SMPN_USERROLE_X.user_id = {0})",SecurityUtils.getUserId())
                );
                List<Map> mmList=new ArrayList();
                for(Menu menu:menuList1) {
                    Map map1=BeanUtils.describe(menu);
                    map1.put("subsys",getSysCode(sysList,menu.getSysId()));
                    map1.put("id", menu.getCode());
                    map1.put("label",menu.getName());
                    map1.put("widget",menu.getPath());
                    map1.put("main","Widget"); //写死。
                    map1.put("inpanel","1".equals(menu.getInpanel())?true:false);
                    map1.put("autorun","1".equals(menu.getAutorun())?true:false);
                    mmList.add(map1);
                };
                map.put("data",mmList);
                menubarwidgets.add(map);
            }else if(CommonConstants.MENU_TYPE_TOOL.equals(m.getType()) && (m.getParentId()==null)){
                Map map=new HashMap();
                map.put("id",m.getCode());
                map.put("sysId",getSysCode(sysList,m.getSysId()));
                map.put("title",m.getName());
                map.put("label",m.getName());
                map.put("icon",m.getIcon());
                map.put("icon2",m.getMouseIcon());

                List<Menu> menuList1= menuService.list(Wrappers.<Menu>lambdaQuery()
                        .eq(Menu::getParentId,m.getId()).orderByAsc(Menu::getSort)
                        .apply("exists\n" +
                                " (select 1\n" +
                                "          from TF_SMPN_USERROLE_X, TF_SMPN_ROLEMENU_X\n" +
                                "         where TF_SMPN_USERROLE_X.role_id = TF_SMPN_ROLEMENU_X.role_id\n" +
                                "           and TF_SMPN_ROLEMENU_X.menu_id = TF_SMPN_MENU_X.id\n" +
                                "           and TF_SMPN_USERROLE_X.user_id = {0})",SecurityUtils.getUserId())
                );
                List<Map> mmList=new ArrayList();
                for(Menu menu:menuList1) {
                    Map map1=BeanUtils.describe(menu);
                    map1.put("id",menu.getCode());
                    map1.put("sysId",getSysCode(sysList,m.getSysId()));
                    map1.put("title",menu.getName());
                    map1.put("label",menu.getName());
                    map1.put("icon",menu.getIcon());
                    map1.put("icon2",menu.getMouseIcon());
                    mmList.add(map1);
                };
                map.put("data",mmList);
                toolbarwidgets.add(map);
            }
        };

        List<Map<String,Object>> subsystem=new ArrayList();
        for(System sys:sysList){
            Map m=BeanUtils.describe(sys);
            m.put("id",sys.getCode());
            m.put("type",sys.getSystemType());
            m.put("title",sys.getNotes());
            m.put("label",sys.getSystemName());
            m.put("icon1",sys.getIcon());
            m.put("icon2",sys.getMouseIcon());
            m.put("initShow",false); //没有字段，写死
            subsystem.add(m);
        };

        Map returnMap=new HashMap();
        returnMap.put("gisresource",gisList);
        returnMap.put("menubarwidgets",menubarwidgets);
        returnMap.put("subsystem",subsystem);
        returnMap.put("toolbarwidgets",toolbarwidgets);

        return ResultRespone.success(returnMap);
    }

    private String  getSysCode(List<System> sysList,Long sysid){
        for (System system: sysList){
            if(sysid.equals(system.getId())){
                return system.getCode();
            }
        }
        return null;
    }


    /**
     * 通过id删除角色
     * @param ids id数组
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除用户" )
    @ApiOperation(value = "通过ID删除用户")
    @DeleteMapping("/removeByIds" )
    public ResultRespone removeByIds(@ApiParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7",name = "ids",required = true) String ids) {
//        String[] idss=ids.split(",");
//        List<Long> list=new ArrayList();
//        boolean flag=true;
//        StringBuffer sb=new StringBuffer();
//        for(String id:idss){
//            SecurityUtils
//        }
        return ResultRespone.success(userService.deleteUserByIds(ids));
    }



    @innerCall
    @PostMapping("/info/update")
    public ResultRespone<Boolean> updateUserInfo(@RequestBody User user){

        if(!StringUtil.isEmpty(user.getLastIp())){
            user.setLoginTime(DateUtil.getCurrentTime());
        }
        try {
            userService.updateById(user);
        }catch (Exception e){
            log.info("报错：------{}",e.getMessage());
        }

        return ResultRespone.success(true);
    }

    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户基本信息及菜单信息")
    public ResultRespone getUserInfo(@ApiParam(value = "所属平台",name = "platform",required = true,type = "String") String platform){
        Map map=new HashMap();
        ToflyUser user = SecurityUtils.getUser();
        map.put("username",user.getUsername());
        map.put("name",user.getRealName());
        map.put("avatar",user.getAvatar());

        List<Menu> menuList= menuService.list(Wrappers.<Menu>lambdaQuery()
                .orderByAsc(Menu::getSort)
                .apply("exists\n" +
                        " (select 1\n" +
                        "          from TF_SMPN_USERROLE_X, TF_SMPN_ROLEMENU_X\n" +
                        "         where TF_SMPN_USERROLE_X.role_id = TF_SMPN_ROLEMENU_X.role_id\n" +
                        "           and TF_SMPN_ROLEMENU_X.menu_id = TF_SMPN_MENU_X.id\n" +
            "           and TF_SMPN_USERROLE_X.user_id = {0})",SecurityUtils.getUserId())
            .apply("exists (select 1 from TF_SMPN_SYSTEM_X where TF_SMPN_SYSTEM_X.id=TF_SMPN_MENU_X.sys_id and code = {0} )",platform)
        );
        map.put("menus",menuList);
        return ResultRespone.success(map);
}


    @ToFlyAppLog(title="通过文件批量新增用户" )
    @ApiOperation(value = "通过文件批量新增用户")
    @PostMapping("/batchUser" )
    public ResultRespone uploadBatchMenu(MultipartFile file){
        return ResultRespone.success(userService.uploadBatchUser(file));
    }

    @ApiOperation(value = "根据菜单名称查询菜单功能已启动的用户")
    @GetMapping("/getUserByMenu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuName", value = "菜单功能名称", required =true, dataType = "String")
    })
    public ResultRespone getUserByMenu(@RequestParam("menuName") String menuName){
        return ResultRespone.success(userService.getUserByMenu(menuName));
    }

    @ApiOperation(value = "根据部门批量查询用户")
    @GetMapping("/getUserByDepts")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "depts", value = "部门id字符串，如‘1,2’", dataType = "String")
    })
    public ResultRespone getUserByDepts(@RequestParam(value = "depts",required = false) String depts){
        List<String> deptIds = new ArrayList<>();
        if(StringUtil.isNotEmpty(depts)){
            deptIds = Arrays.asList(depts.split(","));
        }
        List<Map<String,Object>> deptlist =  departmentService.listMaps(Wrappers.<Department>lambdaQuery()
                .in(deptIds.size() > 0,Department::getId,deptIds)
                .select(Department::getId,Department::getName));
        deptlist.forEach(dept->{
            List userList = userService.listMaps(Wrappers.<User>lambdaQuery()
                    .eq(User::getDepartmentId,dept.get("id"))
                    .select(User::getId,User::getRealName));
            dept.put("users",userList);
        });
        return ResultRespone.success(deptlist);
    }


    private boolean checkHandler(Long userid){

        if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())){
            return false;
        }
        if(SecurityUtils.getUserId().equals(userid)){
            return false;
        }

        User user=userService.getById(userid);

        if(SecurityUtils.getUserId().equals(user.getCreateUser())){
            return false;
        }else {
            if(CommonConstants.SUPER_ADMIN_ULEVEL.equals(user.getUserLevel())){
                return true;
            }else {
                return checkHandler(user.getCreateUser());
            }
        }


    }



    private void updatePwd(String username,String encodePassword){
        //调用清除缓存的方法
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null && cache.get(username).get()!=null) {
            ToflyUser toflyUser= (ToflyUser) cache.get(username).get();
            log.info("password:",toflyUser.getPassword());
            //toflyUser.setPassword(encodePassword);
            ToflyUser toflyUser1=new ToflyUser(toflyUser.getUserid(),toflyUser.getDepartmentId(),toflyUser.getUserLevel(),
                    toflyUser.getRealName(),toflyUser.getDepartemntName(),toflyUser.getAvatar(),
                    toflyUser.getUsername(),encodePassword,
                    true,true,
                    true,true,toflyUser.getAuthorities());
            cache.put(username,toflyUser1);
        }
    }

    private void updateCache(String username,User toflyUserP){
        //调用清除缓存的方法
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null && cache.get(username).get()!=null) {
            ToflyUser toflyUser= (ToflyUser) cache.get(username).get();
            boolean xgflag=false;
            String password=toflyUser.getPassword();
            if(!StringUtil.isEmpty(toflyUserP.getPassword()) && !toflyUserP.getPassword().equals(password)){
                password = toflyUserP.getPassword();
                xgflag=true;
            }
            Long deptid=toflyUser.getDepartmentId();
            String deptName=toflyUser.getDepartemntName();
            if(toflyUserP.getDepartmentId()!=null && deptid.longValue()!=toflyUserP.getDepartmentId()){
                deptid=toflyUserP.getDepartmentId();
                deptName=departmentService.getById(deptid).getName();
                xgflag=true;
            }
            String  avatar=toflyUser.getAvatar();
            if(!StringUtil.isEmpty(toflyUserP.getAvatar()) && !toflyUserP.getAvatar().equals(avatar)){
                avatar=toflyUserP.getAvatar();
                xgflag=true;
            }

            String realName=toflyUser.getRealName();
            if(!StringUtil.isEmpty(toflyUserP.getRealName()) && !toflyUserP.getRealName().equals(realName)){
                realName=toflyUserP.getRealName();
                xgflag=true;
            }

            String userlevel=toflyUser.getUserLevel();
            if(!StringUtil.isEmpty(toflyUserP.getUserLevel()) && !toflyUserP.getUserLevel().equals(userlevel)){
                userlevel=toflyUserP.getUserLevel();
                xgflag=true;
            }

            if(xgflag){
                ToflyUser toflyUser1=new ToflyUser(toflyUser.getUserid(),deptid,userlevel,
                        realName,deptName,avatar,
                        toflyUser.getUsername(),password,
                        true,true,
                        true,true,toflyUser.getAuthorities());
                cache.put(username,toflyUser1);
            }



        }
    }


}
