package com.vctgo.system.controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.mybatisplus.aop.TemporaryIgnoreTables;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.annotation.InnerAuth;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysDept;
import com.vctgo.system.api.domain.SysRole;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.api.domain.dto.StaticsUserPermsDto;
import com.vctgo.system.api.domain.dto.SysUserDto;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.domain.SysPost;
import com.vctgo.system.domain.SysReClassUser;
import com.vctgo.system.service.*;
import com.vctgo.system.util.ConstantUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author vctgo
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysReClassUserService sysReClassUserService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:page")
    @GetMapping("/page")
    public AjaxResult pageList(SysUser user) {
        user.getParams().put("isExcludeTenant", "00");
        IPage<SysUser> list = userService.selectUserPage(user);
        return AjaxResult.success(list);
    }

    /**
     * 获取指定组织的用户列表
     */
    @TemporaryIgnoreTables
    @GetMapping("/list/{deptId}")
    public AjaxResult getUserListByDept(@PathVariable Long deptId,
                                        @RequestParam(name = "tenantId", required = false) Long tenantId,
                                        //0:表示查询全部用户，1:表示存在账号，2:表示不存在账号
                                        @RequestParam(name = "flag", required = false, defaultValue = "0") Integer flag,
                                        @RequestParam(name = "userName", required = false) String nickName,
                                        //0:表示查询本部门及下级部门所有人员，1:表示查询本部门人员，2:表示查询本部门的下级所有部门人员
                                        @RequestParam(name = "departmentType", required = false, defaultValue = "0") Integer departmentType) {
        SysUser user = new SysUser();
        user.setDeptId(deptId);
        if (SecurityUtils.getTenantId() == 9999L || SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept", "sys_user_post", "sys_post"));
        }
        user.getParams().put("isExistAccount", flag);
        if (tenantId != null) {
            user.getParams().put("tenantId", tenantId);
        }
        user.setNickName(nickName);
        List<SysUser> userList = userService.selectUserList(user);
        if (departmentType == 1) {
            userList = userList.stream().filter(obj -> deptId.equals(obj.getDeptId())).collect(Collectors.toList());
        } else if (departmentType == 2) {
            userList = userList.stream().filter(obj -> !deptId.equals(obj.getDeptId())).collect(Collectors.toList());
        }
        SecurityUtils.removeTemporaryIgnoreTables();
        return AjaxResult.success(userList);
    }

    /**
     * 获取指定租户的用户列表
     */
    @TemporaryIgnoreTables
    @GetMapping("/weekPlan/user/list/tenant")
    public AjaxResult getUserListByTenantId(
            //部门Id
            @RequestParam(name = "deptId", required = false) Long deptId,
            //租户Id
            @RequestParam(name = "tenantId", required = false) Long tenantId,
            //0:表示查询全部用户，1:表示存在账号，2:表示不存在账号
            @RequestParam(name = "flag", required = false, defaultValue = "0") Integer flag,
            //用户名称
            @RequestParam(name = "userName", required = false) String nickName,
            //0:表示查询本部门及下级部门所有人员，1:表示查询本部门人员，2:表示查询本部门的下级所有部门人员
            @RequestParam(name = "departmentType", required = false, defaultValue = "0") Integer departmentType,
            //岗位Id
            @RequestParam(name = "postId", required = false) Long postId,
            //是否为骨干
            @RequestParam(name = "isBackbone", required = false) String isBackbone) {
        SysUser user = new SysUser();
        user.setDeptId(deptId);
        if (SecurityUtils.getTenantId() == 9999L || SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept", "sys_user_post", "sys_post"));
        }
        user.getParams().put("isExistAccount", flag);
        if (tenantId != null) {
            user.getParams().put("tenantId", tenantId);
        }
        user.setNickName(nickName);
        user.setPostId(postId);
        user.setIsBackbone(isBackbone);
        List<SysUser> userList = userService.selectUserList(user);
        if (departmentType == 1) {
            userList = userList.stream().filter(obj -> deptId.equals(obj.getDeptId())).collect(Collectors.toList());
        } else if (departmentType == 2) {
            userList = userList.stream().filter(obj -> !deptId.equals(obj.getDeptId())).collect(Collectors.toList());
        }
        SecurityUtils.removeTemporaryIgnoreTables();
        return AjaxResult.success(userList);
    }

    /**
     * 流程管理获取用户列表
     */
    @ApiOperation(value = "获取流程管理用户列表")
    @TemporaryIgnoreTables
    @GetMapping("/process/user/list/tenant")
    public AjaxResult processUserListByTenantId(String tenantId, String nickName, String phoneNumber) {
        if (StrUtils.isEmpty(tenantId)) {
            throw new ServiceException("请先确认租户身份!");
        }
        if (Objects.nonNull(tenantId) && Long.parseLong(tenantId) != SecurityUtils.getTenantId()) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept"));
        }
        return AjaxResult.success(userService.userListByTenantIdAndNickNameWithPhoneNumber(tenantId, nickName, phoneNumber, null));
    }

    /**
     * 文件管理获取用户列表
     */
    @ApiOperation(value = "文件管理获取用户列表")
    @TemporaryIgnoreTables
    @GetMapping("/file/user/list/tenant")
    public AjaxResult fileUserListByTenantId(String nickName, String phoneNumber) {
        Long tenantId = SecurityUtils.getTenantId();
        if (StrUtils.isEmpty(tenantId)) {
            throw new ServiceException("请先确认租户身份!");
        }
        SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept"));
        return AjaxResult.success(userService.userListByTenantIdAndNickNameWithPhoneNumber(String.valueOf(tenantId), nickName, phoneNumber, null));
    }

    /**
     * 全量获取用户列表
     */
    @RequiresPermissions("system:user:all:list")
    @GetMapping("/allList")
    public AjaxResult userList() {
        SysUser sysUser = new SysUser();
        if (SecurityUtils.getTenantId() != 9999L) {
            sysUser.setTenantId(SecurityUtils.getTenantId());
        }
        List<SysUser> list = userService.selectUserList(new SysUser());
        return AjaxResult.success(list);
    }

    /**
     * 通过租户id获取特定的用户列表
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_platform_user", "sys_user", "sys_dept"})
    @GetMapping("/allList/tenantIds")
    public AjaxResult userListByTenantIds(@RequestParam("tenantIds") String tenantIds) {
        return AjaxResult.success(userService.userListByTenantIds(tenantIds));
    }

    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_role_menu"})
    @Transactional
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StrUtils.isNull(sysUser)) {
            return R.loginFail("用户名或密码错误");
        }
        //判断当前用户的状态是否被禁用
        if ("1".equals(sysUser.getAccountStatus())) {
            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
        }
        //判断用户所在的租户管理员状态是否被禁用
        Long tenantId = sysUser.getTenantId();
        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
        if (sysTenant != null && sysTenant.getStatus() == 1) {
            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
        }
        //判断用户对应租户的父级租户管理员状态是否被禁用
        SysTenant parentSysTenant = sysTenantService.getParentTenantInfo(tenantId);
        if (parentSysTenant != null && parentSysTenant.getStatus() == 1) {
            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
        }
        // 查询租户信息
        SysTenant tenant = sysTenantService.selectSysTenantById(sysUser.getTenantId());
        // 租户类型 1 集团租户 2 幼儿园租户有集团 3 幼儿园租户无集团
        SecurityUtils.setTenantType(Objects.isNull(tenant) ? "3" : tenant.getTenantType().toString());
        SecurityUtils.setTenantId(Objects.isNull(tenant) ? "" : tenant.getId().toString());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合,写往缓存里面，校验接口权限
        Set<String> permissions = permissionService.getMenuPermissionByMultiTenant(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUserTempalte(sysUser);
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setSysRolesList(sysUser.getRoles());
        sysUserVo.setPermissions(permissions);
        if (Objects.nonNull(tenant)) {
            sysUserVo.setTenantEndDate(tenant.getTenantEndTime());
            sysUserVo.setTenantStatus(tenant.getStatus());
            sysUserVo.setTenantType(tenant.getTenantType());
            sysUserVo.setTenantName(tenant.getTenantName());
        }
        return R.ok(sysUserVo);
    }

    /**
     * 判断用户是否存在指定的权限
     *
     * @param staticsUserPermsDto 部门信息
     * @return 统计对象集合
     */
    @InnerAuth
    @GetMapping("/exist/perms")
    public R<Boolean> judgeUserIsExistPointPerms(@SpringQueryMap StaticsUserPermsDto staticsUserPermsDto) {
        return R.ok(userService.judgeUserIsExistPointPerms(staticsUserPermsDto));
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @GetMapping("/list/all")
    public R<List<SysUser>> getAllUserByTenantId(@SpringQueryMap SysUserDto sysUserDto) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto, sysUser);
        return R.ok(userService.selectUserListByParams(sysUser.getTenantId(), sysUser.getDelFlag()));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    /**
     * sys_user u
     * sys_dept d
     * sys_role r
     * sys_tenant t
     * sys_user_role ur
     *
     * @param userId
     * @return
     */
    @TemporaryIgnoreTables
    @GetMapping("/name/info/{userId}")
    public R<SysUser> getUserInfoByUserId(@PathVariable Long userId) {
        if (SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept", "d", "u", "sys_role",
                    "r", "sys_tenant", "t", "sys_user_role", "ur"));
        }
        SysUser sysUser = userService.selectUserById(userId);
        SecurityUtils.removeTemporaryIgnoreTables();
        return R.ok(sysUser);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @TemporaryIgnoreTables
    @GetMapping("/detail/{userId}")
    public SysUser getUserDetailByUserId(@PathVariable Long userId) {
        if (SecurityUtils.getTenantId() == 9999L || SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_dept", "sys_user_role", "sys_role"));
        }
        SysUser sysUser = userService.selectUserById(userId);
        SecurityUtils.removeTemporaryIgnoreTables();
        return sysUser;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_user", "sys_dept", "d", "u"})
    @GetMapping("/name/info/permissions")
    public R<String> getPermissions() {
        //调整下查询顺序 将租户id塞入当前查询线程 --或者直接让权限过滤忽略租户查询 毕竟账号id唯一 目前选择直接忽略查询 后续此处修改
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        return R.ok(JSONArray.toJSONString(new ArrayList<>(permissionService.getMenuPermission(user))));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo(@RequestParam(required = false) String tenantId) {
        //调整下查询顺序 将租户id塞入当前查询线程 --或者直接让权限过滤忽略租户查询 毕竟账号id唯一 目前选择直接忽略查询 后续此处修改
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());

        // 只有集团租户下才传这个tenantId值
        if (StrUtils.isNotEmpty(tenantId) && !"null".equals(tenantId)) {
            SecurityUtils.setTenantId(tenantId);
            user.setRoles(roleService.selectRolesByUserId(user.getUserId()));
            user.setRoles(user.getRoles().stream().filter(role -> role.getTenantId() == Long.parseLong(tenantId)).collect(Collectors.toList()));
        }

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合,返回到前端，展示菜单页面
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 查询租户信息
        SysTenant tenant = sysTenantService.selectSysTenantById(StrUtils.isNotEmpty(tenantId) ? Long.parseLong(tenantId) : user.getTenantId());
        AjaxResult ajax = AjaxResult.success();
        user.setTenantId(SecurityUtils.getTenantId());
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("tenantName", Objects.nonNull(tenant) ? tenant.getTenantName() : "");//系统名称同步租户名称
        ajax.put("tenantType", Objects.nonNull(tenant) ? tenant.getTenantType() : "");
        ajax.put("logUrl", tenant.getLogoUrl());
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */

    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StrUtils.isNotNull(userId)) {
            SysUser sysUser = getUserDetailByUserId(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 获取指定岗位的分页人员列表
     */
    @GetMapping("/page/{postCode}")
    public AjaxResult getPointPostUserList(@PathVariable(value = "postCode", required = true) String postCode,
                                           @RequestParam(name = "nickName", required = false) String nickName,
                                           @RequestParam(name = "phoneNumber", required = false) String phoneNumber) {
        return AjaxResult.success(userService.selectPointPostUserList(postCode, nickName, phoneNumber));
    }

    /**
     * 新增用户
     */
    @TemporaryIgnoreTables
    @RequiresPermissions("system:user:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        //此处需要确定集团管理员为哪个租户具体的部门添加人员
        if (SecurityUtils.getTenantType() == 1) {
            if (user.getTenantId() == null) {
                throw new ServiceException("未找到人员所在的租户信息");
            } else {
                SecurityUtils.setTemporaryIgnoreTables(Collections.singletonList("sys_user_role"));
            }
        }

        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，登录账号已存在");
        } else if (StrUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，手机号码已存在");
        } else if (StrUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateById(SecurityUtils.getUserId());
        if (user.getTenantId() == null) {
            user.setTenantId(SecurityUtils.getTenantId());
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        SysUser beforeSysUser = userService.selectUserByUserId(user.getUserId(), null);
        if (!beforeSysUser.getTenantId().equals(user.getTenantId())) {
            return error("暂不支持教职工跨组织调整");
        }
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getNickName() + "'失败，登录账号已存在");
        } else if (StrUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getNickName() + "'失败，手机号码已存在");
        } else if (StrUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getNickName() + "'失败，邮箱账号已存在");
        }
        if ("1".equals(user.getUserStatus())) {
            SysReClassUser sysReClassUser = new SysReClassUser();
            sysReClassUser.setBindUserId(user.getUserId());
            List<SysReClassUser> reClassUserList = sysReClassUserService.selectSysReClassUserList(sysReClassUser);
            //需求要求解除班级时提示，人为解绑，而不是离职时自动解绑班级。
            if (CollectionUtils.isNotEmpty(reClassUserList)) {
                return error("该教职工已绑定班级，不可离职");
            }
        }
        //获取该用户变更前的岗位
        List<Long> postIds = postService.selectPostListByUserId(user.getUserId());
        Long[] beforePostIds = postIds.stream().toArray(Long[]::new);
        //判断人员是否更换岗位
        if (!Arrays.equals(user.getPostIds(), beforePostIds) && ArrayUtils.isNotEmpty(beforePostIds)) {
            //目前系统为单人单岗，一个人只有一个岗位
            SysPost postInfo = postService.selectPostById(beforePostIds[0]);

            //判断当前用户所在的岗位是否已绑定班级，如果绑定需要先解绑班级
            SysReClassUser sysReClassUser = new SysReClassUser();
            sysReClassUser.setBindUserId(user.getUserId());
            String userPosition = "zbjs".equals(postInfo.getPostCode()) ? "1" : ("pbjs".equals(postInfo.getPostCode()) ? "2" :
                    ("byy".equals(postInfo.getPostCode()) ? "3" : ""));
            sysReClassUser.setBindUserPosition(userPosition);
            List<SysReClassUser> reClassUserList = sysReClassUserService.selectSysReClassUserList(sysReClassUser);
            //需求要求提示需要先解除班级，人为解绑，而不是更换岗位时自动解绑班级
            if (CollectionUtils.isNotEmpty(reClassUserList)) {
                return error("该人员现岗位" + postInfo.getPostName() + "已绑定班级，解绑班级后方可调整岗位");
            }
        }
        if (!beforeSysUser.getDeptId().equals(user.getDeptId())) {
            //清除各部门使用当前用户的主管信息
            user.getParams().put("clearLeader", "Y");
        } else {
            user.getParams().put("clearLeader", "N");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateById(SecurityUtils.getUserId());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户基本信息
     */
    @RequiresPermissions("system:user:remove")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        for (Long userId : userIds) {
            SysReClassUser sysReClassUser = new SysReClassUser();
            sysReClassUser.setBindUserId(userId);
            List<SysReClassUser> reClassUserList = sysReClassUserService.selectSysReClassUserList(sysReClassUser);
            //需求要求解除班级时提示，人为解绑，而不是离职时自动解绑班级。
            if (CollectionUtils.isNotEmpty(reClassUserList)) {
                return error("该教职工已绑定班级，不可删除");
            }
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:resetPwd")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        //默认密码采用随机生成，此接口注意，前端仅传了一个userId
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        String newPassword = SecurityUtils.encryptPassword(randomPassword);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(newPassword);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user), randomPassword);
    }

    /**
     * 用户在职状态更新
     */
    @RequiresPermissions("system:user:changeStatus")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if ("1".equals(user.getUserStatus())) {
            SysReClassUser sysReClassUser = new SysReClassUser();
            sysReClassUser.setBindUserId(user.getUserId());
            List<SysReClassUser> reClassUserList = sysReClassUserService.selectSysReClassUserList(sysReClassUser);
            //需求要求解除班级时提示，人为解绑，而不是离职时自动解绑班级。
            if (CollectionUtils.isNotEmpty(reClassUserList)) {
                return error("该教职工已绑定班级，不可离职");
            }
        }
        if ("1".equals(user.getUserStatus()) && StrUtils.isNotEmpty(user.getAccountStatus())) {
            //离职时，将用户账户更改为禁用状态
            user.setAccountStatus(ConstantUtils.ACCOUNT_STATUS_1);
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        int result = userService.updateUserStatus(user);
        // 强制该用户退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getUserid())
                    && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                redisService.deleteObject(key);
            }
        }
        return toAjax(result);
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:auth:role")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 根据角色key获取对应的用户Id
     */
    @GetMapping("/role/check/{roleKey}")
    public AjaxResult selectUserAndRoleList(@PathVariable("roleKey") String roleKey) {
        SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_user_role", "sys_role"));
        List<SysUser> sysUserList = userService.selectUserAndRoleList(roleKey);
        SecurityUtils.removeTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_user_role", "sys_role"));
        List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        return AjaxResult.success(userIdList);
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:auth:role")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:deptTree")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:deptTree:new")
    @GetMapping("/deptTree/new")
    public AjaxResult newDeptTree(SysDept dept) {
        return success(deptService.selectNewDeptTreeList(dept));
    }

    @GetMapping("/appUserInfo/{account}")
    public R<LoginUser> getAppUserInfo(@PathVariable("account") String account) {
        SysUser sysUser = userService.selectUserByPhone(account);
        // 如果用户不存在，创建新用户并返回
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setPhonenumber(account)
                    .setNickName(account)
                    .setTenantId(SecurityUtils.getTenantId());
            userService.insertUserByVote(sysUser);
            // 创建新的 LoginUser 对象并返回
            LoginUser newUserVo = new LoginUser();
            newUserVo.setSysUserTempalte(sysUser);
            newUserVo.setSysUser(sysUser);
            return R.ok(newUserVo);
        }
        // 判断当前用户的状态是否被禁用
        if ("1".equals(sysUser.getAccountStatus())) {
            return R.loginFail("对不起，您的手机号：" + account + " 已被禁用");
        }
        // 判断用户所在的租户管理员状态是否被禁用
//        Long tenantId = sysUser.getTenantId();
//        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
//        if (sysTenant != null && sysTenant.getStatus() == 1) {
//            return R.loginFail("对不起，您的手机号：" + account + " 已被禁用");
//        }
//        // 判断用户对应租户的父级租户管理员状态是否被禁用
//        SysTenant parentSysTenant = sysTenantService.getParentTenantInfo(tenantId);
//        if (parentSysTenant != null && parentSysTenant.getStatus() == 1) {
//            return R.loginFail("对不起，您的手机号：" + account + " 已被禁用");
//        }
        // 创建 LoginUser 对象并返回
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUserTempalte(sysUser);
        sysUserVo.setSysUser(sysUser);
        return R.ok(sysUserVo);
    }

    /**
     * 根据openId查询用户
     *
     * @param wxCode
     * @return
     */
    @GetMapping("/selectByOpenId/{wxCode}")
    public R<LoginUser> selectByOpenId(@PathVariable("wxCode") String wxCode) {
        SysUser sysUser = userService.selectByOpenId(wxCode);
        //判断当前用户的状态是否被禁用
        if ("1".equals(sysUser.getAccountStatus())) {
            return R.loginFail("对不起，用户：" + sysUser.getNickName() + " 已被禁用");
        }
        //判断用户所在的租户管理员状态是否被禁用
        Long tenantId = sysUser.getTenantId();
        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
        if (sysTenant != null && sysTenant.getStatus() == 1) {
            return R.loginFail("对不起，用户：" + sysUser.getNickName() + " 已被禁用");
        }
        //判断用户对应租户的父级租户管理员状态是否被禁用
        SysTenant parentSysTenant = sysTenantService.getParentTenantInfo(tenantId);
        if (parentSysTenant != null && parentSysTenant.getStatus() == 1) {
            return R.loginFail("对不起，用户：" + sysUser.getNickName() + " 已被禁用");
        }
        // 查询租户信息
        SysTenant tenant = sysTenantService.selectSysTenantById(sysUser.getTenantId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUserTempalte(sysUser);
        sysUserVo.setSysUser(sysUser);
        if (Objects.nonNull(tenant)) {
            sysUserVo.setTenantEndDate(tenant.getTenantEndTime());
            sysUserVo.setTenantStatus(tenant.getStatus());
            sysUserVo.setTenantType(tenant.getTenantType());
            sysUserVo.setTenantName(tenant.getTenantName());
        }
        return R.ok(sysUserVo);
    }


    /**
     * 获取用户昵称
     */
    @GetMapping("/getUserName/{userIds}")
    public AjaxResult getUserName(@PathVariable("userIds") List<Long> userIds) {
        return AjaxResult.success(userService.selectByUserIdS(userIds));
    }

    /**
     * 获取当前用户信息
     */
    @Transactional
    @GetMapping("/voteInfo/{username}")
    public R<LoginUser> getVoteUserInfo(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StrUtils.isNull(sysUser)) {
            return R.loginFail("用户名或密码错误");
        }
//        //判断当前用户的状态是否被禁用
//        if ("1".equals(sysUser.getAccountStatus())) {
//            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
//        }
//        //判断用户所在的租户管理员状态是否被禁用
//        Long tenantId = sysUser.getTenantId();
//        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
//        if (sysTenant != null && sysTenant.getStatus() == 1) {
//            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
//        }
//        //判断用户对应租户的父级租户管理员状态是否被禁用
//        SysTenant parentSysTenant = sysTenantService.getParentTenantInfo(tenantId);
//        if (parentSysTenant != null && parentSysTenant.getStatus() == 1) {
//            return R.loginFail("对不起，您的账号：" + username + " 已被禁用");
//        }
        // 查询租户信息

        SysTenant tenant = sysTenantService.selectSysTenantById(sysUser.getTenantId());

        // 租户类型 1 集团租户 2 幼儿园租户有集团 3 幼儿园租户无集团
        SecurityUtils.setTenantType(Objects.isNull(tenant) ? "3" : tenant.getTenantType().toString());
        SecurityUtils.setTenantId(Objects.isNull(tenant) ? "" : tenant.getId().toString());
        // 角色集合

        Set<String> roles = permissionService.getRolePermission(sysUser);

        // 权限集合,写往缓存里面，校验接口权限
       // Set<String> permissions = permissionService.getMenuPermissionByMultiTenant(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUserTempalte(sysUser);
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setSysRolesList(sysUser.getRoles());
      //  sysUserVo.setPermissions(permissions);
        if (Objects.nonNull(tenant)) {
            sysUserVo.setTenantEndDate(tenant.getTenantEndTime());
            sysUserVo.setTenantStatus(tenant.getStatus());
            sysUserVo.setTenantType(tenant.getTenantType());
            sysUserVo.setTenantName(tenant.getTenantName());
        }
        return R.ok(sysUserVo);
    }

}
