package com.bs.web.controller.system;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.annotation.Anonymous;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysRole;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.poi.ExcelUtil;
import com.bs.df.domain.DfBroker;
import com.bs.df.domain.DfUserBroker;
import com.bs.df.service.IDfBrokerService;
import com.bs.df.service.IDfUserBrokerService;
import com.bs.df.utils.HtmlUtils;
import com.bs.system.domain.DfArea;
import com.bs.system.domain.SysUserRole;
import com.bs.system.mapper.SysUserRoleMapper;
import com.bs.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

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

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Resource
    private IDfBrokerService dfBrokerService;

    @Resource
    private IDfUserBrokerService dfUserBrokerService;

    @Resource
    private IDfAreaService dfAreaService;

    @Resource
    private ICmAttachService cmAttachService;




    /**
     * 获取用户列表
     */
    //@PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        List<DfBroker> dfBrokers = dfBrokerService.list();
        Map<Long, String> map = dfBrokers.stream().collect(Collectors.toMap(DfBroker::getId, DfBroker::getBrokerName));
        for (SysUser sysUser : list) {
            sysUser.setUserDesc(HtmlUtils.stripHtmlTags(sysUser.getUserDesc()));
            String deptName = map.get(sysUser.getDeptId());
            if (Validator.isNotEmpty(deptName)) {
                sysUser.setDeptName(deptName);
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/listUserAll")
    public AjaxResult listUserAll(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return success(list);
    }

    @PostMapping("/removeDepts")
    public AjaxResult removeDepts(@RequestBody SysUser user) {
        for (Long userId : user.getUserIds()) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setDeptId(0L);
            userService.updateById(sysUser);
        }
        return success(true);
    }

    @PostMapping("/removeBrokers")
    public AjaxResult removeBrokers(@RequestBody SysUser user) {
        dfUserBrokerService.remove(new LambdaQueryWrapper<DfUserBroker>().in(DfUserBroker::getUserId, user.getUserIds()));
        return success(true);
    }

    @PostMapping("/updateDepts")
    public AjaxResult updateDepts(@RequestBody SysUser user) {
        for (Long userId : user.getUserIds()) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setDeptId(user.getDeptId());
            userService.updateById(sysUser);
        }
        return success(true);
    }

    @PostMapping("/updateBroker")
    public AjaxResult updateBroker(@RequestBody SysUser user) {
        for (Long userId : user.getUserIds()) {
            DfUserBroker dfUserBroker = new DfUserBroker();
            dfUserBroker.setUserId(userId);
            dfUserBroker.setBrokerId(Long.valueOf(user.getBrokerId()));
            dfUserBrokerService.save(dfUserBroker);
        }
        return success(true);
    }


    @GetMapping("/listByType")
    public TableDataInfo listByType(SysUser user) {
        List<DfUserBroker> dfUserBrokers = dfUserBrokerService.list(new LambdaQueryWrapper<DfUserBroker>()
                .eq(DfUserBroker::getBrokerId, user.getBrokerId()));
        if (!"1".equals(user.getSelectAll())) {
            startPage();
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (user.getDeptIds() != null) {
            wrapper.in(SysUser::getDeptId, user.getDeptIds());
        } else {
            if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                List<Long> longs = dfBrokerService.filterByUser();
                wrapper.in(SysUser::getDeptId, longs);
            }
        }
        if (null != user.getBrokerId()) {
            List<Long> userIds = dfUserBrokers.stream()
                    .map(DfUserBroker::getUserId)
                    .distinct()
                    .collect(Collectors.toList());
            if (userIds.isEmpty()) {
                userIds.add(0L);
            }
            wrapper.in(SysUser::getUserId, userIds);
        }
        condition(wrapper,user);
        List<SysUser> list = userService.list(wrapper);
        List<SysUser> listByAll = userService.list();
        List<DfUserBroker> userBrokerListByAll = dfUserBrokerService.list();
        List<DfBroker> dfBrokers = dfBrokerService.list();
        List<DfArea> dfAreas = dfAreaService.list();
        List<CmAttach> attachVo = cmAttachService.list();
        Map<String, List<CmAttach>> attachMap = attachVo.stream()
                .filter(cmAttach -> cmAttach.getFileId() != null)
                .collect(Collectors.groupingBy(CmAttach::getFileId));
        Map<Long, Long> mapByUserBroker = userBrokerListByAll.stream().collect(Collectors.toMap(DfUserBroker::getUserId, DfUserBroker::getBrokerId));
        Map<Long, String> mapByUser = listByAll.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        Map<Long, String> map = dfBrokers.stream().collect(Collectors.toMap(DfBroker::getId, DfBroker::getBrokerName));
        Map<String, String> mapByArea = dfAreas.stream().collect(Collectors.toMap(DfArea::getAreaId, DfArea::getName));
        for (SysUser sysUser : list) {
            sysUser.setUserDesc(HtmlUtils.stripHtmlTags(sysUser.getUserDesc()));
            String deptName = map.get(sysUser.getDeptId());
            sysUser.setBrokerId(String.valueOf(mapByUserBroker.get(sysUser.getUserId())));
            String brokerId = sysUser.getBrokerId();
            if (!Validator.isEmpty(brokerId) && !"null".equals(brokerId)) {
                sysUser.setBrokerName(mapByUser.get(Long.valueOf(brokerId)));
            }
            String cityName = mapByArea.get(sysUser.getCity());
            if (Validator.isNotEmpty(deptName)) {
                sysUser.setDeptName(deptName);
            }
            if (Validator.isNotEmpty(cityName)) {
                sysUser.setCity(cityName);
            }
            Long id = sysUser.getUserId();
            List<CmAttach> matchingAttachments = attachMap.get(String.valueOf(id));
            if (matchingAttachments != null) {
                sysUser.setFiles(matchingAttachments);
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/listByNotBroker")
    public TableDataInfo listByNotBroker(SysUser user) {
        List<DfUserBroker> userBrokerList = dfUserBrokerService.list();
        List<Long> userIdList = userBrokerList.stream()
                .map(DfUserBroker::getUserId)
                .filter(Objects::nonNull) // 过滤掉 null 值
                .collect(Collectors.toList());
        startPage();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.notIn(SysUser::getUserId, userIdList);
        wrapper.eq(SysUser::getUserType,"jj");
        condition(wrapper,user);
        List<SysUser> list = userService.list(wrapper);
        return getDataTable(list);
    }

    @GetMapping("/listByBroker")
    public TableDataInfo listByBroker(SysUser user) {
        startPage();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        condition(wrapper,user);
        List<SysUser> list = userService.list(wrapper);
        List<DfBroker> dfBrokers = dfBrokerService.list();
        List<DfArea> dfAreas = dfAreaService.list();
        List<CmAttach> attachVo = cmAttachService.list();
        Map<String, List<CmAttach>> attachMap = attachVo.stream()
                .filter(cmAttach -> cmAttach.getFileId() != null)
                .collect(Collectors.groupingBy(CmAttach::getFileId));
        Map<Long, String> map = dfBrokers.stream().collect(Collectors.toMap(DfBroker::getId, DfBroker::getBrokerName));
        Map<String, String> mapByArea = dfAreas.stream().collect(Collectors.toMap(DfArea::getAreaId, DfArea::getName));
        for (SysUser sysUser : list) {
            sysUser.setUserDesc(HtmlUtils.stripHtmlTags(sysUser.getUserDesc()));
            String deptName = map.get(sysUser.getDeptId());
            String cityName = mapByArea.get(sysUser.getCity());
            if (Validator.isNotEmpty(deptName)) {
                sysUser.setDeptName(deptName);
            }
            if (Validator.isNotEmpty(cityName)) {
                sysUser.setCity(cityName);
            }
            Long id = sysUser.getUserId();
            List<CmAttach> matchingAttachments = attachMap.get(String.valueOf(id));
            if (matchingAttachments != null) {
                sysUser.setFiles(matchingAttachments);
            }
        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByType")
    public void exportByType(HttpServletResponse response, SysUser user) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (user.getDeptIds()!=null) {
            wrapper.in(SysUser::getDeptId, user.getDeptIds());
        }
        condition(wrapper,user);
        List<SysUser> list = userService.list(wrapper);
        List<DfBroker> dfBrokers = dfBrokerService.list();
        List<DfArea> dfAreas = dfAreaService.list();
        Map<Long, String> map = dfBrokers.stream().collect(Collectors.toMap(DfBroker::getId, DfBroker::getBrokerName));
        Map<String, String> mapByArea = dfAreas.stream().collect(Collectors.toMap(DfArea::getAreaId, DfArea::getName));
        for (SysUser sysUser : list) {
            sysUser.setUserDesc(HtmlUtils.stripHtmlTags(sysUser.getUserDesc()));
            String deptName = map.get(sysUser.getDeptId());
            String cityName = mapByArea.get(sysUser.getCity());
            if (Validator.isNotEmpty(deptName)) {
                sysUser.setDeptName(deptName);
            }
            if (Validator.isNotEmpty(cityName)) {
                sysUser.setCity(cityName);
            }
            if ("jj".equals(sysUser.getUserType())) {
                sysUser.setUserType("经济");
            } else if ("kh".equals(sysUser.getUserType())) {
                sysUser.setUserType("客户");
            }
        }
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }


    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    //@PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        List<DfBroker> dfBrokerList = dfBrokerService.list();
        Map<Long, DfBroker> dfBrokerMap = dfBrokerList.stream()
                .collect(Collectors.toMap(DfBroker::getId, broker -> broker));
        for (SysUser sysUser : list) {
            DfBroker dfBroker = dfBrokerMap.get(sysUser.getDeptId());
            if (null != dfBroker) {
                sysUser.setDeptName(dfBroker.getBrokerName());
            }
        }
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('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());
        Long operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

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

    /**
     * 根据用户编号获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('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 (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            final List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/getUsers"})
    public TableDataInfo getInfosById(SysUser user) {
        SysUser sysUser = userService.selectUserById(user.getUserId());
//        Long deptId = sysUser.getDeptId();
//        LambdaQueryWrapper<DfBroker> dfBrokerLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        if (!sysUser.getDeptId().equals(-1L)) {
//            dfBrokerLambdaQueryWrapper.eq(DfBroker::getParentId, deptId);
//        }
//        List<DfBroker> list = dfBrokerService.list(dfBrokerLambdaQueryWrapper);
//        List<Long> idList = list.stream()
//                .map(DfBroker::getId)
//                .collect(Collectors.toList());
//        if (idList.isEmpty()) {
//            idList.add(0L);
//        }

        List<DfUserBroker> userBrokerList = dfUserBrokerService.list(new LambdaQueryWrapper<DfUserBroker>()
                .eq(DfUserBroker::getBrokerId, sysUser.getUserId()));
        List<Long> userIdList = userBrokerList.stream()
                .map(DfUserBroker::getUserId)
                .collect(Collectors.toList());
        if (userIdList.isEmpty()) {
            userIdList.add(0L);
        }
        startPage();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysUser::getUserId, userIdList)
                .eq(SysUser::getUserType, user.getUserType());
        if (sysUser.getDeptId().equals(-1L)) {
            queryWrapper.or()
                    .isNotNull(SysUser::getUserId);
        }
        List<SysUser> sysUsers = userService.list(queryWrapper);
        return getDataTable(sysUsers);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/getUser/{userId}"})
    @Anonymous
    public AjaxResult getUser(@PathVariable(value = "userId", required = false) Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        List<CmAttach> attachVo = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId, "userId" + userId));
        sysUser.setFiles(attachVo);
        return success(sysUser);
    }



    /**
      获取所有非admin角色，用于租户配置
     */
    @GetMapping("/getRoles")
    public AjaxResult getRoles() {
        List<SysRole> roles = roleService.selectRoleAll();
        return AjaxResult.success().put("roles", roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    }

    /**
     * 新增用户
     */
    //@PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (Validator.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Validator.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setIsTenant(SecurityUtils.getLoginUser().getIsTenant());
        user.setIsTenantAdmin("N");
        if (!"kh".equals(user.getUserType())) {
            user.setUserType("jj");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (Validator.isNotEmpty(user.getUserIdNew())) {
            user.setUserId(Long.valueOf(user.getUserIdNew()));
        }
        int i = userService.insertUser(user);
        if ("kh".equals(user.getUserType())) {
            DfUserBroker dfUserBroker = new DfUserBroker();
            dfUserBroker.setUserId(user.getUserId());
            dfUserBroker.setBrokerId(user.getDeptId());
            dfUserBrokerService.save(dfUserBroker);
        }
        return toAjax(i);
    }

    /**
     * 修改用户
     */
    //@PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (Validator.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Validator.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        if ("kh".equals(user.getUserType())) {
            LambdaQueryWrapper<DfUserBroker> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DfUserBroker::getUserId,user.getUserId());
            List<DfUserBroker> list = dfUserBrokerService.list(queryWrapper);
            DfUserBroker dfUserBroker = list.get(0);
            dfUserBroker.setBrokerId(user.getDeptId());
            dfUserBrokerService.updateById(dfUserBroker);
        } else {
            user.setUserType("jj");
        }
        user.setPassword(null);
        if (null == user.getDeptId()) {
            user.setDeptId(0L);
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    //@PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        LambdaQueryWrapper<DfUserBroker> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DfUserBroker::getUserId,userIds);
        dfUserBrokerService.remove(queryWrapper);
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    //@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    //@PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 审核状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeUserReviewStatus")
    public AjaxResult changeUserReviewStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    //@PreAuthorize("@ss.hasPermi('system:user:query')")
    @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;
    }

    /**
     * 用户授权角色
     */
    //@PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

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

    /**
     * 条件设置
     */
    private void condition (LambdaQueryWrapper<SysUser> queryWrapper,SysUser sysUser){


        //用户ID
        if(Validator.isNotEmpty(sysUser.getUserId())){
            queryWrapper.eq(SysUser::getUserId,sysUser.getUserId());
        }

        //用户账号
        if(Validator.isNotEmpty(sysUser.getUserName())){
            queryWrapper.like(SysUser::getUserName,sysUser.getUserName());
        }

        //用户昵称
        if(Validator.isNotEmpty(sysUser.getNickName())){
            queryWrapper.like(SysUser::getNickName,sysUser.getNickName());
        }

        //用户类型（00系统用户）
        if(Validator.isNotEmpty(sysUser.getUserType())){
            queryWrapper.eq(SysUser::getUserType,sysUser.getUserType());
        }

        //身份证号
        if(Validator.isNotEmpty(sysUser.getIdentityCard())){
            queryWrapper.like(SysUser::getIdentityCard,sysUser.getIdentityCard());
        }

        //城市
        if(Validator.isNotEmpty(sysUser.getCity())){
            queryWrapper.eq(SysUser::getCity,sysUser.getCity());
        }

        //注册时间
        if(Validator.isNotEmpty(sysUser.getRegistrationTime())){
            queryWrapper.eq(SysUser::getRegistrationTime,sysUser.getRegistrationTime());
        }

        //用户邮箱
        if(Validator.isNotEmpty(sysUser.getEmail())){
            queryWrapper.like(SysUser::getEmail,sysUser.getEmail());
        }

        //手机号码
        if(Validator.isNotEmpty(sysUser.getPhonenumber())){
            queryWrapper.like(SysUser::getPhonenumber,sysUser.getPhonenumber());
        }

        //真实姓名
        if(Validator.isNotEmpty(sysUser.getRealName())){
            queryWrapper.like(SysUser::getRealName,sysUser.getRealName());
        }


        //用户性别（0男 1女 2未知）
        if(Validator.isNotEmpty(sysUser.getSex())){
            queryWrapper.eq(SysUser::getSex,sysUser.getSex());
        }

        //地址
        if(Validator.isNotEmpty(sysUser.getAddress())){
            queryWrapper.eq(SysUser::getAddress,sysUser.getAddress());
        }

        //公司
        if(Validator.isNotEmpty(sysUser.getCompany())){
            queryWrapper.eq(SysUser::getCompany,sysUser.getCompany());
        }

        //头像地址
        if(Validator.isNotEmpty(sysUser.getAvatar())){
            queryWrapper.eq(SysUser::getAvatar,sysUser.getAvatar());
        }

        //密码
        if(Validator.isNotEmpty(sysUser.getPassword())){
            queryWrapper.eq(SysUser::getPassword,sysUser.getPassword());
        }

        //帐号状态（0正常 1停用）
        if(Validator.isNotEmpty(sysUser.getStatus())){
            queryWrapper.eq(SysUser::getStatus,sysUser.getStatus());
        }

        //最后登录IP
        if(Validator.isNotEmpty(sysUser.getLoginIp())){
            queryWrapper.eq(SysUser::getLoginIp,sysUser.getLoginIp());
        }

        //最后登录时间
        if(Validator.isNotEmpty(sysUser.getLoginDate())){
            queryWrapper.eq(SysUser::getLoginDate,sysUser.getLoginDate());
        }

        //是否是租户，Y是N，不是
        if(Validator.isNotEmpty(sysUser.getIsTenant())){
            queryWrapper.eq(SysUser::getIsTenant,sysUser.getIsTenant());
        }

        //是否是租户管理员，Y是N，不是
        if(Validator.isNotEmpty(sysUser.getIsTenantAdmin())){
            queryWrapper.eq(SysUser::getIsTenantAdmin,sysUser.getIsTenantAdmin());
        }

        //创建部门
        if(Validator.isNotEmpty(sysUser.getCreateDept())){
            queryWrapper.eq(SysUser::getCreateDept,sysUser.getCreateDept());
        }

        //创建人
        if(Validator.isNotEmpty(sysUser.getCreateBy())){
            queryWrapper.eq(SysUser::getCreateBy,sysUser.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(sysUser.getCreateTime())){
            queryWrapper.eq(SysUser::getCreateTime,sysUser.getCreateTime());
        }

        if(Validator.isNotEmpty(sysUser.getParams().get("beginTime"))){
            queryWrapper.ge(SysUser::getCreateTime,sysUser.getParams().get("beginTime"));
        }

        if(Validator.isNotEmpty(sysUser.getParams().get("endTime"))){
            queryWrapper.le(SysUser::getCreateTime,sysUser.getParams().get("endTime"));
        }


        //修改人
        if(Validator.isNotEmpty(sysUser.getUpdateBy())){
            queryWrapper.eq(SysUser::getUpdateBy,sysUser.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(sysUser.getUpdateTime())){
            queryWrapper.eq(SysUser::getUpdateTime,sysUser.getUpdateTime());
        }

        //备注
        if(Validator.isNotEmpty(sysUser.getRemark())){
            queryWrapper.eq(SysUser::getRemark,sysUser.getRemark());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(sysUser.getDelFlag())){
            queryWrapper.eq(SysUser::getDelFlag,sysUser.getDelFlag());
        }

        //${column.columnComment}
        if(Validator.isNotEmpty(sysUser.getTenantId())){
            queryWrapper.eq(SysUser::getTenantId,sysUser.getTenantId());
        }

    }

}
