package org.jeecg.modules.system.controller;


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.gitee.sop.servercommon.annotation.Open;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.system.bo.queryListUserByDepIdBo;
import org.jeecg.modules.system.constant.AreaConstant;
import org.jeecg.modules.system.constant.SendChangeMsgConstant;
import org.jeecg.modules.system.constant.UserConstant;
import org.jeecg.common.util.encryption.EncryptedString;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.modules.oauth2_server.util.AesUtil;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.enums.RoleEnum;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.to.SysUserRoleTo;
import org.jeecg.modules.system.to.SysUserTo;
import org.jeecg.modules.system.vo.SysDepartUsersVO;
import org.jeecg.modules.system.vo.SysUserRoleVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@Api(tags="sys_user")
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysChangeMsgService sysChangeMsgService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysAreaService sysAreaService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysDepartRoleUserService departRoleUserService;
    @Autowired
    private ISysDepartRoleService departRoleService;
    @Autowired
    private ISysTenantService tenantService;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Resource
    private BaseCommonService baseCommonService;


    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */

    @ApiOperation(value="sys_user-用户列表", notes="sys_user-用户列表")
//    @PermissionData(pageComponent = "system/UserList")
//    @RequiresRoles("scjg_001")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysUser>> queryPageList(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne("username","_reserve_user_external");
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
        if(userIds!=null && userIds.size()>0){
            Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item->{
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }


    @AutoLog(value = "sys_user-添加数据")
    @ApiOperation(value="sys_user-添加新数据", notes="sys_user-添加新数据")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Transactional
    public Result<?> add(@RequestBody JSONObject jsonObject) {
        Result<Object> result = new Result<>();
        String selectedRoles = jsonObject.getString("selectedroles");
        String selectedDeparts = jsonObject.getString("selecteddeparts");
        String[] split = selectedRoles.split(",");
        List<String> roleList = Arrays.asList(split);
        SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
        //获取用户权限信息
        boolean effect = sysUserService.judgeAuthority(roleList, selectedDeparts, user);
        if (!effect){
            return Result.noauth("用户权限不足");
        }
        try {
            /**
             * 判断部门和区划是否已有部门管理员和区划管理员角色
             */
            if (!StringUtils.isEmpty(selectedRoles)) {
                List<SysRole> sysRoles = sysRoleService.queryListByIds(selectedRoles);
                //获取部门角色
                SysRole deptRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.DeptAdmin.getRoleCode())).findFirst().orElse(null);
                if (deptRole != null) {
                    String deptRs = sysUserService.getDeptUser(deptRole.getId(), selectedDeparts);
                    if (!StringUtils.isEmpty(deptRs)) {
                        return result.error500("一个组织机构仅能有一个部门管理员，当前部门管理员账号为:["+deptRs+"]");
                    }
                }
                //获取区划角色
                SysRole areaRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.AreaAdmin.getRoleCode())).findFirst().orElse(null);
                //获取部门所在区划
                SysDepart depart = sysDepartService.getById(selectedDeparts);
                if (areaRole != null) {
                    String areaRs = sysUserService.getAreaUser(areaRole.getId(), depart.getAreaId());
                    if (!StringUtils.isEmpty(areaRs)) {
                        return result.error10002("一个行政区划仅能有一个地区管理员，当前区划管理员账号为:["+areaRs+"]");
                    }
                }
            }
            user.setCreateTime(new Date());//设置创建时间
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode;
            String otherName =UserConstant.OTHER_NAME_PREFIX+"_"+user.getUsername();
            user.setOtherName(otherName);
            String psw = UserConstant.INITIALIZING_PASSWORD;
            if (user.getPassword() != null){
                passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            }else{
                passwordEncode = PasswordUtil.encrypt(user.getUsername(),psw, salt);
            }
            user.setPassword(passwordEncode);
            user.setClearCard(user.getIdCard());
            String idCard = user.getIdCard();
            String font = idCard.substring(UserConstant.CUT_CARD_START, UserConstant.CUT_CARD_MID);
            String back = idCard.substring(idCard.length() - UserConstant.CUT_CARD_END);
            String idCardCheck = font + "***********" + back;
            user.setIdCardCheck(idCardCheck);

            String encryptIdCard = AesUtil.encrypt(user.getIdCard(), EncryptedString.key,EncryptedString.iv);
            user.setIdCard(encryptIdCard);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            SysUser id_card = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getClearCard, user.getClearCard()).eq(SysUser::getStatus,1).last("limit 1"));
            if(!oConvertUtils.isEmpty(id_card)){
                return result.error10001("身份证以被"+id_card.getAreaName()+id_card.getRealname()+"占用");
            }
            SysUser phone = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getPhone, user.getPhone()).eq(SysUser::getStatus,1).last("limit 1"));
            if (!oConvertUtils.isEmpty(phone)){
                return result.error10006("手机号被"+phone.getAreaName()+phone.getRealname()+"占用");
            }
            sysUserService.addUserWithRole(user, selectedRoles);
            sysUserService.addUserWithDepart(user, selectedDeparts);

            SysDepart depart = sysDepartService.getById(selectedDeparts);
            tenantService.sendUserMsg(user,depart,SendChangeMsgConstant.INSERT);
            List<SysRole> sysRoles = sysRoleService.queryListByIds(selectedRoles);
            for (SysRole sysRole : sysRoles) {
                tenantService.sendUserRoleMsg(user,sysRole,depart,SendChangeMsgConstant.INSERT);
            }
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("姓名",user.getRealname());
            hashMap.put("账号",user.getUsername());
            hashMap.put("密码",psw);
            result.setResult(hashMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @RequestMapping(value = "/getParentList",method = RequestMethod.GET)
    public Object queryUserAndArea(){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser userById = sysUserService.getUserById(loginUser.getId());
        String areaName = userById.getAreaName();
        Map<String, Object> map = new HashMap<>();

        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return null;
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");
        QueryWrapper<SysDepart> wrapper = new QueryWrapper<SysDepart>();
        String[] parentIdPath = new String[0];
        if(!oConvertUtils.isEmpty(areaName)){
            SysArea sysArea = sysAreaService.getOne(new QueryWrapper<SysArea>().eq("area_name", areaName));
            parentIdPath = sysAreaService.findParentIdPath(sysArea.getId());
        }
        if (isAdmin){
            map.put("role","isAdmin");
        }else if(isBasicOperation){
            map.put("role","isBasicOperation");
        }else if (isAreaAdmin){
            map.put("role","isAreaAdmin");
        }else if (isDeptAdmin){
            map.put("role","isDeptAdmin");
        }else {
            map.put("role","isAverageUser");
        }
        map.put("parentIdPath",parentIdPath);
        return map;
    }


    @ApiOperation(value="sys_user-编辑数据", notes="sys_user-编辑数据")
    @AutoLog(value = "sys_user-编辑数据")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @Transactional
    public Result<Object> edit(@RequestBody JSONObject jsonObject) {
        Result<Object> result = new Result<>();
        try {
            SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
            baseCommonService.addLog("编辑用户，id： " +jsonObject.getString("id") ,CommonConstant.LOG_TYPE_2, 2);
            if(sysUser==null) {
                result.error500("未找到对应实体");
            }else {
                String status = jsonObject.getString("status");
                int sta = Integer.parseInt(status);
                SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
                user.setIdCard(sysUser.getIdCard());
                user.setClearCard(sysUser.getClearCard());
                user.setIdCardCheck(sysUser.getIdCardCheck());
                user.setUpdateTime(new Date());
                String roles = jsonObject.getString("selectedroles");
                String departs = jsonObject.getString("selecteddeparts");
                String[] split = roles.split(",");
                List<String> roleLists = Arrays.asList(split);
                boolean effect = sysUserService.judgeAuthority(roleLists, departs, user);
                if (!effect){
                    return Result.noauth("用户权限不足");
                }

                SysDepart sysDepart = sysDepartService.getById(departs);
                List<SysRole> sysRoles = sysRoleService.queryListByIds(roles);
                List<SysRole> sysRoless = sysRoleService.getByUserId(sysUser.getId());
                List<SysRole> roleList = new ArrayList<>();

                roleList.addAll(sysRoles);
                roleList.removeAll(sysRoless);
                roleList.addAll(sysRoless);

                List<SysRole> roleAllList = new ArrayList<SysRole>();
                roleAllList.addAll(roleList);
                roleAllList.removeAll(sysRoless);
                roleList.removeAll(sysRoles);

                //获取部门角色
                SysDepart depart = sysDepartService.getValidDeptById(departs);
                if (sta!=0){
                    SysRole deptRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.DeptAdmin.getRoleCode())).findFirst().orElse(null);
                    if (deptRole != null) {
                        String deptUser = sysUserService.getDeptUser(deptRole.getId(), departs);
                        SysUser sUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", deptUser).eq("status",1).last("limit 1"));
                        if (!StringUtils.isEmpty(deptUser)&&!oConvertUtils.isEmpty(sUser)&&!sUser.getId().equals(jsonObject.getString("id"))) {
                            return result.error500("一个组织机构仅能有一个部门管理员，当前部门管理员账号为:["+deptUser+"]");
                        }
                    }
                    //获取区划角色
                    SysRole areaRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.AreaAdmin.getRoleCode())).findFirst().orElse(null);
                    //获取部门所在区划
                    if (areaRole != null&&!oConvertUtils.isEmpty(depart)) {
                        String areaUser = sysUserService.getAreaUser(areaRole.getId(), depart.getAreaId());
                        SysUser sUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", areaUser).last("limit 1"));
                        if (!StringUtils.isEmpty(areaUser)&&!oConvertUtils.isEmpty(sUser)&&!sUser.getId().equals(jsonObject.getString("id"))) {
                            return result.error10002("一个行政区划仅能有一个地区管理员，当前区划管理员账号为:["+areaUser+"]");
                        }
                    }
                    //校验身份证
                    int count = sysUserService.count(new QueryWrapper<SysUser>().eq("clear_card", sysUser.getClearCard()).ne("id", sysUser.getId()).eq("status", 1));
                    if (count>0){
                        SysUser id_card = sysUserService.getOne(new QueryWrapper<SysUser>().eq("clear_card", sysUser.getClearCard()).ne("id",sysUser.getId()).eq("status",1).last("limit 1"));
                        if (oConvertUtils.isNotEmpty(id_card)){
                            return result.error10001("身份证以被"+id_card.getAreaName()+id_card.getRealname()+"占用");
                        }
                    }
                    //校验手机
                    int count1 = sysUserService.count(new QueryWrapper<SysUser>().eq("phone", user.getPhone()).ne("id", user.getId()).eq("status", 1));
                    if (count1>0){
                        SysUser phone = sysUserService.getOne(new QueryWrapper<SysUser>().eq("phone", user.getPhone()).ne("id", user.getId()).eq("status", 1).last("limit 1"));
                        if (oConvertUtils.isNotEmpty(phone)){
                            return result.error10006("手机号被"+phone.getAreaName()+phone.getRealname()+"占用");
                        }
                    }

                }
                sysUserService.editUserWithRole(user, roles);
                sysUserService.editUserWithDepart(user, departs);
                sysUserService.updateNullPhoneEmail();
                if (!roleAllList.isEmpty()){
                    for (SysRole sysRole : roleAllList) {
                        tenantService.sendUserRoleMsg(user,sysRole,sysDepart,SendChangeMsgConstant.UPDATE);
                    }
                }
                if (!roleList.isEmpty()){
                    for (SysRole sysRole : roleList) {
                        tenantService.sendUserRoleMsg(user,sysRole,sysDepart, SendChangeMsgConstant.UPDATE);
                    }
                }
                tenantService.sendUserMsg(user,depart, SendChangeMsgConstant.UPDATE);
                LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                baseCommonService.addLog("用户名: "+loginUser.getRealname()+
                                "在sys_user表中编辑了"+user, CommonConstant.LOG_TYPE_2 ,
                        CommonConstant.OPERATE_TYPE_3,loginUser);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除用户
     */
    @AutoLog(value = "sys_user-删除数据")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        baseCommonService.addLog("删除用户，id： " +id ,CommonConstant.LOG_TYPE_2, 3);
        this.sysUserService.deleteUser(id);
        return Result.ok("删除用户成功");
    }

    /**
     * 批量删除用户
     */
    @AutoLog(value = "sys_user-批量删除数据")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        baseCommonService.addLog("批量删除用户， ids： " +ids ,CommonConstant.LOG_TYPE_2, 3);
        this.sysUserService.deleteBatchUsers(ids);
        return Result.ok("批量删除用户成功");
    }

    /**
     * 冻结&解冻用户
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "sys_user-冻结&解冻用户")
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public Result<SysUser> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("status");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if(oConvertUtils.isNotEmpty(id)) {
                    this.sysUserService.update(new SysUser().setStatus(Integer.parseInt(status)),
                            new UpdateWrapper<SysUser>().lambda().eq(SysUser::getId,id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败"+e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }

    @ApiOperation(value="sys_user-通过id查询", notes="sys_user-通过id查询")
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysUser> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysUser> result = new Result<SysUser>();
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysUser);
            result.setSuccess(true);
        }
        return result;
    }

    @ApiOperation(value="sys_user-查询全部user", notes="sys_user-查询全部user")
    @RequestMapping(value = "/queryUserAll", method = RequestMethod.GET)
    public Result<IPage<SysUser>> queryUserAll(@RequestParam(name="clientId",required=false) String client_id,
                                               @RequestParam(name="clientSercret",required=false) String client_sercret){
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        List<SysUser> list = sysUserService.list();
        IPage<SysUser> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        if (list == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(pageList);
            result.setSuccess(true);
        }
        return result;
    }

    @ApiOperation(value="sys_user-userid查询角色", notes="sys_role-userid查询角色")
    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    public Result<HashMap<String, String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        Result<HashMap<String, String>> result = new Result<>();
        HashMap<String, String> map = new HashMap<>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
        List<String> roleIds = new ArrayList<>();
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                roleIds.add(sysUserRole.getRoleId());

            }
            String roleIdStr = roleIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            map.put("userId",userid);
            map.put("roleId",roleIdStr);
            result.setSuccess(true);
            result.setResult(map);
        }
        return result;
    }

    @ApiOperation(value="sys_user查询全部角色", notes="sys_role-查询全部角色")
    @RequestMapping(value = "/queryAllUserRole", method = RequestMethod.GET)
    public Result<List<SysUserRole> > queryAllUserRole( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        Result<List<SysUserRole> > result = new Result<>();
        List<SysUserRole> userRole = sysUserRoleService.list(null);
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        }
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }


    /**
     *  校验用户账号是否唯一<br>
     *  可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(SysUser sysUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>(sysUser));
            if (user != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 重置密码
     */
    @ApiOperation(value="sys_user-重置密码", notes="sys_user-重置密码")
    @AutoLog(value = "sys_user-重置密码")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.PUT)
    @Transactional
    public Result<?> resetPassword(@RequestBody SysUser sysUser) {
        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
        if (u == null) {
            return Result.error("用户不存在！");
        }
        if (u.getUsername().equals(UserConstant.ADMIN_USER)){
            return Result.noauth("无法修改超级管理员账号密码");
        }
        boolean b = sysUserService.checkChangePassword(sysUser);
        if (!b){
            return Result.noauth("访问权限认证未通过");
        }
        sysUser.setId(u.getId());

        return sysUserService.resetPassword(sysUser);
    }


    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
    public Result<List<DepartIdModel>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        Result<List<DepartIdModel>> result = new Result<>();
        try {
            List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
            if (depIdModelList != null && depIdModelList.size() > 0) {
                result.setSuccess(true);
                result.setMessage("查找成功");
                result.setResult(depIdModelList);
            } else {
                result.setSuccess(false);
                result.setMessage("查找失败");
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("查找过程中出现了异常: " + e.getMessage());
            return result;
        }

    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    @RequestMapping("/randName")
    public String randName(){
        String filename= RandomStringUtils.randomAlphanumeric(8);
        return filename;
    }
    /**
     * 根据部门id查询用户信息
     *
     * @param
     * @return
     */
    @AutoLog(value = "根据部门id查询用户信息")
    @ApiOperation(value="根据部门id查询用户信息", notes="根据部门id查询用户信息")
    @RequestMapping(value = "/queryListUserByDepId", method = RequestMethod.POST)
    public Result<Page<SysUser>> queryListUserByDepId(@RequestBody queryListUserByDepIdBo queryListUserByDepIdBo) throws Exception {
        Integer pageNo = queryListUserByDepIdBo.getPageNo();
        Integer pageSize = queryListUserByDepIdBo.getPageSize();
        String id = queryListUserByDepIdBo.getDepId();
        String username = queryListUserByDepIdBo.getUsername();
        String realname = queryListUserByDepIdBo.getRealname();
        String enPhone = queryListUserByDepIdBo.getPhone();
        String enIdCard = queryListUserByDepIdBo.getIdCard();
        String phone = AesUtil.decrypt(enPhone);
        String idCard = AesUtil.decrypt(enIdCard);
        Result<Page<SysUser>> result = new Result<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if(userOtherInfo.get("isAreaAdmin").equals(false) && userOtherInfo.get("isDeptAdmin").equals(false) && userOtherInfo.get("isAdmin").equals(false) &&userOtherInfo.get("isBasicOperation").equals(false)){
            SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(loginUser.getId());
            Page<SysUser> page = new Page<>(pageNo, pageSize);
            if (id.equals(sysUserDepart.getDepId())){
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.eq("id", loginUser.getId());
                if (oConvertUtils.isNotEmpty(username)){
                    wrapper.like("username", username);
                }
                if (oConvertUtils.isNotEmpty(realname)){
                    wrapper.like("realname", realname);
                }
                if (oConvertUtils.isNotEmpty(phone)){
                    wrapper.eq("phone", phone);
                }
                if (oConvertUtils.isNotEmpty(idCard)){
                    wrapper.like("clear_card", idCard);
                }
                Page<SysUser> page1 = sysUserService.page(page, wrapper);
                //Page<SysUser> page1 = sysUserService.page(page, new QueryWrapper<SysUser>().eq("id", loginUser.getId()));
                page1.getRecords().forEach(item->{
                    try {
//                        String encrypt  = AesUtil.encrypt(item.getPhone());
//                        item.setPhone(encrypt);
                        item.setClearCard("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                result.setResult(page1);
            }else {
                result.setResult(page);
            }
        }else {
            Page<SysUser> sysUserPage = sysUserDepartService.queryUserByDepCode(id, realname,username,phone,idCard, pageNo, pageSize);
            sysUserPage.getRecords().forEach(item->{
                try {
//                    String encrypt  = AesUtil.encrypt(item.getPhone());
//                    item.setPhone(encrypt);
                    item.setClearCard("");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            result.setResult(sysUserPage);
        }
        return result;
    }


    @AutoLog(value = "queryTest-通过登录账号和姓名查询")
    @ApiOperation(value="queryTest-通过登录账号和姓名查询", notes="queryTest-通过登录账号和姓名查询")
    @GetMapping(value = "/queryUserTreeUnchecked")
    public Result<?> queryUserTreeUnchecked( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                             @RequestParam(name="departSimpleName", required = true) String simple,
                                             String username,String realname,String phone,String idCard) {
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> list;
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return Result.noauth("该账号无权限信息");
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");
        if (!isBasicOperation&&!isAdmin){
            if (isAreaAdmin){
                list = sysUserService.querySysUserPageBySimple(page, currentArea.getId(), username, realname, phone,idCard,simple);
            }else if (isDeptAdmin){
                int count = sysDepartService.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
                if(count>0){
                    list =sysUserService.querySysUserPageByPSimple(page,currentDept.getId(), username, realname, phone,idCard,simple);
                }else if (oConvertUtils.isNotEmpty(currentDept.getParentId())){
                    list = sysUserService.querySysUserPageByCSimple(page,currentDept.getId(),currentDept.getParentId(), username, realname, phone,idCard,simple);
                }else {
                    list = sysUserService.querySysUserPageBySimpleId(page,currentDept.getId(), username, realname, phone,idCard,simple);
                }
            }else {
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                if(currentDept.getDepartSimpleName().contains(simple)){
                    wrapper.eq("id", loginUser.getId());
                    if (oConvertUtils.isNotEmpty(username)){
                        wrapper.like("username", username);
                    }
                    if (oConvertUtils.isNotEmpty(realname)){
                        wrapper.like("realname", realname);
                    }
                    if (oConvertUtils.isNotEmpty(phone)){
                        wrapper.eq("phone", phone);
                    }
                    if (oConvertUtils.isNotEmpty(idCard)){
                        wrapper.like("clear_card", idCard);
                    }
                    list = sysUserService.page(page, wrapper);
                }else {
                    wrapper.eq("id", "loginUser");
                    list = sysUserService.page(page, wrapper);
                }
            }
        }else {
            list = sysUserService.querySysUserPageBySimple(page, "81", username, realname, phone,idCard,simple);
        }
        list.getRecords().forEach(item->{
            try {
                String encrypt  = AesUtil.encrypt(item.getPhone());
                item.setPhone(encrypt);
                item.setClearCard("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return Result.OK(list);
    }


    /**
     * 通过登录账号和姓名查询
     *
     * @param username realname
     * @return
     */
    @AutoLog(value = "sys_area-通过登录账号和姓名查询")
    @ApiOperation(value = "sys_area-通过登录账号和姓名查询", notes = "sys_area-通过登录账号和姓名查询")
    @GetMapping(value = "/queryByNameAndReal")
    public Result<?> queryByName(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 String username, String realname, String phone, String idCard) {
        //IPage<SysUser> list = sysUserService.queryPage(pageNo,pageSize,username,realname,departIds,phone);
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> list;
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return null;
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");
        if (!isBasicOperation&&!isAdmin){
            if (isAreaAdmin){
                if (!currentArea.getId().equals(AreaConstant.SC_AREA_ID)){
                    list = sysUserService.querySysUserPage(page, currentArea.getId(), username, realname, phone,idCard);
                }else {
                    list = sysUserService.queryPage(page,username,realname,"1",phone,idCard);
                }
            }else if (isDeptAdmin){
                int count = sysDepartService.count(new QueryWrapper<SysDepart>().eq("parent_id", currentDept.getId()));
                if(count>0){
                    list =sysUserService.querySysUserPageByPDept(page,currentDept.getId(), username, realname, phone,idCard);
                }else if (oConvertUtils.isNotEmpty(currentDept.getParentId())){
                    list = sysUserService.querySysUserPageByDept(page,currentDept.getId(),currentDept.getParentId(), username, realname, phone,idCard);
                }else {
                    list = sysUserService.querySysUserPageByDeptId(page,currentDept.getId(), username, realname, phone,idCard);
                }
            }else {
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.eq("id", loginUser.getId());
                if (oConvertUtils.isNotEmpty(username)){
                    wrapper.like("username", username);
                }
                if (oConvertUtils.isNotEmpty(username)){
                    wrapper.like("realname", realname);
                }
                if (oConvertUtils.isNotEmpty(phone)){
                    wrapper.eq("phone", phone);
                }
                if (oConvertUtils.isNotEmpty(idCard)){
                    wrapper.like("clear_card", idCard);
                }
                list = sysUserService.page(page, wrapper);
            }
        }else {
            list = sysUserService.queryPage(page,username,realname,"1",phone,idCard );
        }
        list.getRecords().forEach(item->{
            try {
                String encrypt  = AesUtil.encrypt(item.getPhone());
                item.setPhone(encrypt);
                item.setClearCard("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return Result.OK(list);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysUser
     */
    @RequestMapping(value = "/exportXls")
    @RequiresPermissions("user:export:excel")
    public ModelAndView exportXls(SysUser sysUser,HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if(!oConvertUtils.isEmpty(selections)){
            queryWrapper.in("id",selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SysUser> pageList = sysUserService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("用户列表数据", "导出人:"+user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("user:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response)throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUser> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), SysUser.class, params);
                for (int i = 0; i < listSysUsers.size(); i++) {
                    SysUser sysUserExcel = listSysUsers.get(i);
                    if (StringUtils.isBlank(sysUserExcel.getPassword())) {
                        // 密码默认为 “123456”
                        sysUserExcel.setPassword("123456");
                    }
                    // 密码加密加盐
                    String salt = oConvertUtils.randomGen(8);
                    sysUserExcel.setSalt(salt);
                    String passwordEncode = PasswordUtil.encrypt(sysUserExcel.getUsername(), sysUserExcel.getPassword(), salt);
                    sysUserExcel.setPassword(passwordEncode);
                    try {
                        sysUserService.save(sysUserExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage().toLowerCase();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：用户名已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_WORK_NO)) {
                            errorMessage.add("第 " + lineNumber + " 行：工号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_PHONE)) {
                            errorMessage.add("第 " + lineNumber + " 行：手机号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_EMAIL)) {
                            errorMessage.add("第 " + lineNumber + " 行：电子邮件已经存在，忽略导入。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 批量将部门和用户信息建立关联关系
                    String departIds = sysUserExcel.getDepartIds();
                    if (StringUtils.isNotBlank(departIds)) {
                        String userId = sysUserExcel.getId();
                        String[] departIdArray = departIds.split(",");
                        List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
                        for (String departId : departIdArray) {
                            userDepartList.add(new SysUserDepart(userId, departId));
                        }
                        sysUserDepartService.saveBatch(userDepartList);
                    }

                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
    }

    /**
     * @功能：根据id 批量查询
     * @param userIds
     * @return
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<SysUser>> queryByIds(@RequestParam String userIds) {
        Result<Collection<SysUser>> result = new Result<>();
        String[] userId = userIds.split(",");
        Collection<String> idList = Arrays.asList(userId);
        Collection<SysUser> userRole = sysUserService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }



    /**
     * 用户修改密码
     */

    @ApiOperation(value="sys_user-用户修改密码", notes="sys_user-用户修改密码")
    @AutoLog(value = "sys_user-用户修改密码")
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    @Transactional
    public Result<?> changePassword(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");
        SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if(user==null) {
            return Result.error("用户不存在！");
        }
        if (user.getUsername().equals(UserConstant.ADMIN_USER)){
            return Result.noauth("无法修改超级管理员账号密码");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        boolean b = sysUserService.checkChangePassword(sysUser);
        if (!b){
            return Result.noauth("访问权限认证未通过");
        }
        return sysUserService.changePassword(username,password,confirmpassword);
    }

    @RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
    public Result<IPage<SysUser>> userRoleList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<>();
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        IPage<SysUser> pageList = sysUserService.getUserByRoleId(page,roleId,username);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 给指定角色添加用户
     *
     * @param
     * @return
     */
    @RequiresPermissions("role:add:user")
    @AutoLog(value = "sys_user-给指定角色添加用户")
    @RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
    @Transactional
    public Result<Object> addSysUserRole(@RequestBody SysUserRoleVO sysUserRoleVO) {
        Result<Object> result = new Result<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户权限信息
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return Result.error("账号权限不够");
        }
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        if (!isAdmin){
            return Result.noauth("账号权限不够");
        }
        try {
            String sysRoleId = sysUserRoleVO.getRoleId();
            if (sysRoleId.equals(UserConstant.USER_ADMIN)){
                int count = sysUserRoleService.count(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, sysRoleId));
                if (count>0){
                    result.error10004("超级管理员只能有一个");
                    return result;
                }
            }
            if (sysRoleId.equals(UserConstant.USER_OPERATION)){
                int count = sysUserRoleService.count(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, sysRoleId));
                if (count>0){
                    result.error10004("基础数据运维人员只能有一个");
                    return result;
                }
            }
            for(String sysUserId:sysUserRoleVO.getUserIdList()) {
                if (!StringUtils.isEmpty(sysRoleId)) {
                    SysUserDepart userDepart = sysUserDepartService.getbyUserId(sysUserId);
                    List<SysRole> sysRoles = sysRoleService.queryListByIds(sysRoleId);
                    //获取部门角色
                    SysRole deptRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.DeptAdmin.getRoleCode())).findFirst().orElse(null);
                    if (deptRole != null) {
                        String deptRs = sysUserService.getDeptUser(deptRole.getId(), userDepart.getDepId());
                        if (!StringUtils.isEmpty(deptRs)) {
                            return result.error500("一个组织机构仅能有一个部门管理员，当前部门管理员账号为:["+deptRs+"]");
                        }
                    }
                    //获取区划角色
                    SysRole areaRole = sysRoles.stream().filter(r -> r.getRoleCode().equals(RoleEnum.AreaAdmin.getRoleCode())).findFirst().orElse(null);
                    //获取部门所在区划
                    SysDepart depart = sysDepartService.getById( userDepart.getDepId());
                    if (areaRole != null) {
                        String areaRs = sysUserService.getAreaUser(areaRole.getId(), depart.getAreaId());
                        if (!StringUtils.isEmpty(areaRs)) {
                            return result.error10002("一个行政区划仅能有一个地区管理员，当前区划管理员账号为:["+areaRs+"]");
                        }
                    }
                }

                SysUserRole sysUserRole = new SysUserRole(sysUserId,sysRoleId);
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
                queryWrapper.eq("role_id", sysRoleId).eq("user_id",sysUserId);

                SysUserRole one = sysUserRoleService.getOne(queryWrapper);
                if(one==null){
                    SysRole sysRole = sysRoleService.getById(sysRoleId);
                    SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(sysUserId);
                    SysUserRoleTo sysUserRoleTo = new SysUserRoleTo();
                    sysUserRoleTo.setRoleId(sysRoleId);
                    sysUserRoleTo.setUserId(sysUserId);
                    sysUserRoleTo.setRoleCode(sysRole.getRoleCode());
                    sysUserRoleTo.setDeptId(sysUserDepart.getDepId());
                    sysUserRoleTo.setCreateTime(new Date());
                    List<SysTenant> list = tenantService.list(new QueryWrapper<SysTenant>().isNotNull("msg_url").eq("is_send","1"));
                    list.forEach(sysTenant -> {
                        String json = JSON.toJSONString(sysUserRoleTo);
                        sysChangeMsgService.saveChangeMsg(sysTenant.getId(),sysTenant.getMsgUrl(),json,SendChangeMsgConstant.INSERT,SendChangeMsgConstant.TYPE_USER_ROLE);
                    });
                    sysUserRoleService.save(sysUserRole);
                }

            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     *   删除指定角色的用户关系
     * @param
     * @return
     */
    @RequiresPermissions("role:delete:user")
    @AutoLog(value = "sys_user-删除指定角色的用户关系")
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
    public Result<Object> deleteUserRole(@RequestParam(name="roleId") String roleId,
                                         @RequestParam(name="userId",required=true) String userId
    ) {

        Result<Object> result = new Result<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户权限信息
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return Result.error("账号权限不够");
        }
        try {
            Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
            if (!isAdmin){
                return Result.noauth("账号权限不够");
            }
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).eq("user_id",userId);
            SysRole sysRole = sysRoleService.getById(roleId);
            SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(userId);
            SysUserRoleTo sysUserRoleTo = new SysUserRoleTo();
            sysUserRoleTo.setRoleId(roleId);
            sysUserRoleTo.setUserId(userId);
            sysUserRoleTo.setRoleCode(sysRole.getRoleCode());
            sysUserRoleTo.setDeptId(sysUserDepart.getDepId());
            sysUserRoleTo.setUpdateTime(new Date());
            List<SysTenant> list = tenantService.list(new QueryWrapper<SysTenant>().isNotNull("msg_url").eq("is_send","1"));
            list.forEach(sysTenant -> {
                String json = JSON.toJSONString(sysUserRoleTo);
                sysChangeMsgService.saveChangeMsg(sysTenant.getId(),sysTenant.getMsgUrl(),json,SendChangeMsgConstant.DELETE,SendChangeMsgConstant.TYPE_USER_ROLE);
            });
            sysUserRoleService.remove(queryWrapper);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    @AutoLog(value = "sys_user-批量删除指定角色的用户关系")
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
    public Result<SysUserRole> deleteUserRoleBatch(
            @RequestParam(name="roleId") String roleId,
            @RequestParam(name="userIds",required=true) String userIds) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            System.out.println(userIds);
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).in("user_id",Arrays.asList(userIds.split(",")));
            SysRole sysRole = sysRoleService.getById(roleId);
            List<String> strings = Arrays.asList(userIds.split(","));
            strings.forEach(s -> {
                SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(s);
                SysUserRoleTo sysUserRoleTo = new SysUserRoleTo();
                sysUserRoleTo.setRoleId(roleId);
                sysUserRoleTo.setUserId(s);
                sysUserRoleTo.setRoleCode(sysRole.getRoleCode());
                sysUserRoleTo.setDeptId(sysUserDepart.getDepId());
                sysUserRoleTo.setUpdateTime(new Date());
                List<SysTenant> list = tenantService.list(new QueryWrapper<SysTenant>().isNotNull("msg_url").eq("is_send","1"));
                list.forEach(sysTenant -> {
                    String json = JSON.toJSONString(sysUserRoleTo);
                    sysChangeMsgService.saveChangeMsg(sysTenant.getId(),sysTenant.getMsgUrl(),json,SendChangeMsgConstant.DELETE,SendChangeMsgConstant.TYPE_USER_ROLE);
                });
            });
            sysUserRoleService.remove(queryWrapper);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 部门用户列表
     */
    @ApiOperation(value="sys_user-部门用户列表 ", notes="sys_user-部门用户列表 ")
    @AutoLog(value = "sys_user-部门用户列表")
    @RequestMapping(value = "/departUserList", method = RequestMethod.GET)
    public Result<IPage<SysUser>> departUserList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String depId = req.getParameter("depId");
        String username = req.getParameter("username");
        //根据部门ID查询,当前和下级所有的部门IDS
        List<String> subDepids = new ArrayList<>();
        //部门id为空时，查询我的部门下所有用户
        if(oConvertUtils.isEmpty(depId)){
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            int userIdentity = user.getUserIdentity() != null?user.getUserIdentity():CommonConstant.USER_IDENTITY_1;
            if(oConvertUtils.isNotEmpty(userIdentity) && userIdentity == CommonConstant.USER_IDENTITY_2 ){
                subDepids = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
            }
        }else{
            subDepids = sysDepartService.getSubDepIdsByDepId(depId);
        }
        if(subDepids != null && subDepids.size()>0){
            IPage<SysUser> pageList = sysUserService.getUserByDepIds(page,subDepids,username);
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
            if(userIds!=null && userIds.size()>0){
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                pageList.getRecords().forEach(item -> {
                    //批量查询用户的所属部门
                    item.setOrgCode(useDepNames.get(item.getId()));
                });
            }
            result.setSuccess(true);
            result.setResult(pageList);
        }else{
            result.setSuccess(true);
            result.setResult(null);
        }
        return result;
    }


    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 若某个用户包含多个部门，则会显示多条记录，可自行处理成单条记录
     */
    @GetMapping("/queryByOrgCode")
    public Result<?> queryByDepartId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode") String orgCode,
            SysUser userParams
    ) {
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, new Page(pageNo, pageSize));
        return Result.ok(pageList);
    }

    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 针对通讯录模块做的接口，将多个部门的用户合并成一条记录，并转成对前端友好的格式
     */
    @GetMapping("/queryByOrgCodeForAddressList")
    public Result<?> queryByOrgCodeForAddressList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode",required = false) String orgCode,
            SysUser userParams
    ) {
        IPage page = new Page(pageNo, pageSize);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
        List<SysUserSysDepartModel> list = pageList.getRecords();

        // 记录所有出现过的 user, key = userId
        Map<String, JSONObject> hasUser = new HashMap<>(list.size());

        JSONArray resultJson = new JSONArray(list.size());

        for (SysUserSysDepartModel item : list) {
            String userId = item.getId();
            // userId
            JSONObject getModel = hasUser.get(userId);
            // 之前已存在过该用户，直接合并数据
            if (getModel != null) {
                String departName = getModel.get("departName").toString();
                getModel.put("departName", (departName + " | " + item.getDepartName()));
            } else {
                // 将用户对象转换为json格式，并将部门信息合并到 json 中
                JSONObject json = JSON.parseObject(JSON.toJSONString(item));
                json.remove("id");
                json.put("userId", userId);
                json.put("departId", item.getDepartId());
                json.put("departName", item.getDepartName());
//                json.put("avatar", item.getSysUser().getAvatar());
                resultJson.add(json);
                hasUser.put(userId, json);
            }
        }
        IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
        result.setRecords(resultJson.toJavaList(JSONObject.class));
        return Result.ok(result);
    }

    /**
     * 给指定部门添加对应的用户
     */
    @ApiOperation(value="sys_user-给指定部门添加对应的用户 ", notes="sys_user-给指定部门添加对应的用户 ")
    @AutoLog(value = "sys_user-给指定部门添加对应的用户")
    @RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
    public Result<String> editSysDepartWithUser(@RequestBody SysDepartUsersVO sysDepartUsersVO) {
        Result<String> result = new Result<String>();
        try {
            String sysDepId = sysDepartUsersVO.getDepId();
            for(String sysUserId:sysDepartUsersVO.getUserIdList()) {
                SysUserDepart sysUserDepart = new SysUserDepart(null,sysUserId,sysDepId);
                QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
                queryWrapper.eq("dep_id", sysDepId).eq("user_id",sysUserId);
                SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
                if(one==null){
                    sysUserDepartService.save(sysUserDepart);
                }
            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     *   删除指定机构的用户关系
     */
    @AutoLog(value = "sys_user-删除指定机构的用户关系")
    @RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepart(@RequestParam(name="depId") String depId,
                                                    @RequestParam(name="userId",required=true) String userId
    ) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id",userId);
            boolean b = sysUserDepartService.remove(queryWrapper);
            if(b){
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id",depId));
                List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                if(roleIds != null && roleIds.size()>0){
                    QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                    query.eq("user_id",userId).in("drole_id",roleIds);
                    departRoleUserService.remove(query);
                }
                result.success("删除成功!");
            }else{
                result.error500("当前选中部门与用户无关联关系!");
            }
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定机构的用户关系
     */
    @AutoLog(value = "sys_user-批量删除指定机构的用户关系")
    @RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepartBatch(
            @RequestParam(name="depId") String depId,
            @RequestParam(name="userIds",required=true) String userIds) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).in("user_id",Arrays.asList(userIds.split(",")));
            boolean b = sysUserDepartService.remove(queryWrapper);
            if(b){
                departRoleUserService.removeDeptRoleUser(Arrays.asList(userIds.split(",")),depId);
            }
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     *  查询当前用户的所有部门/当前部门编码
     * @return
     */
    @RequestMapping(value = "/getCurrentUserDeparts", method = RequestMethod.GET)
    public Result<Map<String,Object>> getCurrentUserDeparts() {
        Result<Map<String,Object>> result = new Result<Map<String,Object>>();
        try {
            LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
            List<SysDepart> list = this.sysDepartService.queryUserDeparts(sysUser.getId());
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list", list);
            map.put("orgCode", sysUser.getOrgCode());
            result.setSuccess(true);
            result.setResult(map);
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败！");
        }
        return result;
    }




    /**
     * 用户注册接口
     *
     * @param jsonObject
     * @param user
     * @return
     */



    /**
     * 给指定用户添加运维密码
     */
    //TODO 给指定用户添加运维密码
    @ApiOperation(value="sys_user-给指定用户添加运维密码 ", notes="sys_user-给指定用户添加运维密码")
    @AutoLog(value = "sys_user-给指定用户添加运维密码")
    @RequestMapping(value = "/optPassword" ,method = RequestMethod.POST)
    public Result<String> operationPassword(@RequestBody SysUser sysUser) {
        Result<String> result = new Result<String>();
        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
        if (u == null) {
            result.setMessage("用户不存在");
            return result;
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户权限信息
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            result.setMessage("请先登录");
            return result;
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        //sysUser.setId(u.getId());
        if(!isAdmin&&!isBasicOperation){
            result.setMessage("账号权限不足，请用管理员账号添加运维权限");
            return result;
        }
        String password = sysUserService.setOpePassword(u);
        result.setResult(password);
        return result;
    }


    @AutoLog(value = "gt_sys_user-注册用户")
    @ApiOperation(value="gt_sys_user-注册用户", notes="gt_sys_user-注册用户")
    @PostMapping("/register")
    public Result<JSONObject> userRegister(@RequestBody JSONObject jsonObject, SysUser user) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        String username = jsonObject.getString("username");
        //未设置用户名，则用手机号作为用户名
        if(oConvertUtils.isEmpty(username)){
            username = phone;
        }
        //未设置密码，则随机生成一个密码
        String password = jsonObject.getString("password");
        if(oConvertUtils.isEmpty(password)){
            password = RandomUtil.randomString(8);
        }
        String email = jsonObject.getString("email");
        SysUser sysUser1 = sysUserService.getUserByName(username);
        if (sysUser1 != null) {
            result.setMessage("用户名已注册");
            result.setSuccess(false);
            return result;
        }
        SysUser sysUser2 = sysUserService.getUserByPhone(phone);
        if (sysUser2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }

        if(oConvertUtils.isNotEmpty(email)){
            SysUser sysUser3 = sysUserService.getUserByEmail(email);
            if (sysUser3 != null) {
                result.setMessage("邮箱已被注册");
                result.setSuccess(false);
                return result;
            }
        }
        if(null == code){
            result.setMessage("手机验证码失效，请重新获取");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(code.toString())) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }

        try {
            user.setCreateTime(new Date());// 设置创建时间
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            user.setSalt(salt);
            user.setUsername(username);
            user.setRealname(username);
            user.setPassword(passwordEncode);
            user.setEmail(email);
            user.setPhone(phone);
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setActivitiSync(CommonConstant.ACT_SYNC_0);
            sysUserService.addUserWithRole(user,"ee8626f80f7c2619917b6236f3a7f02b");//默认临时角色 test
            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    /**
     * 根据用户名或手机号查询用户信息
     * @param
     * @return
     */
    @GetMapping("/querySysUser")
    public Result<Map<String, Object>> querySysUser(SysUser sysUser) {
        String phone = sysUser.getPhone();
        String username = sysUser.getUsername();
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        if (oConvertUtils.isNotEmpty(phone)) {
            SysUser user = sysUserService.getUserByPhone(phone);
            if(user!=null) {
                map.put("username",user.getUsername());
                map.put("phone",user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        if (oConvertUtils.isNotEmpty(username)) {
            SysUser user = sysUserService.getUserByName(username);
            if(user!=null) {
                map.put("username",user.getUsername());
                map.put("phone",user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        result.setSuccess(false);
        result.setMessage("验证失败");
        return result;
    }

    /**
     * 用户手机号验证
     */
    @PostMapping("/phoneVerification")
    public Result<Map<String,String>> phoneVerification(@RequestBody JSONObject jsonObject) {
        Result<Map<String,String>> result = new Result<Map<String,String>>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        //设置有效时间
        redisUtil.set(phone, smscode,600);
        //新增查询用户名
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getPhone,phone);
        SysUser user = sysUserService.getOne(query);
        Map<String,String> map = new HashMap<>();
        map.put("smscode",smscode);
        map.put("username",user.getUsername());
        result.setResult(map);
        result.setSuccess(true);
        return result;
    }

    /**
     * 用户更改密码
     */
    @GetMapping("/passwordChange")
    public Result<SysUser> passwordChange(@RequestParam(name="username")String username,
                                          @RequestParam(name="password")String password,
                                          @RequestParam(name="smscode")String smscode,
                                          @RequestParam(name="phone") String phone) {
        Result<SysUser> result = new Result<SysUser>();
        if(oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(password) || oConvertUtils.isEmpty(smscode)  || oConvertUtils.isEmpty(phone) ) {
            result.setMessage("重置密码失败！");
            result.setSuccess(false);
            return result;
        }

        SysUser sysUser=new SysUser();
        Object object= redisUtil.get(phone);
        if(null==object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if(!smscode.equals(object)) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username).eq(SysUser::getPhone,phone));
        if (sysUser == null) {
            result.setMessage("未找到用户！");
            result.setSuccess(false);
            return result;
        } else {
            String salt = oConvertUtils.randomGen(8);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
            sysUser.setPassword(passwordEncode);
            this.sysUserService.updateById(sysUser);
            result.setSuccess(true);
            result.setMessage("密码重置完成！");
            return result;
        }
    }


    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public Result<?> getUserSectionInfoByToken(HttpServletRequest request, @RequestParam(name = "token", required = false) String token) {
        try {
            String username = null;
            // 如果没有传递token，就从header中获取token并获取用户信息
            if (oConvertUtils.isEmpty(token)) {
                username = JwtUtil.getUserNameByToken(request);
            } else {
                username = JwtUtil.getUsername(token);
            }

            log.debug(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

            // 根据用户名查询用户信息
            SysUser sysUser = sysUserService.getUserByName(username);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sysUserId", sysUser.getId());
            map.put("sysUserCode", sysUser.getUsername()); // 当前登录用户登录账号
            map.put("sysUserName", sysUser.getRealname()); // 当前登录用户真实名称
            map.put("sysOrgCode", sysUser.getOrgCode()); // 当前登录用户部门编号

            log.debug(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

            return Result.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 【APP端接口】获取用户列表  根据用户名和真实名 模糊匹配
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/appUserList")
    public Result<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
                                 @RequestParam(name = "username", required = false) String username,
                                 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                 @RequestParam(name = "syncFlow", required = false) String syncFlow) {
        try {
            //TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
            LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>();
            if(oConvertUtils.isNotEmpty(syncFlow)){
                query.eq(SysUser::getActivitiSync, CommonConstant.ACT_SYNC_1);
            }
            query.eq(SysUser::getDelFlag,CommonConstant.DEL_FLAG_0);
            if(oConvertUtils.isNotEmpty(username)){
                if(username.contains(",")){
                    query.in(SysUser::getUsername,username.split(","));
                }else{
                    query.eq(SysUser::getUsername,username);
                }
            }else{
                query.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
            }
            Page<SysUser> page = new Page<>(pageNo, pageSize);
            IPage<SysUser> res = this.sysUserService.page(page, query);
            return Result.ok(res);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }

    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @RequiresPermissions("user:recycleBin")
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted();
        if (logicDeletedUserList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = logicDeletedUserList.stream().map(SysUser::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            logicDeletedUserList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 还原被逻辑删除的用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
    public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String userIds = jsonObject.getString("userIds");
        if (StringUtils.isNotBlank(userIds)) {
            SysUser updateUser = new SysUser();
            updateUser.setUpdateBy(JwtUtil.getUserNameByToken(request));
            updateUser.setUpdateTime(new Date());
            sysUserService.revertLogicDeleted(Arrays.asList(userIds.split(",")), updateUser);
        }
        return Result.ok("还原成功");
    }

    /**
     * 彻底删除用户
     *
     * @param userIds 被删除的用户ID，多个id用半角逗号分割
     * @return
     */
    @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE)
    public Result deleteRecycleBin(@RequestParam("userIds") String userIds) {
        if (StringUtils.isNotBlank(userIds)) {
            sysUserService.removeLogicDeleted(Arrays.asList(userIds.split(",")));
        }
        return Result.ok("删除成功");
    }


    /**
     * 移动端修改用户信息
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/appEdit", method = RequestMethod.PUT)
    public Result<SysUser> appEdit(HttpServletRequest request,@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            String username = JwtUtil.getUserNameByToken(request);
            SysUser sysUser = sysUserService.getUserByName(username);
            baseCommonService.addLog("移动端编辑用户，id： " +jsonObject.getString("id") ,CommonConstant.LOG_TYPE_2, 2);
            String realname=jsonObject.getString("realname");
            String avatar=jsonObject.getString("avatar");
            String sex=jsonObject.getString("sex");
            String phone=jsonObject.getString("phone");
            String email=jsonObject.getString("email");
            Date birthday=jsonObject.getDate("birthday");
            SysUser userPhone = sysUserService.getUserByPhone(phone);
            if(sysUser==null) {
                result.error500("未找到对应用户!");
            }else {
                if(userPhone!=null){
                    String userPhonename = userPhone.getUsername();
                    if(!userPhonename.equals(username)){
                        result.error500("手机号已存在!");
                        return result;
                    }
                }
                if(StringUtils.isNotBlank(realname)){
                    sysUser.setRealname(realname);
                }
                if(StringUtils.isNotBlank(avatar)){
                    sysUser.setAvatar(avatar);
                }
                if(StringUtils.isNotBlank(sex)){
                    sysUser.setSex(Integer.parseInt(sex));
                }
                if(StringUtils.isNotBlank(phone)){
                    sysUser.setPhone(phone);
                }
                if(StringUtils.isNotBlank(email)){
                    sysUser.setEmail(email);
                }
                if(null != birthday){
                    sysUser.setBirthday(birthday);
                }
                sysUser.setUpdateTime(new Date());
                sysUserService.updateById(sysUser);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }
    /**
     * 移动端保存设备信息
     * @param clientId
     * @return
     */
    @RequestMapping(value = "/saveClientId", method = RequestMethod.GET)
    public Result<SysUser> saveClientId(HttpServletRequest request,@RequestParam("clientId")String clientId) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            String username = JwtUtil.getUserNameByToken(request);
            SysUser sysUser = sysUserService.getUserByName(username);
            if(sysUser==null) {
                result.error500("未找到对应用户!");
            }else {
                sysUser.setClientId(clientId);
                sysUserService.updateById(sysUser);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }
    /**
     * 根据userid获取用户信息和部门员工信息
     *
     * @return Result
     */
    @GetMapping("/queryChildrenByUsername")
    public Result queryChildrenByUsername(@RequestParam("userId") String userId) {
        //获取用户信息
        Map<String,Object> map=new HashMap<String,Object>();
        SysUser sysUser = sysUserService.getById(userId);
        String username = sysUser.getUsername();
        Integer identity = sysUser.getUserIdentity();
        map.put("sysUser",sysUser);
        if(identity!=null && identity==2){
            //获取部门用户信息
            String departIds = sysUser.getDepartIds();
            if(StringUtils.isNotBlank(departIds)){
                List<String> departIdList = Arrays.asList(departIds.split(","));
                List<SysUser> childrenUser = sysUserService.queryByDepIds(departIdList,username);
                map.put("children",childrenUser);
            }
        }
        return Result.ok(map);
    }
    /**
     * 移动端查询部门用户信息
     * @param departId
     * @return
     */
    @GetMapping("/appQueryByDepartId")
    public Result<List<SysUser>> appQueryByDepartId(@RequestParam(name="departId", required = false) String departId) {
        Result<List<SysUser>> result = new Result<List<SysUser>>();
        List<String> list=new ArrayList<String> ();
        list.add(departId);
        List<SysUser> childrenUser = sysUserService.queryByDepIds(list,null);
        result.setResult(childrenUser);
        return result;
    }
    /**
     * 移动端查询用户信息(通过用户名模糊查询)
     * @param keyword
     * @return
     */
    @GetMapping("/appQueryUser")
    public Result<List<SysUser>> appQueryUser(@RequestParam(name = "keyword", required = false) String keyword) {
        Result<List<SysUser>> result = new Result<List<SysUser>>();
        LambdaQueryWrapper<SysUser> queryWrapper =new LambdaQueryWrapper<SysUser>();
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne(SysUser::getUsername,"_reserve_user_external");
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
        }
        List<SysUser> list = sysUserService.list(queryWrapper);
        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
        if(userIds!=null && userIds.size()>0){
            Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            list.forEach(item->{
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setResult(list);
        return result;
    }

    /**
     * 根据用户名修改手机号
     * @param json
     * @return
     */
    @RequestMapping(value = "/updateMobile", method = RequestMethod.PUT)
    public Result<?> changMobile(@RequestBody JSONObject json,HttpServletRequest request) {
        String smscode = json.getString("smscode");
        String phone = json.getString("phone");
        Result<SysUser> result = new Result<SysUser>();
        //获取登录用户名
        String username = JwtUtil.getUserNameByToken(request);
        if(oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            result.setMessage("修改手机号失败！");
            result.setSuccess(false);
            return result;
        }
        Object object= redisUtil.get(phone);
        if(null==object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if(!smscode.equals(object)) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        SysUser user = sysUserService.getUserByName(username);
        if(user==null) {
            return Result.error("用户不存在！");
        }
        user.setPhone(phone);
        sysUserService.updateById(user);
        return Result.ok("手机号设置成功!");
    }
}
