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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.dto.ApplyForReviewDTO;
import com.tofly.base.dto.ResetUserDTO;
import com.tofly.base.em.Constant;
import com.tofly.base.entity.System;
import com.tofly.base.entity.*;
import com.tofly.base.service.*;
import com.tofly.base.service.messge.MessagepushService;
import com.tofly.base.service.messge.MessagerecipientService;
import com.tofly.base.service.messge.UsertaskService;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.JSONUtil;
import com.tofly.common.core.util.PasswordUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
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 com.tofly.pojo.Userdept;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.pojo.message.Usertask;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
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;
    @Value("${xrty.ftp.excelmb}")
    private String filePathExcel;
    @Value("${user.account}")
    private String account;
    @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;
    @Autowired
    private MessagepushService messageClient;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MessagerecipientService messagerecipientService;
    @Autowired
    private UsertaskService usertaskService;
    @Autowired
    private UserMiddleService userMiddleService;
    @Autowired
    private UserdeptService userdeptService;

    @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.forEach(role -> {
            String sysids = role.getTreeValue();
            stringBuilder.append(sysids).append(",");
        });
        return ResultRespone.success(baseSysmenuService.getTreeSys(sysId, stringBuilder.toString()));
    }


    @ApiOperation(value = "根据用户字符串获取对应名称map")
    @GetMapping("/getUserIdNameMap")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userIds", value = "用户ids", dataType = "String")
    })
    public ResultRespone<Map<Long, String>> getUserIdNameMap(@RequestParam(value = "userIds") String userIds) {
        List<Long> stationIdList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        Map<Long, String> userIdNameMap = userService.list(new QueryWrapper<User>().lambda().in(User::getId, stationIdList)).stream().
                collect(Collectors.
                        toMap(User::getId, User::getRealName, (item1, item2) -> item1));
        return ResultRespone.success(userIdNameMap);
    }


    @GetMapping("/getUserAvatarPathList")
    @ApiOperation(value = "获取用户头像信息 key 用户id,value头像路径")
    public ResultRespone<Map<Long, String>> getUserAvatarPathList(@RequestParam(value = "userIds") String userIds) {
        List<Long> userList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        try {
            List<User> list = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userList).select(User::getId, User::getAvatar));
            list.forEach(info -> {
                if (null == info.getAvatar()) {
                    info.setAvatar("");
                }
            });
            Map<Long, String> maps = list.stream().collect(Collectors.toMap(User::getId, User::getAvatar, (key1, key2) -> key2));

            return ResultRespone.success(maps);
        } catch ( Exception e ) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return ResultRespone.failed();
    }

    /**
     * 分页查询
     *
     * @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));
        }
    }

    /**
     * 新增用户表-新
     *
     * @param user 用户表
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "新增用户表-新")
    @ApiOperation(value = "新增用户表-新")
    @PostMapping("/saveNew")
    @Transactional
    public ResultRespone saveNew(MultipartFile file, UserRoles user,
                                 @ApiParam(value = "电子签名", name = "electronicFile", required = true) MultipartFile electronicFile) {
        return ResultRespone.success(userService.saveNew(file, user, electronicFile));
    }

    /**
     * 模板下载
     *
     * @return ResultRespone
     */
    @GetMapping(value = "/template")
    @ApiOperation(value = "模版下载", notes = "模版下载")
    public ResultRespone planTemplate() throws Exception {
        return ResultRespone.success(userService.planTemplate());
    }

    /**
     * 申请审核
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "申请审核")
    @ApiOperation(value = "申请审核")
    @PutMapping("/applyForReview")
    public ResultRespone applyForReview(@RequestBody ApplyForReviewDTO user) {
        if (!CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())) {
            return ResultRespone.failed("当前用户不能审核用户信息");
        }
        //审核通过修改用户信息
        String roles = user.getRoles();
        User quser = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId, user.getId()));
        if (quser != null) {
            quser.setAudittime(new Date());
            quser.setAuditor(SecurityUtils.getUserName());
            quser.setAuditstate(user.getAuditstate());
            quser.setAuditstatus(user.getAuditstatus());
            userService.updateById(quser);
            //分配权限
            if (!StringUtil.isEmpty(roles)) {
                String[] role = roles.split(",");
                UserRole userRole;
                for (String s : role) {
                    userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Long.valueOf(s));
                    userRoleService.save(userRole);
                }
            }
        }
        Messagepush messagepush = new Messagepush();
        messagepush.setTopic("账户申请审核");
        messagepush.setMessage("审核通过");
        messagepush.setRouteIp(account);
        messageClient.save(messagepush);
        Messagerecipient messagerecipient = new Messagerecipient();
        messagerecipient.setMessageId(messagepush.getId());
        messagerecipient.setRecipient(userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, user.getApplyer())).getId());
        messagerecipient.setFlag("0");
        messagerecipientService.save(messagerecipient);
        return ResultRespone.success(user.getAuditstatus());
    }

    /**
     * 历史申请记录查询
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "历史申请记录查询")
    @ApiOperation(value = "历史申请记录查询")
    @GetMapping("/historySelect")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realName", value = "用户名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "auditStatus", value = "审核意见", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startAuditTime", value = "开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endAuditTime", value = "结束日期", required = false, dataType = "String")
    })
    public ResultRespone historySelect(Page page, String realName, String auditStatus, String startAuditTime, String endAuditTime) {
        Map map = new HashMap();
        map.put("realName", realName);
        map.put("auditStatus", auditStatus);
        map.put("StartAuditTime", StringUtil.isEmpty(startAuditTime) ? null : startAuditTime + " 00:00:00");
        map.put("endAuditTime", StringUtil.isEmpty(endAuditTime) ? null : endAuditTime + " 23:59:59");
        map.put("userName", SecurityUtils.getUserName());
        return ResultRespone.success(userService.getListHistory(page, map));
    }

    /**
     * 账号申请
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "账号申请")
    @ApiOperation(value = "账号申请")
    @PutMapping("/accountApplication")
    @Transactional
    @ApiImplicitParam(name = "recipient", value = "指派的审核人", required = false, dataType = "Long")
    public ResultRespone accountApplication(User user, MultipartFile file, MultipartFile electronicFile, Long recipient) {
        Messagepush messagepush = new Messagepush();
        messagepush.setTopic("账号申请");
        messagepush.setMessage("申请的账号需要审核");
        messagepush.setRouteIp(account);
        messageClient.save(messagepush);
        //指派审核人
        Messagerecipient messagerecipient = new Messagerecipient();
        messagerecipient.setMessageId(messagepush.getId());
        messagerecipient.setRecipient(recipient);
        messagerecipientService.save(messagerecipient);
        //待办事项
        Usertask usertask = new Usertask();
        usertask.setTknm("账号申请");
        usertask.setTkty("0");
        usertask.setRouteIp(account);
        usertask.setHandleUser(recipient);
        usertaskService.save(usertask);
        User userById = userService.getUserById(recipient);
        user.setAuditor(userById.getUsername());
        ResultRespone resultRespone = userService.accountApplication(file, user, electronicFile);
        return ResultRespone.success(resultRespone);
    }

    /**
     * 获取拥有用户管理权限的相关用户
     */
    @ApiOperation(value = "获取拥有用户管理权限的相关用户")
    @GetMapping("/getUserpermissions")
    public ResultRespone<List<User>> getUserpermissions() {
        Menu menu = menuService.getUserPersion();
        List<RoleMenu> list = roleMenuService.getAllRoleId(menu.getId());
        List<Long> roleId = list.stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
        List<UserRole> userRoles = userRoleService.list(Wrappers.<UserRole>lambdaQuery().in(UserRole::getRoleId, roleId));
        List<Long> userId = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
        List<User> userList = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userId));
        return ResultRespone.success(userList);
    }


    /**
     * 通过当前用户获取当前部门下的所有用户获取拥有用户管理权限的相关用户
     */
    @ApiOperation(value = "通过当前用户获取当前部门下的所有用户获取拥有用户管理权限的相关用户")
    @GetMapping("/getUserpermissionsByDepatment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String")
    })
    public ResultRespone getUserpermissionsByDepatment(String ids) throws Exception {
        List<Long> removeId = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<Menu> menu = menuService.listByIds(removeId);
        List<RoleMenu> lists = new ArrayList<>();
        for (Menu m : menu) {
            List<RoleMenu> list = roleMenuService.getAllRoleId(m.getId());
            lists.addAll(list);
        }
        List<Long> roleId = lists.stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
        List<UserRole> userRoles = userRoleService.list(Wrappers.<UserRole>lambdaQuery().in(UserRole::getRoleId, roleId));
        List<Long> userId = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
        List<User> userList = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userId));
        List<User> departmentList = userService.getDepartmentUsers();
        List<User> users = removeRepeatFactor(userList, departmentList);
        return ResultRespone.success(users);
    }

    /**
     * 通过部门和菜单权限获取对应的用户
     */
    @ApiOperation(value = "通过部门和菜单权限获取对应的用户")
    @GetMapping("/getUserpermissionsByDepatmentAndMune")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String"),
            @ApiImplicitParam(name = "departmentId", value = "departmentId", required = true, dataType = "Long")
    })
    public ResultRespone getUserpermissionsByDepatmentAndMune(String ids, Long departmentId) throws Exception {
        List<Long> removeId = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<Menu> menu = menuService.listByIds(removeId);
        List<RoleMenu> lists = new ArrayList<>();
        for (Menu m : menu) {
            List<RoleMenu> list = roleMenuService.getAllRoleId(m.getId());
            lists.addAll(list);
        }
        List<Long> roleId = lists.stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
        List<UserRole> userRoles = userRoleService.list(Wrappers.<UserRole>lambdaQuery().in(UserRole::getRoleId, roleId));
        List<Long> userId = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
        List<User> userList = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userId));
        List<User> departmentList = userService.getDepartmentUsersByIds(departmentId);
        List<User> users = removeRepeatFactor(userList, departmentList);
        return ResultRespone.success(users);
    }


    /**
     * 通过菜单权限获取部门及其用户
     */
    @ApiOperation(value = "通过菜单权限获取部门及其用户")
    @GetMapping("/getUserAndDepatmentByPerssion")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String")
    })
    public ResultRespone getUserAndDepatmentByPerssion(String ids) throws Exception {

        return userService.getUserAndDepatmentByPerssion(ids);
    }

    /**
     * 修改用户及其权限
     *
     * @param user 用户表
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "修改用户及其权限")
    @ApiOperation(value = "修改用户及其权限")
    @PutMapping("/updateNew")
    public ResultRespone updateByIdNew(@ApiParam(value = "头像", name = "file", required = true) MultipartFile file, User user,
                                       @ApiParam(value = "电子签名", name = "electronicFile", required = true) MultipartFile electronicFile,
                                       @ApiParam(value = "用户权限ids(用逗号隔开)", name = "roles") String roles) {

        return ResultRespone.success(userService.updateByIdNew(file, user, electronicFile, roles, user.getUserdeptList()));
    }

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

//        if (!(SecurityUtils.getUserId().equals(user.getCreateUser()))) {
//            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();
                }
                //调用清除缓存的方法
                updateCache(username, user);

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

        }

        return ResultRespone.success(true);
    }

    /**
     * 通过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("/getUserInformatiomByLikeName")
    @ApiOperation(value = "根据用户名模糊获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "name", required = true, dataType = "String")
    })
    public ResultRespone getUserInformatiomByLikeName(String name) {
        return ResultRespone.success(userService.getUserInformatiomByLikeName(name));
    }

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

    /**
     * 锁定
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "锁定用户")
    @ApiOperation(value = "锁定用户")
    @PutMapping("/lock")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7", name = "ids", required = true)
    })
    public ResultRespone lockUser(String ids) {
        return ResultRespone.success(userService.updateByIdList(ids));
    }


    /**
     * 通过当前用户获取当前部门下的所有用户
     *
     * @return ResultRespone
     */
    @GetMapping("/getDepartmentUser")
    @ApiOperation(value = "通过当前用户获取当前部门下的所有用户")
    public ResultRespone getDepartmentUser() {
        return ResultRespone.success(userService.getDepartmentUsers());
    }

    /**
     * 解锁
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "解锁用户")
    @ApiOperation(value = "解锁用户")
    @PutMapping("/unlock")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7", name = "ids", required = true)
    })
    public ResultRespone unlockUser(String ids) {
        return ResultRespone.success(userService.updateByIdListToUnlock(ids));
    }

    /**
     * 禁用
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "禁用用户")
    @ApiOperation(value = "禁用用户")
    @PutMapping("/statusFlag")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7", name = "ids", required = true)
    })
    public ResultRespone statusFlagUser(String ids) {
        return ResultRespone.success(userService.updateByIdStatusFlag(ids));
    }

    /**
     * 启用
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "启用用户")
    @ApiOperation(value = "启用用户")
    @PutMapping("/unStatusFlag")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7", name = "ids", required = true)
    })
    public ResultRespone unStatusFlagUser(String ids) {
        return ResultRespone.success(userService.updateUnStatusFlag(ids));
    }

    /**
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "修改密码")
    @ApiOperation(value = "修改密码")
    @PutMapping("/updatePassword")
    public ResultRespone updatePassword(@RequestBody User user2) {
        return userService.updatePassword(user2);
    }

    /**
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "重置密码")
    @ApiOperation(value = "重置密码")
    @PutMapping("/resetPassword")
    public ResultRespone resetPassword(@RequestBody ResetUserDTO users) {
        return ResultRespone.success(userService.resetPassword(users));
    }


    /**
     * 模板上传
     *
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "模板上传")
    @ApiOperation(value = "模板上传")
    @PutMapping("/templateToUpload")
    public ResultRespone templateToUpload(MultipartFile file) throws IOException {
        return ResultRespone.success(userService.templateToUpload(file));
    }

    @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) {
        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<Userdept> userdeptList = userdeptService.list(new QueryWrapper<Userdept>().lambda()
                    .eq(Userdept::getDeptId, Long.parseLong(String.valueOf(dept.get("id")))));
            if (CollUtil.isEmpty(userdeptList)) {
                return;
            }
//            List userList = userService.listMaps(Wrappers.<User>lambdaQuery()
//                    .eq(User::getDepartmentId, dept.get("id"))
//                    .eq(User::getEnableFlag, "1")
//                    .select(User::getId, User::getRealName, User::getDepartmentId, User::getPhone));
            List userList = userService.listMaps(Wrappers.<User>lambdaQuery()
                    .in(User::getId, userdeptList.stream().map(Userdept::getUserId).distinct().collect(Collectors.toList()))
                    .eq(User::getEnableFlag, "1")
                    .select(User::getId, User::getRealName, User::getDepartmentId, User::getPhone));
            dept.put("users", userList);
        });
        return ResultRespone.success(deptlist);
    }

    @ApiOperation(value = "获取部门下的用户信息列表")
    @GetMapping("/getDeptUserList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptIds", value = "部门id（多个用,分隔）", dataType = "String")
    })
    public ResultRespone<List<User>> getDeptUserList(@RequestParam(value = "deptIds", required = false) String deptIds) {
        List<User> list = null;
        if (StringUtils.isBlank(deptIds)) {
            list = userService.list(new QueryWrapper<User>().lambda().eq(User::getEnableFlag, "1"));
        } else {
            List<Long> deptIdList = Arrays.stream(deptIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<Long> departmentIds = new ArrayList<>(deptIdList);
            List<Department> departmentList = departmentService.list(new QueryWrapper<Department>().lambda()
                    .and(w -> w.in(Department::getParentId, deptIdList).or().in(Department::getId, deptIdList)));
            if (departmentList.size() != 0) {
                departmentIds = departmentList.stream().map(Department::getId).collect(Collectors.toList());
            }
            list = userService.list(new QueryWrapper<User>().lambda().in(User::getDepartmentId, departmentIds).eq(User::getEnableFlag, "1"));
        }

        if (null != list && list.size() > 0) {
            return ResultRespone.success(list);
        }
        return ResultRespone.success(new ArrayList<>());
    }

    @innerCall
    @GetMapping("/info/{username}")
    @ApiOperation(value = "获取用户信息")
    public ResultRespone getInfo(@PathVariable("username") String username) {
        log.info("base:通过用户名从数据库找信息..:" + username);
        User sysUser = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, username));
        log.info("base:从数据库找到用户信息..:" + username + ":" + sysUser);
        if (sysUser == null) {
            return ResultRespone.failed("用户信息为空" + username);
        }
        return ResultRespone.success(userService.getUserInfo(sysUser));
    }

    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 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(Short.valueOf("0"),toflyUser.getParentCompanyId(),toflyUser.getParentCompanyName(),toflyUser.getCompanyId(),toflyUser.getCompanyName(),toflyUser.getUserid(),toflyUser.getDepartmentId(),toflyUser.getUserLevel(),
//                        toflyUser.getRealName(),toflyUser.getDepartemntName(),toflyUser.getAvatar(),
//                        toflyUser.getUsername(),/*SecurityConstants.BCRYPT+*/toflyUser.getPassword(),
//                        true,true,
//                        true,true,toflyUser.getAuthorities());
//                cache.put(username, toflyUser1);
            }
        }
    }

    public String sub(String str) {
        StringBuffer result = new StringBuffer();
        List list = new ArrayList();
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (!list.contains(cs[i])) {
                result.append(cs[i]);
                list.add(cs[i]);
            }
        }
        return result.toString();
    }

    public List<User> removeRepeatFactor(List<User> list1, List<User> list2) throws Exception {
        List<User> resultUser = new ArrayList<>();
        if (list1 != null && list2 != null) {
            if (list1.size() != 0 && list2.size() != 0) {
                List<User> allUsers = new ArrayList<>();
                allUsers.addAll(list1);
                Map mapList1 = list1.stream().collect(Collectors.toMap(User::getId, m -> m));
                resultUser = list2.stream().filter(k -> mapList1.containsKey(k.getId())).collect(Collectors.toList());

            }
        }
        return resultUser;
    }


    @GetMapping("/sysUserReport")
    @ApiOperation(value = "系统使用人员统计,统计部门下的人员")

    public ResultRespone sysUserReport() {
        return ResultRespone.success(userService.sysUserReport());

    }

    @GetMapping("/serialNumberUpDown")
    @ApiOperation(value = "序号上移下移")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "type", value = "类型（1上移;2下移）", required = true, dataType = "String"),
    })
    public ResultRespone serialNumberUpDown(Long userId, String type) {
        userService.serialNumberUpDown(userId, type);
        return ResultRespone.success();
    }

    @GetMapping("/serialNumberJump")
    @ApiOperation(value = "序号上跳下跳")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adjustUserId", value = "调整用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "replaceUserId", value = "替换用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "type", value = "类型（1上跳;2下跳）", required = true, dataType = "String"),
    })
    public ResultRespone serialNumberJump(Long adjustUserId, Long replaceUserId, String type) {
        userService.serialNumberJump(adjustUserId, replaceUserId, type);
        return ResultRespone.success();
    }
}
