package com.willalp.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.annotation.DataScope;
import com.willalp.common.constant.UserConstants;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.domain.entity.SysDept;
import com.willalp.common.core.domain.entity.SysRole;
import com.willalp.common.core.domain.entity.SysUser;
import com.willalp.common.core.domain.request.SysUserExport;
import com.willalp.common.enums.NumberRuleEnum;
import com.willalp.common.enums.SysOrgCodeEnum;
import com.willalp.common.exception.ServiceException;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.StringUtils;
import com.willalp.common.utils.http.HttpUtils;
import com.willalp.common.utils.spring.SpringUtils;
import com.willalp.number.domain.req.NumberRuleReq;
import com.willalp.number.service.IHsSysNumberRuleService;
import com.willalp.system.domain.*;
import com.willalp.system.domain.resp.AppUserResp;
import com.willalp.system.mapper.*;
import com.willalp.system.service.ISysConfigService;
import com.willalp.system.service.ISysDeptService;
import com.willalp.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author willalp
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private IHsSysNumberRuleService iHsSysNumberRuleService;

    @Autowired
    private SysCardInfoMapper sysCardInfoMapper;

    @Autowired
    private SysUserOrganizationMapper sysUserOrganizationMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Resource
    private HttpUtils httpUtils;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }


    @Override
    public AppUserResp selectAppUserList(SysUser user) {
        return userMapper.selectAppUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertUser(SysUser user) {
//        NumberRuleReq req = new NumberRuleReq();
//        req.setRuleId(NumberRuleEnum.USER.getValue());
//        = iHsSysNumberRuleService.getNumber(req);
//        if (StrUtil.isBlank(code)) {
//            throw new BaseException("system.user.errorCode1", new Object[]{});
//        }
        String code = user.getUserName();
        //会山默认机构
        SysUserOrganization hs = new SysUserOrganization();
        hs.setIsDefault(1);
        hs.setLoginName(code);
        hs.setOrganizationCode(SysOrgCodeEnum.HuiJiFen.getCode());
        hs.setEffectiveDate(DateUtils.addYears(new Date(), 50));
        sysUserOrganizationMapper.insert(hs);
        user.setUserName(code);
        if (!StrUtil.isBlankIfStr(user.getDeptId()) && StrUtil.isNotBlank(user.getUserType())) {
            SysUserOrganization org = new SysUserOrganization();
            org.setLoginName(code);
            org.setOrganizationCode(iSysDeptService.getOrganizationCode(user.getDeptId()));
            org.setUserType(user.getUserType());
            org.setIsDefault(1);
            org.setEffectiveDate(DateUtils.addYears(new Date(), 1));
            sysUserOrganizationMapper.insert(org);
            //默认机构
            SysUserOrganization o = new SysUserOrganization();
            o.setLoginName(user.getUserName());
            List<SysUserOrganization> organizationList = sysUserOrganizationMapper.selectSysUserOrganizationList(o);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                organizationList = organizationList.stream().filter(t -> t.getIsDefault() == 1).collect(Collectors.toList());
                if (organizationList.size() > 1) {
                    for (SysUserOrganization z : organizationList) {
                        if (!z.getOrganizationCode().equals(org.getOrganizationCode())) {
                            z.setIsDefault(0);
                            sysUserOrganizationMapper.updateById(z);
                        }
                    }
                }
            }
        }

        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        String loginName = "";
        if (rows > 0) {
            loginName = code;
        }
        return loginName;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();

        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        user.getOrganizations().add(iSysDeptService.getOrganizationCode(user.getDeptId()));
        if (!user.getOrganizations().isEmpty() && StrUtil.isNotBlank(user.getUserType())) {
            SysUserOrganization org = new SysUserOrganization();
            org.setLoginName(user.getUserName());
            List<SysUserOrganization> list = sysUserOrganizationMapper.selectSysUserOrganizationList(org);
            List<String> codes = list.stream().map(SysUserOrganization::getOrganizationCode).collect(Collectors.toList());
            Boolean flag = true;
            for (String code : user.getOrganizations()) {
                if (!codes.contains(code)) {
                    org.setOrganizationCode(code);
                    org.setLoginName(user.getUserName());
                    org.setUserType(user.getUserType());
                    org.setIsDefault(1);
                    org.setEffectiveDate(DateUtils.addYears(new Date(), 1));
                    sysUserOrganizationMapper.insert(org);
                }
            }
        }
        if (StrUtil.isNotBlank(user.getUserType())) {
            SysUserOrganization temp = new SysUserOrganization();
            temp.setLoginName(user.getUserName());
            temp.setOrganizationCode(iSysDeptService.getOrganizationCode(user.getDeptId()));
            List<SysUserOrganization> organizationList = sysUserOrganizationMapper.selectSysUserOrganizationList(temp);
            if (CollectionUtil.isEmpty(organizationList)) {
                temp.setUserType(user.getUserType());
                temp.setIsDefault(1);
                temp.setEffectiveDate(DateUtils.addYears(new Date(), 1));
                sysUserOrganizationMapper.insert(temp);
            } else {
                temp = organizationList.get(0);
                if (!temp.getUserType().equals(user.getUserType())) {
                    temp.setUserType(user.getUserType());
                    temp.setIsDefault(1);
                    sysUserOrganizationMapper.updateById(temp);
                }
            }
            SysUserOrganization o = new SysUserOrganization();
            o.setLoginName(user.getUserName());
            organizationList = sysUserOrganizationMapper.selectSysUserOrganizationList(o);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                organizationList = organizationList.stream().filter(t -> t.getIsDefault() == 1).collect(Collectors.toList());
                if (organizationList.size() > 1) {
                    for (SysUserOrganization z : organizationList) {
                        if (!z.getOrganizationCode().equals(temp.getOrganizationCode())) {
                            z.setIsDefault(0);
                            sysUserOrganizationMapper.updateById(z);
                        }
                    }
                }
            }
        }
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importUser(List<SysUserExport> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new BaseException("system.user.errorCode4", new Object[]{});
        }
        StringBuffer buf = new StringBuffer();
        Map<String, List<SysUserExport>> group = userList.stream().filter(e ->
                StrUtil.isNotBlank(e.getPhonenumber())).collect(Collectors.groupingBy(SysUserExport::getPhonenumber));
        for (Map.Entry<String, List<SysUserExport>> entry : group.entrySet()) {
            if (entry.getValue().size() > 1) {
                buf.append(entry.getKey()).append(",");
            }
        }
        if (buf.length() > 0) {
            throw new BaseException("system.user.errorCode5", new String[]{
                    buf.deleteCharAt(buf.length() - 1).toString()
            });
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUserExport sysUserExport : userList) {
            SysUser user = BeanUtil.toBean(sysUserExport, SysUser.class);
            String flag = checkPhoneUnique(user);
            if (flag.equals(UserConstants.NOT_UNIQUE)) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：手机号" + user.getPhonenumber() + "已存在");
                continue;
            }
            try {
                // 验证是否存在这个用户
                user.setPassword(SecurityUtils.encryptPassword(password));
                user.setCreateBy(operName);
                if (StrUtil.isNotBlank(sysUserExport.getDeptCode())) {
                    SysDept dept = new SysDept();
                    dept.setDeptCode(sysUserExport.getDeptCode());
                    List<SysDept> list = iSysDeptService.selectDeptList(dept);
                    if (!list.isEmpty()) {
                        user.setDeptId(Long.valueOf(list.get(0).getDeptId()));
                    }
                }
                user.setCreateTime(DateUtils.getNowDate());
                if (StrUtil.isNotBlank(sysUserExport.getRoleCode())) {
                    SysRole role = new SysRole();
                    role.setRoleCode(sysUserExport.getRoleCode());
                    List<SysRole> list = roleMapper.selectRoleList(role);
                    if (!list.isEmpty()) {
                        Long[] roleIds = {list.get(0).getRoleId()};
                        user.setRoleIds(roleIds);
                    }
                }

                this.insertUser(user);

                if (StrUtil.isNotBlank(sysUserExport.getCardUsername())) {
                    SysCardInfo sysCardInfo = new SysCardInfo();
                    while (true) {
                        String idStr = IdWorker.getIdStr();
                        SysCardInfo byId = sysCardInfoMapper.selectById(idStr);
                        if (null == byId) {
                            sysCardInfo.setId(idStr);
                            break;
                        }
                    }
                    sysCardInfo.setCardUsername(sysUserExport.getCardUsername());
                    sysCardInfo.setCardPhonenumber(sysUserExport.getCardPhonenumber());
                    sysCardInfo.setCardPassword(SecurityUtils.encryptPassword(password));
                    sysCardInfo.setUserId(user.getUserName());
                    sysCardInfo.setOrganizationCode(user.getOrganizationCode());
                    sysCardInfo.setIsDelete(0);
                    sysCardInfo.setCreateBy(operName);
                    sysCardInfo.setCreateTime(DateUtils.getNowDate());
                    NumberRuleReq req = new NumberRuleReq();
                    req.setRuleId(NumberRuleEnum.CARD.getValue());
                    String code = iHsSysNumberRuleService.getNumber(req);
                    if (StrUtil.isBlank(code)) {
                        throw new BaseException("system.card.errorCode1", new Object[]{});
                    }
                    sysCardInfo.setCardCode(code);
                    sysCardInfoMapper.insert(sysCardInfo);
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
//                SysUser u = userMapper.selectUserByUserName(user.getUserName());
//                if (StringUtils.isNull(u)) {
//                    user.setPassword(SecurityUtils.encryptPassword(password));
//                    user.setCreateBy(operName);
//                    this.insertUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
//                } else if (isUpdateSupport) {
//                    user.setUpdateBy(operName);
//                    this.updateUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
//                } else {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
//                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<SysUser> queryUserInfoByUserName(String userName) {
        List<SysUser> list = userMapper.queryUserByUserNameOrNickName(userName);
        if (list.isEmpty()) {
            throw new BaseException("system.user.errorCode2", new String[]{
                    userName
            });
        }

        return list;
    }

    @Override
    public List<SysUser> queryUser() {
        List<SysUser> list = userMapper.queryUser();
        return list;
    }

    @Override
    public void singleUserTypeAuth(SysUserOrganization sysUserOrganization) {
        String[] loginNameList = sysUserOrganization.getLoginName().split(",");
        List<SysUserOrganization> organs = new ArrayList<>();
        for (int i = 0; i < loginNameList.length; i++) {
            SysUserOrganization temp = new SysUserOrganization();
            BeanUtil.copyProperties(sysUserOrganization, temp);
            temp.setLoginName(loginNameList[i]);
            organs.add(temp);
        }

        organs.forEach(t -> {
            String sslPost = httpUtils.sendGet(httpUtils.getHttpsMasterUrl("/org/binding"), "uc=" + t.getLoginName());
            AjaxResult ajaxResult = JSON.parseObject(sslPost, AjaxResult.class);
            if (((int) ajaxResult.get(AjaxResult.CODE_TAG)) == 500) {
                log.error("绑定失败 - 无法同步主服务数据");
            }
            //判断是否已有机构
            SysUserOrganization exist = new SysUserOrganization();
            exist.setLoginName(t.getLoginName());
            exist.setOrganizationCode(t.getOrganizationCode());
            List<SysUserOrganization> exists = sysUserOrganizationMapper.selectSysUserOrganizationList(exist);
            if (CollectionUtil.isNotEmpty(exists)) {
                exist = exists.get(0);
                exist.setEffectiveDate(t.getEffectiveDate());
                exist.setUserType(t.getUserType());
                sysUserOrganizationMapper.updateById(exist);
            } else {
                t.setIsDefault(1);
                sysUserOrganizationMapper.insert(t);
            }
            //用户部门为空时添加机构为部门
            SysUser user = userMapper.selectUserByUserName(t.getLoginName());
            if (user.getDeptId() == null) {
                SysDept dept = new SysDept();
                dept.setDeptCode(t.getOrganizationCode());
                List<SysDept> depts = sysDeptMapper.selectDeptList(dept);
                if (CollectionUtil.isNotEmpty(depts)) {
                    dept = depts.get(0);
                    user.setDeptId(Long.valueOf(dept.getDeptId()));
                    userMapper.updateUser(user);
                }
            }
            //默认机构
            SysUserOrganization o = new SysUserOrganization();
            o.setLoginName(user.getUserName());
            List<SysUserOrganization> organizationList = sysUserOrganizationMapper.selectSysUserOrganizationList(o);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                organizationList = organizationList.stream().filter(tt -> tt.getIsDefault() == 1).collect(Collectors.toList());
                if (organizationList.size() > 1) {
                    for (SysUserOrganization z : organizationList) {
                        if (!z.getOrganizationCode().equals(sysUserOrganization.getOrganizationCode())) {
                            z.setIsDefault(0);
                            sysUserOrganizationMapper.updateById(z);
                        }
                    }
                }
            }
        });
    }

    @Override
    public SysUser getUserByPhone(String phoneNumber) {
        return userMapper.checkPhoneUnique(phoneNumber);
    }

    @Override
    public List<SysUser> getIntegralUsers(String organizationCode) {
        return userMapper.getIntegralUsers(organizationCode);
    }

    @Override
    public List<SysUser> getUserOrganization(String organizationCode) {
        return userMapper.getUserOrganization(organizationCode);
    }

    @Override
    public List<SysUser> getUserBindingList(String[] userIds) {
        return userMapper.getUserBindingList(userIds);
    }

    @Override
    public List<SysUser> getAllUser() {
        return userMapper.getAllUser();
    }


}
