package com.fs.company.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.BeanCopyUtils;
import com.fs.common.QRutils;
import com.fs.common.annotation.DataScope;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.ServiceException;
import com.fs.common.exception.file.OssException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PatternUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.*;
import com.fs.company.mapper.*;
import com.fs.company.param.CompanyUserAreaParam;
import com.fs.company.param.CompanyUserCodeParam;
import com.fs.company.param.CompanyUserQwParam;
import com.fs.company.service.*;
import com.fs.company.vo.*;
import com.fs.course.service.IFsUserCompanyUserService;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.service.IFsCityService;
import com.fs.his.vo.CitysAreaVO;
import com.fs.his.vo.OptionsVO;
import com.fs.hisStore.domain.FsStoreProductAttrScrm;
import com.fs.hisStore.domain.FsStoreProductAttrValueScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.dto.ProductArrtDTO;
import com.fs.hisStore.vo.FsStoreProductExportVO;
import com.fs.qw.domain.QwUser;
import com.fs.qw.dto.UserProjectDTO;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwOptionsVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysRoleService;
import com.fs.system.service.ISysUserService;
import com.fs.voice.utils.StringUtil;
import com.fs.wxUser.domain.CompanyWxUser;
import com.github.pagehelper.PageHelper;
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 org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 物业公司管理员信息Service业务层处理
 *
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyUserServiceImpl implements ICompanyUserService
{
    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private CompanyRoleMapper roleMapper;

    @Autowired
    private CompanyPostMapper postMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private CompanyDeptMapper companyDeptMapper;

    @Autowired
    private CompanyUserRoleMapper userRoleMapper;

    @Autowired
    private CompanyUserPostMapper userPostMapper;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    public IFsCityService iFsCityService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private IFsUserCompanyUserService userCompanyUserService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IQwUserService qwUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ICompanyConfigService companyConfigService;

//    @Autowired
//    private ICompanyUserRoleService userRoleService;


    /**
     * 查询物业公司管理员信息
     *
     * @param userId 物业公司管理员信息ID
     * @return 物业公司管理员信息
     */
    @Override
    public CompanyUser selectCompanyUserById(Long userId)
    {
        return companyUserMapper.selectCompanyUserById(userId);
    }

    @Override
    public CompanyUser selectCompanyUserByIdForRedis(Long userId) {

        String key =(String)redisCache.getCacheObject("companyUserInfo:"+userId);
        if (!StringUtil.strIsNullOrEmpty(key)){
            return JSON.parseObject(key, CompanyUser.class);
        }
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);

        redisCache.setCacheObject("companyUserInfo:"+userId ,JSON.toJSONString(companyUser),45, TimeUnit.MINUTES);

        return companyUser;
    }

    /**
     * 查询物业公司管理员信息列表
     *
     * @param companyUser 物业公司管理员信息
     * @return 物业公司管理员信息
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUser> selectCompanyUserList(CompanyUser companyUser)
    {
        return companyUserMapper.selectCompanyUserList(companyUser);
    }

    /**
     * 新增物业公司管理员信息
     *
     * @param companyUser 物业公司管理员信息
     * @return 结果
     */
    @Override
    public int insertCompanyUser(CompanyUser companyUser)
    {
        companyUser.setCreateTime(DateUtils.getNowDate());
        return companyUserMapper.insertCompanyUser(companyUser);
    }

    @Override
    public String importCompanyUser(List<CompanyUserImportVO> list, boolean updateSupport) {

        if (com.fs.common.utils.StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入销售信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CompanyUserImportVO importVO : list){
            try
            {
                CompanyUser copy = BeanCopyUtils.copy(importVO, CompanyUser.class);

                assert copy != null;

                if (StringUtil.strIsNullOrEmpty(copy.getPassword())){
                    throw new CustomException("密码不能为空");
                }


                if (!PatternUtils.checkPassword(copy.getPassword())) {
                    throw new CustomException("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20 位");
                }

                if (copy.getCompanyId() == null){
                    throw new CustomException("公司ID不能为空,且为数字!");
                } else if (!String.valueOf(copy.getCompanyId()).matches("\\d+")) {
                    throw new CustomException("公司ID必须为数字!");
                }

                if (copy.getDeptId() == null){
                    throw new CustomException("部门编号不能为空,且为数字!");
                } else if (!String.valueOf(copy.getDeptId()).matches("\\d+")) {
                    throw new CustomException("部门编号必须为数字!");
                }

                if (StringUtil.strIsNullOrEmpty(copy.getPhonenumber())){
                    throw new CustomException("手机号不能为空");
                } else if (!copy.getPhonenumber().matches("\\d+")) {
                    throw new CustomException("手机号必须为数字!");
                }

                if (StringUtil.strIsNullOrEmpty(copy.getAddressId())){
                    throw new CustomException("区域不能为空");
                } else if (!copy.getAddressId().matches("\\d+")) {
                    throw new CustomException("区域ID必须为数字!");
                }

                Integer count=companyUserService.selectCompanyUserCountByCompanyId(copy.getCompanyId());
                Company company=companyService.selectCompanyById(copy.getCompanyId());
                if (company== null) {
                    throw new CustomException("未查询到相应的销售公司!");
                }

                if(count>company.getLimitUserCount()){
                    throw new CustomException("销售公司的销售数量已达到上限!");
                }

                if (UserConstants.NOT_UNIQUE.equals(String.valueOf(companyUserService.checkUserName(copy.getUserName()))))
                {
                    throw new CustomException("新增用户'" + copy.getUserName() + "'失败，登录账号已存在");
                }

                if (StringUtil.strIsNullOrEmpty(copy.getNickName())){
                    throw new CustomException("用户昵称不能为空");
                }

                if (StringUtil.strIsNullOrEmpty(importVO.getRoleString())){
                    throw new CustomException("角色-不能为空");
                }

                try {
                    String[] splitRoles = splitRoles(importVO.getRoleString());

                    // 新增用户与岗位管理
                    Set<Long> setList= new HashSet<>();

                    for (String stringRole : splitRoles) {
                        Long rolesId = roleMapper.selectRolesByUserNameAndCompanyId(stringRole, copy.getCompanyId());

                        if (StringUtils.isNotNull(rolesId)) {
                            setList.add(rolesId);
                        }else {
                            throw new CustomException("当前销售公司没有此角色");
                        }
                    }

                    // 转换为 Long[]
                    Long[] roleIds = setList.toArray(new Long[0]);
                    copy.setRoleIds(roleIds);


                }catch (Exception e){
                    throw new CustomException("角色-格式不正确");
                }



                copy.setUserType("01");//一般用户
                copy.setIsAudit(1);
                copy.setPassword(SecurityUtils.encryptPassword(copy.getPassword()));
                copy.setCreateTime(new Date());
                copy.setStatus("0");

                int rows = companyUserMapper.insertCompanyUser(copy);
                if (rows>0){
                    // 新增用户与角色管理
                    insertUserRole(copy);
                }else {
                    throw new CustomException("新增用户'" + copy.getUserName() + "'失败");
                }


                successNum++;
                successMsg.append("<br/>" + successNum + "、销售账号 " + copy.getUserName() + " 导入成功");
            }
            catch (Exception e)
            {

                failureNum++;
                String msg = "<br/>" + failureNum + "、销售账号 " + importVO.getUserName()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }

        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    public String[] splitRoles(String roleString) {
        if (roleString == null || roleString.trim().isEmpty()) {
            return new String[0];
        }

        // 预处理：替换中文标点，去除首尾空格
        String processed = roleString
                .replace("，", ",")
                .replace("；", ";")
                .replace("、", ",")
                .trim();

        // 分割并过滤空值
        return Arrays.stream(processed.split("[,;\\s]+"))
                .filter(s -> !s.isEmpty())
                .map(String::trim)
                .toArray(String[]::new);
    }

    /**
     * 修改物业公司管理员信息
     *
     * @param companyUser 物业公司管理员信息
     * @return 结果
     */
    @Override
    public int updateCompanyUser(CompanyUser companyUser)
    {
        companyUser.setUpdateTime(DateUtils.getNowDate());
//        if (companyUser.getStatus().equals("1")){
//            CompanyVoiceCaller caller = callerMapper.selectCompanyVoiceCallerByUserId(companyUser.getCompanyId(),companyUser.getUserId());
//            caller.setCompanyId(0l);
//            caller.setCompanyUserId(0l);
//            caller.setMobile("");
//            caller.setStatus(1);
//            callerMapper.updateCompanyVoiceCaller(caller);
//        }
        return companyUserMapper.updateCompanyUser(companyUser);
    }

    @Override
    public int updateAllCompanyUser(CompanyUser companyUser) {
        return companyUserMapper.updateAllCompanyUser(companyUser);
    }


    /**
     * 批量删除物业公司管理员信息
     *
     * @param userIds 需要删除的物业公司管理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserByIds(Long[] userIds)
    {

        for (int i = 0; i <userIds.length ; i++) {
            //清除企微的销售的绑定关系
            qwUserMapper.updateUserByUserId(userIds[i]);
        }

        return companyUserMapper.deleteCompanyUserByIds(userIds);
    }

    /**
     * 删除物业公司管理员信息信息
     *
     * @param userId 物业公司管理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserById(Long userId)
    {
        return companyUserMapper.deleteCompanyUserById(userId);
    }

    @Override
    public CompanyUser selectUserByUserName(String account) {
        return companyUserMapper.selectUserByUserName(account);
    }

    @Override
    public String selectUserRoleGroup(String username) {
        List<CompanyRole> list = roleMapper.selectRolesByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserPostGroup(String username) {
        List<CompanyPost> list = postMapper.selectPostsByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public int updateUserAvatar(String username, String avatar) {
        return companyUserMapper.updateUserAvatar(username, avatar) ;
    }

    @Override
    public int resetUserPwd(String userName, String encryptPassword) {
        return companyUserMapper.resetUserPwd(userName, encryptPassword);
    }

    @Override
    public int updateUserProfile(CompanyUser user) {
        return companyUserMapper.updateCompanyUser(user);
    }

    @Override
    public int checkUserName(String userName) {
        return companyUserMapper.checkUserName(userName);
    }


    @Override
    @Transactional
    public int insertUser(CompanyUser user)
    {
        logger.info("打印邀请用户信息------------------------------》：{}",user);
        // 新增用户信息
        int rows = companyUserMapper.insertCompanyUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        //新增用户需要修改密码
        redisCache.setCacheObject("newCompanyUser:" + user.getCompanyId() + ":" +user.getUserName(),user.getUserId());
        return rows;
    }

    @Override
    public R registerCompany(CompanyUserCodeParam userCodeParam) {
        CompanyUser user=new CompanyUser();

        QwUser qwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(userCodeParam.getCorpId(),userCodeParam.getQwUserIdByStr());

        if (qwUser==null){
            return R.error("无企微员工信息,无法处理，请先同步员工:"+ userCodeParam.getQwUserIdByStr()+"--"+userCodeParam.getCorpId());
        }

        if (qwUser.getCompanyUserId()!=null&&!qwUser.getCompanyUserId().equals(qwUser.getCompanyUserId())){
            return R.error( qwUser.getQwUserName()+"已经被其他人绑定，请先解绑");
        }

        if (userCodeParam.getBindType()==1){

            if (!PatternUtils.checkPassword(userCodeParam.getPassword())) {
                return R.error("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20 位");
            }

            //判断用户数量是否已达到上线
            Integer count=companyUserService.selectCompanyUserCountByCompanyId(userCodeParam.getCompanyId());
            Company company=companyService.selectCompanyById(userCodeParam.getCompanyId());

            if(count>company.getLimitUserCount()){
                return R.error("用户数量已达到上限");
            }

            if (UserConstants.NOT_UNIQUE.equals(String.valueOf(companyUserService.checkUserName(userCodeParam.getUserName()))))
            {
                return R.error("新增用户'" + userCodeParam.getUserName() + "'失败，登录账号已存在");
            }
            user.setNickName(userCodeParam.getNickName());
            user.setUserName(userCodeParam.getUserName());
            user.setSex(userCodeParam.getSex());
            user.setStatus("1");
            user.setDeptId(userCodeParam.getDeptId());
            user.setPhonenumber(userCodeParam.getPhonenumber());
            user.setRoleIds(userCodeParam.getRoleIds());
            user.setAddressId(userCodeParam.getAddressId());
            user.setCompanyId(userCodeParam.getCompanyId());
            user.setCreateBy(userCodeParam.getQwUserIdByStr());
            user.setPassword(SecurityUtils.encryptPassword(userCodeParam.getPassword()));
            user.setCreateTime(new Date());
            user.setUserType("01");//一般用户
            user.setIsAudit(1);

            int i = companyUserService.insertUser(user);
            if (i>0){

                CompanyUser companyUser = companyUserMapper.selectUserByUserName(userCodeParam.getUserName());

                bindQwUserToCompanyUser(qwUser, companyUser);

            }else {
                return R.error("销售创建失败");
            }

            return R.ok();

        }
        else if (userCodeParam.getBindType()==2){

            // 绑定到现有用户
            CompanyUser companyUser = companyUserMapper.selectUserByUserName(userCodeParam.getUserName());
            if (companyUser == null) {
                return R.error("指定的用户不存在");
            }

            bindQwUserToCompanyUser(qwUser, companyUser);
        }

        return R.error();
    }

    private void bindQwUserToCompanyUser(QwUser qwUser, CompanyUser companyUser) {
        // 更新公司用户的企微ID列表
        Set<String> qwUserIdSet = new HashSet<>();

        if (!StringUtil.strIsNullOrEmpty(companyUser.getQwUserId())) {
            String[] existingIds = companyUser.getQwUserId().split(",");
            qwUserIdSet.addAll(Arrays.stream(existingIds)
                    .filter(id -> !id.isEmpty())
                    .collect(Collectors.toSet()));
        }

        qwUserIdSet.add(String.valueOf(qwUser.getId()));
        companyUser.setQwUserId(String.join(",", qwUserIdSet));
        companyUser.setQwStatus(1);
        companyUserMapper.updateCompanyUser(companyUser);

        // 更新企微用户信息
        QwUser qw = new QwUser();
        qw.setCompanyUserId(companyUser.getUserId());
        qw.setId(qwUser.getId());
        qw.setStatus(1);
        qw.setCompanyId(companyUser.getCompanyId());
        qwUserService.updateQwUser(qw);
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(CompanyUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        logger.info("wc \n 【删除角色】:{}", user.getUserName());
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return companyUserMapper.updateCompanyUser(user);
    }

    @Override
    public int resetUserPwdByUserId(Long userId, String encryptPassword) {
        return companyUserMapper.resetUserPwdByUserId(userId,encryptPassword);
    }

    @Override
    public List<Map<String, Object>> selectAllUsersList(CompanyUser user) {
        List<CompanyUser> users = companyUserMapper.selectAllUsersList(user);
        Set<String> firstChar = new HashSet<String>();
        for (CompanyUser u: users){
            firstChar.add(u.getFirstchar());
        }
        List<Map<String,Object>> userlist = new ArrayList<>();
        for(String n:firstChar){
            Map<String,Object> map = new HashMap<>();
            List<CompanyUser> subMenuIds = users.stream().filter(s->s.getFirstchar().equals(n)).collect(Collectors.toList());
            map.put("letter",n);
            map.put("data",subMenuIds);
            userlist.add(map);
        }
        return userlist;
    }

    @Override
    public List<CompanyUserVO> selectMyUserList(CompanyUser user) {
        return companyUserMapper.selectMyUserList(user);
    }

    @Override
    @DataScope(deptAlias = "u",userAlias = "u")
    public List<CompanyUser> getUserListByDeptId(CompanyUser user) {
        return companyUserMapper.getUserListByDeptId(user);
    }

    @Override
    public Integer selectCompanyUserCountByCompanyId(Long companyId) {
        return companyUserMapper.selectCompanyUserCountByCompanyId(companyId);
    }

    @Override
    public String checkUserNameUnique(String userName) {
        return companyUserMapper.checkUserNameUnique(userName)>0?"1":"0";
    }

    @Override
    public List<DocCompanyUserVO> selectDocCompanyUserListByIds(String companyUserIds) {
        return companyUserMapper.selectDocCompanyUserListByIds(companyUserIds);
    }


    @Override
    public List<DocCompanyUserVO> selectDocCompanyUserListByUserIds(Set<Long> userIds) {
        return companyUserMapper.selectDocCompanyUserListByUserIds(userIds);
    }

    @Override
    public CompanyUser selectCompanyUserByCompanyIdAndNickName(long companyId, String nickName) {
        return companyUserMapper.selectCompanyUserByCompanyIdAndNickName(companyId,nickName);
    }

    @Override
    public List<CompanyUserVO> selecCompanyAllUsersList(CompanyUser map) {
        return companyUserMapper.selecCompanyAllUsersList(map);
    }

    @Override
    public List<CompanyUserQwVO> getUserListByDeptIdToQwUserid(CompanyUser user) {
        return companyUserMapper.getUserListByDeptIdToQwUserid(user);
    }

    @Override
    public List<CitysAreaVO> getCitysAreaList() {
        return iFsCityService.getCitysArea();
    }

    @Override
    public List<QwUserVO> selectCompanyQwUserList(String corpId,Long companyId) {
        return companyUserMapper.selectCompanyQwUserList(corpId,companyId);
    }

    @Override
    public List<QwUserVO> selectCompanyQwUserListByMy(String corpId, Long companyId, Long userId) {
        return companyUserMapper.selectCompanyQwUserListByMy(corpId,companyId,userId);
    }

    @Override
    public List<QwUserVO> selectCompanyQwUserListByDept(String corpId, Long companyId, List<Long> combinedList, String userType) {
        return companyUserMapper.selectCompanyQwUserListByDept(corpId,companyId,combinedList,userType);
    }

    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUserQwListVO> selectCompanyUserQwListVO(CompanyUserQwParam user) {
//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(user.getCompanyId(), "company:admin:show");
        boolean  isAdminShow = false;
//        if(!StringUtils.isEmpty(companyConfig.getConfigValue())){
//            isAdminShow = Boolean.parseBoolean(companyConfig.getConfigValue());
//        }
        if(isAdminShow){
            Company company = companyService.selectCompanyById(user.getCompanyId());
            Long userId = company.getUserId();
            user.setUserId(userId);
        }
        PageHelper.startPage(user.getPageNum(), user.getPageSize());
        List<CompanyUserQwListVO> companyUserQwListVOS = companyUserMapper.selectCompanyUserQwListVO(user);
        return companyUserQwListVOS;
    }

    @Override
    public R updateCompanyUserAreaList(CompanyUserAreaParam param) {

        int i = companyUserMapper.updateCompanyUserAreaList(param);
        if (i > 0) {
            return R.ok("操作成功");
        }else {
            return R.error("操作失败");
        }

    }

    @Override
    public CompanyWxUser selectCompanyUserByNickName(Long companyUserId, String nickName) {
        return companyUserMapper.selectCompanyUserByNickName(companyUserId, nickName);
    }

    @Override
    public List<CompanyQwUserByIdsVo> selectCompanyQwUserByIds(List<Long> ids) {
        return companyUserMapper.selectCompanyQwUserByIds(ids);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(CompanyUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<CompanyUserPost> list = new ArrayList<CompanyUserPost>();
            for (Long postId : posts)
            {
                CompanyUserPost up = new CompanyUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }
    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(CompanyUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<CompanyUserRole> list = new ArrayList<>();
            for (Long roleId : roles)
            {
                CompanyUserRole ur = new CompanyUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
                logger.info("wc \n 【完成角色更新】:{}", user.getUserName());
            }
        }
    }

    @Override
    public List<CompanyUser> selectCompanyUserByIds(Set<Long> ids) {
        return companyUserMapper.selectCompanyUserByIds(ids);
    }

    @Override
    public CompanyUser selectCompanyUserByUserId(Long userId) {
        return companyUserMapper.selectCompanyUserByUserId(userId);
    }

    @Override
    public String selectCompanyUserNameUserById(Long userId) {
        return companyUserMapper.selectCompanyUserNameUserById(userId);
    }

    @Override
    public List<Long> selectUserAllCompanyUserId(Long companyUserId) {
        return companyUserMapper.selectUserAllCompanyUserId(companyUserId);
    }

    @Override
    public List<CompanyUser> getAllUserListLimit(Long companyId, String keywords) {
        return companyUserMapper.getAllUserListLimit(companyId,keywords);
    }

    @Override
    public List<CompanyUser> selectAllCompanyUserAndSelf(Long userId) {
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        List<CompanyUser> list = new ArrayList<>();
        if (companyUser.isAdmin()){
            list = companyUserMapper.selectAllCompanyUserAndSelf(userId,companyUser.getCompanyId());
        }else {
            list =   companyUserMapper.selectAllCompanyUserAndSelf(userId,null);
        }
        return list;
    }

    /**
     * 查询销售列表
     * @param companyId 公司ID
     * @param deptId 部门ID
     * @return list
     */
    @Override
    public List<CompanyUser> getCompanyUserListByCompanyIdAndDeptId(Long companyId, Long deptId) {
        return companyUserMapper.selectAllCompanyUserByCompanyIdAndDeptId(companyId, deptId);
    }

    @Override
    public CompanyUser getCompanyUserByOpenId(String openId) {
        return companyUserMapper.getCompanyUserByOpenId(openId);
    }

    @Override
    public CompanyUser getCompanyUserByPhone(String phoneNumber) {
        return companyUserMapper.getCompanyUserByPhone(phoneNumber);
    }

    @Override
    public int changeCompanyUser(List<UserProjectDTO> users, Long companyUserId, Long companyId) {

        CompanyUser toUser = companyUserMapper.selectCompanyUserById(companyUserId);
        if (Objects.isNull(toUser)) {
            throw new ServiceException("需要更换归属的销售不存在");
        }
        for (UserProjectDTO u : users) {
            userCompanyUserService.changeRelationship(u.getUserId(), u.getProjectId(), toUser.getCompanyId(), toUser.getUserId());
        }
        return 1;
    }

    /**
     * 查询销售选项列表
     * @param params    参数
     * @return  list
     */
    @Override
    public List<OptionsVO> selectCompanyUserListByMap(Map<String, Object> params) {
        return companyUserMapper.selectCompanyUserListByMap(params);
    }

    @Override
    public Boolean setIsRegisterMember(boolean status, List<Long> userIds) {
        try {
            companyUserMapper.setIsRegisterMember(status, userIds);
        } catch (RuntimeException e) {
            throw new ServiceException("操作异常");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditUsers(List<Long> userIds,Long companyId) {
        if (userIds.isEmpty()) {
            return;
        }
        //获取用户信息
        List<CompanyUser> companyUserList=companyUserMapper.getUserInfoByUserIds(userIds);

        if(ObjectUtil.isNotNull(companyUserList) && !companyUserList.isEmpty()){

            //获取默认角色信息
            CompanyRole role=roleMapper.selectCompanyRoleByRoleKey(companyId+"_sales");

            //获取默认部门
            CompanyDept dept= companyDeptMapper.selectDeptNameBydeptName("销售(默认部门)");

            //获取默认岗位
            CompanyPost companyPost= postMapper.selectCompanyPostCode("default_sale",companyId);

            //存储用户角色中间表
            List<CompanyUserRole> companyUserRoleList=new LinkedList<>();

            //存储岗位
            List<CompanyUserPost> companyUserPosts=new LinkedList<>();
            companyUserList.stream().forEach(c->{
                //判断角色是否为空
                if(ObjectUtil.isNotNull(role)){
                    //判断该用户角色是否存在
                    CompanyUserRole companyUserRole = userRoleMapper.selectCompanyUserRoleById(c.getUserId());
                    if(companyUserRole == null || !Objects.equals(companyUserRole.getRoleId(), role.getRoleId())){
                        CompanyUserRole userRole=new CompanyUserRole();
                        userRole.setRoleId(role.getRoleId());
                        userRole.setUserId(c.getUserId());
                        companyUserRoleList.add(userRole);
                    }
                }

                //判断部门
                if(ObjectUtil.isNotNull(dept)){
                    c.setDeptId(dept.getDeptId());
                }

                //判断岗位
                if(ObjectUtil.isNotNull(companyPost)){
                    //判断该岗位是否存在
                    CompanyUserPost companyUserPost = userPostMapper.selectCompanyUserPostById(c.getUserId());
                    if(companyUserPost == null || !Objects.equals(companyUserPost.getPostId(), companyPost.getPostId())){
                        //添加用户岗位表
                        CompanyUserPost userPost=new CompanyUserPost();
                        userPost.setPostId(companyPost.getPostId());
                        userPost.setUserId(c.getUserId());
                        companyUserPosts.add(userPost);
                    }
                }
            });

            //批量插入角色用户中间表
            if(!companyUserRoleList.isEmpty()){
                userRoleMapper.batchUserRole(companyUserRoleList);
            }

            //批量插入用户岗位中间表
            if(!companyUserPosts.isEmpty()){
                userPostMapper.batchUserPost(companyUserPosts);
            }

            //批量更新用户部门信息
            companyUserMapper.batchUpdateUserDept(companyUserList);

            companyUserMapper.auditUsers(userIds);
        }

    }

    @Override
    public CompanyUser selectCompanyUserByPhone(String phone) {
        return companyUserMapper.selectCompanyUserByPhone(phone);
    }

    @Override
    public List<CompanyUser> getCompanyUserList(CompanyUser companyUser) {
        return companyUserMapper.getCompanyUserList(companyUser);
    }

    @Override
    public List<QwOptionsVO> selectQwUserListLikeName(Map<String, Object> params) {
        return companyUserMapper.selectQwUserListLikeName(params);
    }

    @Override
    public String selectCompanyUserByStrIds(String companyUserIds) {
        return companyUserMapper.selectCompanyUserNameByIds(companyUserIds);
    }

    @Override
    public Boolean isAllowedAllRegister(boolean status, List<Long> userIds) {
        try {
            companyUserMapper.updateAllowedAllRegister(status, userIds);
        } catch (RuntimeException e) {
            throw new ServiceException("操作异常");
        }
        return true;
    }

    @Override
    public List<QwIpadTotalVo> selectCompanyByIpadStatus(String dateTime) {
        return companyUserMapper.selectCompanyByIpadStatus(dateTime);
    }

    @Override
    public List<QwIpadTotalVo> selectCompanyByIpadStatusCount() {
        return companyUserMapper.selectCompanyByIpadStatusCount();
    }

    @Override
    public int insertQwIpadTotal(List<QwIpadTotalVo> qwIpadTotalVos) {
        return companyUserMapper.insertQwIpadTotal(qwIpadTotalVos);
    }
    @Override
    public String uploadQrCode(MultipartFile file, String userId) throws IOException {
        if (file.isEmpty())
        {
            throw new OssException("上传文件不能为空");
        }
        // 上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(file.getBytes(), suffix);

        if(userId == null) {
            throw new CustomException("上传二维码失败！userId 为空！");
        }
        companyUserMapper.uploadQrCode(userId,url);
        return url;
    }

    @Override
    public R bindDoctor(CompanyUser companyUser) {
        CompanyUser map = new CompanyUser();
        map.setUserId(companyUser.getUserId());
        map.setDoctorId(companyUser.getDoctorId());
        int i = companyUserMapper.updateCompanyUser(map);
        if (i > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @Override
    public R unBindDoctor(Long userId) {
        int i = companyUserMapper.unBindDoctorId(userId);
        if (i > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    private final static String bindBaseUrl = "https://userapp.jnmyunl.com/bindcompanyuser?companyUserId=";
    /**
     * @param companyUserId
     * @return
     */
    @Override
    public R getBindInfo(Long companyUserId) {
        //链接
        String url = bindBaseUrl + companyUserId;
        //查询码是否存在
        CompanyUser companyUser = selectCompanyUserById(companyUserId);
        if (companyUser != null) {
            if (StringUtils.isBlank(companyUser.getBindCode())) {
                //生成二维码
                InputStream qrCodeStream = QRutils.getQRCodeImageInputStream(url, 250, 250);
                CloudStorageService storage = OSSFactory.build();
                if (storage != null) {
                    String link = storage.uploadSuffix(qrCodeStream, ".jpg");
                    companyUser.setBindCode(link);
                    updateCompanyUser(companyUser);

                }
            }
            return R.ok().put("url", url).put("imageUrl", companyUser.getBindCode());
        }
        return R.error();
    }

    /**
     * 批量修改角色
     * @param batchUserRolesVO 批量修改角色参数
     */
    @Override
    public R updateBatchUserRoles(BatchUserRolesVO batchUserRolesVO) {
        Long[] roleIds = batchUserRolesVO.getRoleIds();
        Long[] userIds = batchUserRolesVO.getUserIds();
        //先删除之前关联的角色
        userRoleMapper.deleteCompanyUserRoleByIds(userIds);
        for (Long userId : userIds){
            try {
                CompanyUser companyUser = selectCompanyUserById(userId);
                companyUser.setRoleIds(roleIds);
                //updateUser(companyUser) 直接使用这个方法后屏蔽下方代码也可以
                insertUserRole(companyUser);
                userPostMapper.deleteUserPostByUserId(userId);
                insertUserPost(companyUser);
                companyUserMapper.updateCompanyUser(companyUser);
            }catch (Exception exception){
                throw new CustomException("修改失败");
            }
        }
        return R.ok("修改成功");
    }

    @Override
    public List<Long> selectCompanyQwUserByDept(List<Long> deptList,String userType) {
        return companyUserMapper.selectCompanyQwUserByDept(deptList,userType);
    }
}
