package jnpf.personnels.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jnpf.account.PTenantAccountApi;
import jnpf.attendance.AttendanceGroupApi;
import jnpf.attendance.AttendanceUserApi;
import jnpf.attendance.dto.AttendanceUserGroupVo;
import jnpf.attendance.dto.GroupUpdateByUserDTO;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.entity.StoreEntity;
import jnpf.entity.StoreUserRelation;
import jnpf.enums.personnel.PersonnelFormDataSystemRosterFields;
import jnpf.exception.LoginException;
import jnpf.model.personnels.bo.ExportRosterOneVo;
import jnpf.model.personnels.bo.FtbRosterImportTemplateBO;
import jnpf.model.personnels.dto.staff.employment.FtbPersonnelsStaffEmploymentApplyDto;
import jnpf.model.personnels.dto.staff.field.*;
import jnpf.model.personnels.dto.staff.registerform.ProbationPeriodDto;
import jnpf.model.personnels.dto.staff.registerform.WorkAddressDto;
import jnpf.model.personnels.dto.staff.roster.*;
import jnpf.model.personnels.dto.staff.transfer.TransferPositionDto;
import jnpf.model.personnels.dto.turnover.SaveTenantUserForm;
import jnpf.model.personnels.po.FtbPersonnelsRegistrationFormFieldOption;
import jnpf.model.personnels.po.FtbPersonnelsStaffRegistrationFormData;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.req.roster.UserAccountDto;
import jnpf.model.personnels.vo.roster.FtbRosterInsertAttributesVO;
import jnpf.model.personnels.vo.roster.FtbRosterInsertNomalVO;
import jnpf.model.personnels.vo.turnover.FtbPersonnelsTurOrgInfo;
import jnpf.model.personnels.vo.turnover.FtbPersonnelsTurnoverManagementVO;
import jnpf.model.store.vo.StoreUserRelationVo;
import jnpf.permission.*;
import jnpf.permission.dto.QueryUserListDTO;
import jnpf.permission.dto.SaveUserManagerAddDTO;
import jnpf.permission.dto.SynUserBoundRoleDTO;
import jnpf.permission.dto.UpdateUserManagerBoundDTO;
import jnpf.permission.dto.v2.UserBoundInfoDTO;
import jnpf.permission.dto.v2.user.UpdateUserDTO;
import jnpf.permission.entity.*;
import jnpf.permission.model.position.PositionGradesInfoVO;
import jnpf.permission.model.role.RoleListVO;
import jnpf.permission.model.role.UserBoundRolesVO;
import jnpf.permission.model.user.*;
import jnpf.permission.vo.contract.ContractTypeVO;
import jnpf.permission.vo.user.UserBasicVO;
import jnpf.permission.vo.v2.grades.GradeVO;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.personnels.service.FtbPersonnelsTurnoverManagementService;
import jnpf.personnels.service.FtbPersonnelsUchisuikePondService;
import jnpf.store.mapper.StoreMapper;
import jnpf.store.mapper.StoreUserRelationMapper;
import jnpf.util.Constants;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import jnpf.utils.FeignHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
public class PersonnelOrgUtils {

    @Autowired
    private OrganizeApi organizeApi;

    @Autowired
    private PositionApi positionApi;

    @Autowired
    private UserApi userApi;

    @Autowired
    private RoleApi roleApi;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private ContractTypeApi contractTypeApi;

    @Autowired
    private PTenantAccountApi pTenantAccountApi;

    @Autowired
    private FTBApi ftbApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FtbPersonnelsUchisuikePondService ftbPersonnelsUchisuikePondService;

    @Autowired
    private StoreUserRelationMapper storeUserRelationMapper;
    @Autowired
    private PersonnelOrgUtils personnelOrgUtils;

    @Autowired
    private AttendanceUserApi attendanceUserApi;

    @Autowired
    private AttendanceGroupApi attendanceGroupApi;

    @Autowired
    private RosterExportThreadPool rosterExportThreadPool;

    @Autowired
    private AttendanceGroupService attendanceGroupService;
    @Autowired
    private FtbPersonnelsStaffRosterService ftbPersonnelsStaffRosterService;

    @Autowired
    V2OrganizeApi v2OrganizeApi;

    @Autowired
    V2PositionApi v2PositionApi;

    @Autowired
    V2GradesApi v2GradesApi;

    @Autowired
    V2UserApi v2UserApi;

    @Resource
    FtbPersonnelsTurnoverManagementService turnoverManagementService;

    final static String redisTenantIdToCode = "ftb:personnel:tentantIdToCode";
    final static String redisCodeToTenantId = "ftb:personnel:codeToTenantId";
    final static String redisAllCode = "ftb:personnel:allCode";
    final static List<String> excludeExportFields = List.of("contractDetail");


    /**
     * 根据id查询组织信息
     *
     * @param id
     * @return
     */
    public OrganizeEntity queryOrganizeInfo(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<OrganizeGeneralDetailVO> actionResult = v2OrganizeApi.organizeInfoById(null,id);
        if (null == actionResult || ObjectUtil.isNull(actionResult.getData())) {
            return null;
        }
        return covertOrganizeEntity( actionResult.getData());

    }
    private OrganizeEntity covertOrganizeEntity(OrganizeGeneralDetailVO data) {
        if (data == null) {
            return null;
        }
        OrganizeEntity organizeEntity = new OrganizeEntity();
        organizeEntity.setId(data.getId());
        organizeEntity.setFullName(data.getName());
        organizeEntity.setEnCode(data.getEnCode());
        organizeEntity.setParentId(data.getParentId());
        organizeEntity.setOrganizeIdTree(data.getOrganizeIdTree());
        organizeEntity.setOrganizeTreeName(data.getOrganizeTreeName());
        return organizeEntity;
    }

    /**
     * 根据id查询组织信息
     *
     * @param id
     * @return
     */
    public OrganizeEntity queryOrganizeInfoNoToken(String id, String tanentId) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<OrganizeGeneralDetailVO> actionResult = v2OrganizeApi.organizeInfoById(null,id);
        if (null == actionResult || ObjectUtil.isNull(actionResult.getData())) {
            return null;
        }
        return covertOrganizeEntity( actionResult.getData());
    }

    /**
     * 查询岗位
     *
     * @param id
     * @return
     */
    public PositionEntity queryPosition(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<PositionVO> actionResult = v2PositionApi.infoPosition(id);
        if (null == actionResult || ObjectUtil.isNull(actionResult.getData())) {
            return null;
        }
        return covertPositionEntity(actionResult.getData());
    }
    public PositionEntity covertPositionEntity(PositionVO data) {
        if (data == null) {
            return null;
        }
        PositionEntity positionEntity = new PositionEntity();
        positionEntity.setId(data.getId());
        positionEntity.setFullName(data.getFullName());
        positionEntity.setEnCode(data.getEnCode());
        positionEntity.setType(data.getType());
        positionEntity.setDescription(data.getDescription());
        positionEntity.setPositionDescription(data.getPositionDescription());
        positionEntity.setPositionDescriptionUrl(data.getPositionDescriptionUrl());
        return positionEntity;
    }
    /**
     * 查询岗位
     *
     * @param id
     * @return
     */
    public PositionEntity queryPositionNoToken(String id, String tenantId) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<PositionVO> actionResult = v2PositionApi.infoPosition(id);
        if (null == actionResult || ObjectUtil.isNull(actionResult.getData())) {
            return null;
        }
        return covertPositionEntity(actionResult.getData());
    }

    /**
     * 根据职等ID查询职等信息
     *
     * @param id
     * @return
     */
    public PositionGradesInfoVO queryRank(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<GradeVO> gradeVOActionResult = v2GradesApi.infoGrade(id);
        if (gradeVOActionResult != null && gradeVOActionResult.getData() != null) {
            return covertPositionGradesInfoVO( gradeVOActionResult.getData());
        }
        return null;
    }
    public PositionGradesInfoVO covertPositionGradesInfoVO(GradeVO data) {
        if (data == null) {
            return null;
        }
        PositionGradesInfoVO positionGradesInfoVO = new PositionGradesInfoVO();
        positionGradesInfoVO.setId(data.getId());
        positionGradesInfoVO.setFullName(data.getName());
        return positionGradesInfoVO;
    }

    public PositionGradesInfoVO queryRankNoToken(String id, String tenantId) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        ActionResult<GradeVO> gradeVOActionResult = v2GradesApi.infoGrade(id);
        if (gradeVOActionResult != null && gradeVOActionResult.getData() != null) {
            return covertPositionGradesInfoVO( gradeVOActionResult.getData());
        }
        return null;
    }

    public String queryContractTypeName(String id) {
        if (StringUtils.isEmpty(id)) {
            return "";
        }
        if ("1".equals(id)) {
            return "固定期限劳动合同";
        } else if ("2".equals(id)) {
            return "无固定期限劳动合同";
        } else if ("3".equals(id)) {
            return "实习协议";
        } else if ("4".equals(id)) {
            return "劳务协议";
        } else if ("5".equals(id)) {
            return "劳务派遣合同";
        } else if ("6".equals(id)) {
            return "返聘协议";
        } else if ("7".equals(id)) {
            return "短期劳动合同";
        }
        ActionResult<ContractTypeVO> info = contractTypeApi.getInfo(id);
        if (info != null && info.getData() != null) {
            return info.getData().getFullName();
        }
        return "";
    }

    public String queryContractTypeNameNoToken(String id, String tenantId) {
        if (StringUtils.isEmpty(id)) {
            return "";
        }
        if ("1".equals(id)) {
            return "固定期限劳动合同";
        } else if ("2".equals(id)) {
            return "无固定期限劳动合同";
        } else if ("3".equals(id)) {
            return "实习协议";
        } else if ("4".equals(id)) {
            return "劳务协议";
        } else if ("5".equals(id)) {
            return "劳务派遣合同";
        } else if ("6".equals(id)) {
            return "返聘协议";
        } else if ("7".equals(id)) {
            return "短期劳动合同";
        }
        ActionResult<ContractTypeVO> info = contractTypeApi.getInfoNoToken(id, tenantId);
        if (info != null && info.getData() != null) {
            return info.getData().getFullName();
        }
        return "";
    }

    public List<ContractTypeVO> queryContractTypeForIds(List<String> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }

        ActionResult<List<ContractTypeVO>> listInfo = contractTypeApi.getListInfo(ids);
        if (null != listInfo && CollectionUtil.isNotEmpty(listInfo.getData())) {
            return listInfo.getData();
        }
        return new ArrayList<>();
    }

    public StoreEntity queryStoreInfo(String id) {
        StoreEntity entity = storeMapper.getStoreById(id);
        return entity;
    }

    public UserEntity queryUserInfo(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        List<UserEntity> userEntityList = userApi.getUserName(List.of(id));
        if (CollectionUtil.isNotEmpty(userEntityList)) {
            return userEntityList.get(0);
        }
        return null;
    }

    public FtbPersonnelsStaffRoster queryUserInfoLocal(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return ftbPersonnelsStaffRosterService.getById(id);


    }


    public void fillRankName(List<FtbPersonnelsStaffEmploymentApplyDto> records) {
        for (FtbPersonnelsStaffEmploymentApplyDto record : records) {
            try {
                ActionResult<PositionGradesInfoVO> gradesInfo = positionApi.getGradesInfo(record.getCurrRank());
                if (gradesInfo != null && gradesInfo.getData() != null) {
                    record.setCurrRankName(gradesInfo.getData().getFullName());
                }
            } catch (Exception e) {
                log.error("根据职等ID查询职等信息异常,rankId={},{}", record.getCurrRank(), e);
            }
        }
    }

    /**
     * 填充合同类型
     *
     * @param records
     */
    public void fillContractTypeName(List<FtbPersonnelsStaffEmploymentApplyDto> records) {
        for (FtbPersonnelsStaffEmploymentApplyDto record : records) {
            String contractTypeName = queryContractTypeName(record.getContractType());
            record.setContractTypeName(contractTypeName);
        }
    }

    public void fillPositionName(List<FtbPersonnelsStaffEmploymentApplyDto> list) {
        //获取组织id列表
        List<String> ids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getCurrPosition())) {
                ids.add(item.getCurrPosition());
            }
        });

        List<PositionEntity> entityLists = positionApi.getPositionName(ids);
        if (CollectionUtil.isEmpty(entityLists)) {
            return;
        }
        Map<String, PositionEntity> listMap = entityLists.stream().collect(Collectors.toMap(PositionEntity::getId, Function.identity()));
        for (FtbPersonnelsStaffEmploymentApplyDto dto : list) {
            PositionEntity entity = listMap.get(dto.getCurrPosition());
            if (null == entity) {
                continue;
            }
            dto.setCurrPositionName(entity.getFullName());
        }
    }

    public void fillOrgName(List<FtbPersonnelsStaffEmploymentApplyDto> list) {
        //获取组织id列表
        List<String> ids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getCurrOrg())) {
                ids.add(item.getCurrOrg());
            }
        });
        List<OrganizeEntity> entityList = organizeApi.getOrganizeName(ids);
        if (CollectionUtil.isEmpty(entityList)) {
            return;
        }
        Map<String, OrganizeEntity> listMap = entityList.stream().collect(Collectors.toMap(OrganizeEntity::getId, Function.identity()));
        for (FtbPersonnelsStaffEmploymentApplyDto dto : list) {
            OrganizeEntity organizeEntity = listMap.get(dto.getCurrOrg());
            if (null == organizeEntity) {
                continue;
            }
            dto.setCurrOrgName(organizeEntity.getFullName());
        }
    }

    public void fillExpireDayNum(List<FtbPersonnelsStaffEmploymentApplyDto> records) {
        Date now = new Date();
        records.forEach(item -> {
            if (item.getIsNeedCheck() == 1 || (item.getIsNeedCheck() == 0 && item.getCheckStatus() == 2)) {
                if (item.getStatus() == 2) {
                    if (now.after(item.getExpectedStartDate())) {
                        item.setExpireDayNum(DateUtil.betweenDay(item.getExpectedStartDate(), now, false));
                    }
                }
            }

        });
    }


    public void addUserStoreRelation(String userId, String storeId, String orgId, String postionId, String rankId) {
        if (StringUtils.isEmpty(storeId) || StringUtils.isEmpty(orgId)) {
            return;
        }
        QueryWrapper<StoreUserRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(StoreUserRelation::getUserId, userId)
                .eq(StoreUserRelation::getOrganizeId, orgId)
                .eq(StoreUserRelation::getPositionId, postionId)
                .eq(StoreUserRelation::getRankId, rankId)
                .eq(StoreUserRelation::getStoreId, storeId)
                .eq(StoreUserRelation::getDeleteMark, 0);
        List<StoreUserRelation> list = storeUserRelationMapper.selectList(wrapper);

        if (CollectionUtil.isNotEmpty(list)) {
            return;
        }
        StoreUserRelation entity = new StoreUserRelation();
        entity.setStoreId(storeId);
        entity.setUserId(userId);
        entity.setOrganizeId(orgId);
        entity.setPositionId(postionId);
        entity.setRankId(rankId);
        entity.setDeleteMark(0);
        storeUserRelationMapper.insert(entity);

    }

    /**
     * 根据用户ID查询门店信息
     *
     * @param userIds
     * @return
     */
    public List<StoreUserRelationVo> queryStoreManagerForUserId(List<String> userIds) {
        if (CollectionUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        List<StoreUserRelationVo> list = storeUserRelationMapper.queryList(userIds);
        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list;
    }

    public List<List<SubMulitFieldValDto>> parseGroupData(String affiliatedGroupData) {

        Gson gson = new Gson();
        Type type = new TypeToken<List<List<SubMulitFieldValDto>>>() {
        }.getType();
        List<List<SubMulitFieldValDto>> dataList = gson.fromJson(affiliatedGroupData, type);
        return dataList;
    }

    public List<List<FormFieldDto>> buildMulitField(List<FormFieldDto> groupList, String affiliatedGroupData, String userId, String tenantId) {
        if (StringUtils.isEmpty(userId)) {
            return List.of(groupList);
        }
        Map<String, List<WorkerGroupDataDto>> map = getUserOrgBoundInfoForUserListAndTenantId(List.of(userId), tenantId, true);
        List<WorkerGroupDataDto> list = map.get(userId);
        if (CollectionUtil.isEmpty(list)) {
            return List.of(groupList);
        }

        List<List<FormFieldDto>> retList = new ArrayList<>();
        for (WorkerGroupDataDto workerGroupDataDto : list) {
            List<FormFieldDto> newGroupList = new ArrayList<>();
            for (FormFieldDto formFieldDto : groupList) {
                FormFieldDto newFormFieldDto = new FormFieldDto();
                BeanUtil.copyProperties(formFieldDto, newFormFieldDto);
                if ("workerName".equals(newFormFieldDto.getId()) || "phone".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setCurrIsUpdate(false);
                }
                if ("affiliatedOrg".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedOrg());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedOrgName());
                } else if ("affiliatedPosition".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedPosition());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedPositionName());
                } else if ("affiliatedRank".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedRank());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedRankName());
                } else if ("affiliatedShop".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedShop());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedShopName());
                } else if ("affiliatedReportsTo".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getReportsTo());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getReportsToName());
                }
                newGroupList.add(newFormFieldDto);
            }
            retList.add(newGroupList);
        }
        return retList;
    }

    public List<List<FormFieldDto>> buildMulitField(List<FormFieldDto> groupList, String affiliatedGroupData, String userId) {
        if (StringUtils.isEmpty(userId)) {
            return List.of(groupList);
        }
        List<WorkerGroupDataDto> list = getUserOrgBoundInfo(userId);
        if (CollectionUtil.isEmpty(list)) {
            return List.of(groupList);
        }

        List<List<FormFieldDto>> retList = new ArrayList<>();
        for (WorkerGroupDataDto workerGroupDataDto : list) {
            List<FormFieldDto> newGroupList = new ArrayList<>();
            for (FormFieldDto formFieldDto : groupList) {
                FormFieldDto newFormFieldDto = new FormFieldDto();
                BeanUtil.copyProperties(formFieldDto, newFormFieldDto);
                // 是否为主岗
                newFormFieldDto.setIsPrimaryPosition(workerGroupDataDto.getIsPrimaryPosition());
                if ("affiliatedOrg".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedOrg());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedOrgName());
                } else if ("affiliatedPosition".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedPosition());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedPositionName());
                } else if ("affiliatedRank".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedRank());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedRankName());
                } else if ("affiliatedShop".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getAffiliatedShop());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getAffiliatedShopName());
                } else if ("affiliatedReportsTo".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getReportsTo());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getReportsToName());
                } else if ("team".equals(newFormFieldDto.getId())) {
                    newFormFieldDto.setUserValue(workerGroupDataDto.getStoreTeamId());
                    newFormFieldDto.setUserValueLable(workerGroupDataDto.getStoreTeamName());
                }
                newGroupList.add(newFormFieldDto);
            }
            retList.add(newGroupList);
        }
        return retList;
    }


    public UpdateUserDTO convertSynUserBoundDTOList(List<WorkerGroupDataDto> list, String userId) {
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        WorkerGroupDataDto dataDto = list.stream().findFirst().orElse(new WorkerGroupDataDto());
        UpdateUserDTO updateUserDTO = new UpdateUserDTO();
        updateUserDTO.setId(userId);
        UserBoundInfoDTO boundInfoDTO = new UserBoundInfoDTO();
        boundInfoDTO.setOrganizeId(dataDto.getAffiliatedOrg());
        boundInfoDTO.setPositionId(dataDto.getAffiliatedPosition());
        boundInfoDTO.setGradesId(dataDto.getAffiliatedRank());
        boundInfoDTO.setLeaderId(dataDto.getReportsTo());
        boundInfoDTO.setStoreTeamId(dataDto.getStoreTeamId());
        updateUserDTO.setBoundInfoDTO(boundInfoDTO);
        return updateUserDTO;
    }

    public Boolean sysUserBoundList(List<WorkerGroupDataDto> list, String userId) {
        //todo同步组织
        UpdateUserDTO boundInfoDTO = convertSynUserBoundDTOList(list, userId);
        Boolean aBoolean = null;
        try {
            ActionResult<Boolean> actionResult = v2UserApi.updateUserInfo(userId,  boundInfoDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("同步组织岗位等信息异常");
            throw new RuntimeException(e);
        }
        return aBoolean;
    }

    /**
     * 同步角色
     *
     * @param dto
     * @return
     */
    public Boolean sysUserRole(SynUserBoundRoleDTO dto) {
        //同步角色

        Boolean aBoolean = userApi.synchronousUserBoundRole(dto);
        log.error("正常日志，同步角色={},result={}", JSONUtil.toJsonStr(dto), aBoolean);
        return aBoolean;
    }

    /**
     * 根据组织岗位职等获取用户id列表
     *
     * @param orgId
     * @param positionId
     * @param gradesId
     * @return
     */
    public List<String> queryUserIdList(String orgId, String positionId, String gradesId) {
        return userApi.getUserIdsByGradesId(orgId, positionId, gradesId);
    }


    public String getImportWorkerSex(List<FtbRosterInsertAttributesVO> attributesVOList) {
        String workerSex = null;

        if (CollectionUtil.isNotEmpty(attributesVOList)) {
            for (FtbRosterInsertAttributesVO attributesVO : attributesVOList) {
                String formFieldId = attributesVO.getFormFieldId();
                String attributeValue = attributesVO.getAttributeValue();
                if ("workerSex".equals(formFieldId)) {
                    workerSex = attributeValue;
                    break;
                }
            }
        }
        return workerSex;
    }

    public Map<String, String> getImportInfoMap(List<FtbRosterInsertAttributesVO> attributesVOList) {
        Map<String, String> map = new HashMap<>();
        if (CollectionUtil.isNotEmpty(attributesVOList)) {
            for (FtbRosterInsertAttributesVO attributesVO : attributesVOList) {
                String formFieldId = attributesVO.getFormFieldId();
                String attributeValue = attributesVO.getAttributeValue();
                map.put(formFieldId, attributeValue);
            }
        }
        return map;
    }

    public FtbPersonnelsStaffRoster buildImportRoster(FtbRosterInsertNomalVO vo) {
        FtbPersonnelsStaffRoster entity = new FtbPersonnelsStaffRoster();
        entity.setName(vo.getUserName());
        entity.setPhone(vo.getPhone());
        if (StringUtils.isNotEmpty(vo.getEntrySalary())) {
            entity.setEntrySalary(new BigDecimal(vo.getEntrySalary()));
        }
        if (StringUtils.isNotEmpty(vo.getRegularSalary())) {
            entity.setRegularSalary(new BigDecimal(vo.getRegularSalary()));
        }


        List<FtbRosterInsertAttributesVO> attributesVOList = vo.getFtbRosterInsertAttributesVOS();
        String probationPeriod = "";
        if (CollectionUtil.isNotEmpty(attributesVOList)) {
            Map<String, String> importInfoMap = new HashMap<>();
            for (FtbRosterInsertAttributesVO attributesVO : attributesVOList) {
                String formFieldId = attributesVO.getFormFieldId();
                String attributeValue = attributesVO.getAttributeValue();
                importInfoMap.put(formFieldId, attributeValue);
                if ("systemWokerId".equals(formFieldId)) {
                    entity.setSystemWokerId(attributeValue);
                } else if ("systemContractId".equals(formFieldId)) {
                    entity.setSystemContractId(attributeValue);
                } else if ("workerNo".equals(formFieldId)) {
                    entity.setWorkerNo(attributeValue);
                } else if ("currOrg".equals(formFieldId)) {
                    entity.setCurrOrg(attributeValue);
                } else if ("currPosition".equals(formFieldId)) {
                    entity.setCurrPosition(attributeValue);
                } else if ("currRank".equals(formFieldId)) {
                    entity.setCurrRank(attributeValue);
                } else if ("currShopId".equals(formFieldId)) {
                    entity.setCurrShopId(attributeValue);
                } else if ("currReportsTo".equals(formFieldId)) {
                    entity.setCurrReportsTo(attributeValue);
                } else if ("contractNo".equals(formFieldId)) {
                    entity.setContractNo(attributeValue);
                } else if ("contractEffectiveDate".equals(formFieldId)) {
                    entity.setContractEffectiveDate(stringDateToDate(attributeValue));
                } else if ("contractDate".equals(formFieldId)) {
                    entity.setContractEndDate(stringDateToDate(attributeValue));
                } else if ("actualStartDate".equals(formFieldId)) {
                    entity.setActualStartDate(stringDateToDate(attributeValue));
                } else if ("workerType".equals(formFieldId)) {
                    entity.setWorkerType(attributeValue);
                } else if ("contractType".equals(formFieldId)) {
                    entity.setContractType(attributeValue);
                } else if ("workerStatus".equals(formFieldId)) {
                    entity.setWorkerStatus(attributeValue);
                } else if ("actualProbationaryDate".equals(formFieldId)) {
                    entity.setActualProbationaryDate(stringDateToDate(attributeValue));
                } else if ("currRole".equals(formFieldId)) {
                    entity.setCurrRole(attributeValue);
                } else if ("probationPeriod".equals(formFieldId)) {
                    probationPeriod = attributeValue;
                }
            }
            vo.setInnerFieldValueCacheMap(importInfoMap);
        }

        if (StringUtils.isEmpty(probationPeriod)) {
            probationPeriod = "100";
        }
        ProbationPeriodDto probationPeriodDto = new ProbationPeriodDto(probationPeriod, "0");

        if ("302".equals(entity.getWorkerStatus())) {
            entity.setCurrSalary(entity.getEntrySalary());
            if (probationPeriodDto.getType().equals("100")) {
                throw new RuntimeException("姓名：" + entity.getName() + ",手机号：" + entity.getPhone() + ",员工状态是试用,请配置试用期限");
            }
        } else {
            entity.setCurrSalary(entity.getRegularSalary());
        }

        if (null == entity.getCurrSalary()) {
            if (null != entity.getRegularSalary()) {
                entity.setCurrSalary(entity.getRegularSalary());
            } else if (null != entity.getEntrySalary()) {
                entity.setCurrSalary(entity.getEntrySalary());
            }
        }
        return entity;
    }

    /**
     * 从excel中获取指定值
     *
     * @param attributesVOList
     * @param key
     * @return
     */
    public String getValueForExcel(List<FtbRosterInsertAttributesVO> attributesVOList, String key) {
        String value = "";
        if (CollectionUtil.isEmpty(attributesVOList)) {
            return value;
        }
        for (FtbRosterInsertAttributesVO attributesVO : attributesVOList) {
            String formFieldId = attributesVO.getFormFieldId();
            String attributeValue = attributesVO.getAttributeValue();
            if (key.equals(formFieldId)) {
                value = attributeValue;
                break;
            }
        }
        return value;

    }

    public Date convertToLocalDateToDate(LocalDate localDate) {
        // 将LocalDate转换为LocalDateTime，默认时间设置为0点
        LocalDateTime localDateTime = localDate.atStartOfDay();

        // 将LocalDateTime转换为ZonedDateTime，使用系统默认时区
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());

        // 从ZonedDateTime获取Instant对象
        Instant instant = zonedDateTime.toInstant();

        // 使用Instant构造Date对象
        return Date.from(instant);
    }

    public Date stringDateToDate(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        try {
            if (str.contains(":")) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = formatter.parse(str);
                return date;
            } else if (str.contains("/")) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
                Date date = formatter.parse(str);
                return date;
            } else if (str.contains("-")) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date date = formatter.parse(str);
                return date;
            } else {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                Date date = formatter.parse(str);
                return date;
            }
        } catch (ParseException e) {
            log.error("转换日期失败 ={}", str);
        }
        return null;
    }

    public Date stringDateToDateTime(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将字符串转换为Date对象
            Date date = formatter.parse(str);
            return date;
        } catch (ParseException e) {
            log.error("转换日期失败 ={}", str);
        }
        return null;
    }

    public List<StaffRosterSimpleBaseInfoDto> queryUserBaseInfoAndOrgAndPosAndRank(List<String> userIdList, String tenantId) {
        List<UserBoundMoreInfoVO> selectList = userApi.getUserBoundMoreInfosByUserIdsNoToken(userIdList, tenantId);
        if (CollectionUtil.isEmpty(selectList)) {
            return new ArrayList<>();
        }
        List<StaffRosterSimpleBaseInfoDto> retList = new ArrayList<>();
        Map<String, List<UserBoundMoreInfoVO>> map = selectList.stream().collect(Collectors.groupingBy(UserBoundMoreInfoVO::getUserId));
        for (Map.Entry<String, List<UserBoundMoreInfoVO>> entry : map.entrySet()) {
            String userId = entry.getKey(); // 用户ID
            StaffRosterSimpleBaseInfoDto baseInfoDto = new StaffRosterSimpleBaseInfoDto();
            baseInfoDto.setUserId(userId);
            List<UserBoundMoreInfoVO> list = entry.getValue(); // 获取值列表
            List<WorkerGroupDataDto> workerGroupDataDtoList = new ArrayList<>();
            for (UserBoundMoreInfoVO vo : list) {
                WorkerGroupDataDto dto = new WorkerGroupDataDto();
                dto.setReportsToName(vo.getManagerRealName());
                dto.setReportsTo(vo.getManagerId());
                dto.setAffiliatedOrg(vo.getOrganizeId());
                dto.setAffiliatedOrgName(vo.getOrganizeName());
                dto.setAffiliatedPosition(vo.getPositionId());
                dto.setAffiliatedPositionName(vo.getPositionName());
                dto.setAffiliatedRank(vo.getPositionGradesId());
                dto.setAffiliatedRankName(vo.getPositionGradesName());
                dto.setOrgEncode(vo.getOrganizeEnCode());
                dto.setPositionEncode(vo.getPositionEnCode());
                dto.setIsDefaultOrganize(vo.getIsDefaultOrganize());
                dto.setIsDefaultPosition(vo.getIsDefaultPosition());
                workerGroupDataDtoList.add(dto);
            }
            baseInfoDto.setInfoList(workerGroupDataDtoList);
            retList.add(baseInfoDto);
        }
        return retList;
    }

    public Map<String, List<WorkerGroupDataDto>> getUserOrgBoundInfoForUserList(List<String> userIdList) {
        List<UserBoundMoreInfoVO> selectList = userApi.getUserBoundMoreInfosByUserIds(userIdList);
        if (CollectionUtil.isEmpty(selectList)) {
            return new HashMap<>();
        }
        Map<String, List<WorkerGroupDataDto>> retMap = new HashMap<>();
        Map<String, List<UserBoundMoreInfoVO>> map = selectList.stream().collect(Collectors.groupingBy(UserBoundMoreInfoVO::getUserId));
        for (Map.Entry<String, List<UserBoundMoreInfoVO>> entry : map.entrySet()) {
            String userId = entry.getKey(); // 用户ID
            List<UserBoundMoreInfoVO> list = entry.getValue(); // 获取值列表
            List<WorkerGroupDataDto> workerGroupDataDtoList = new ArrayList<>();
            for (UserBoundMoreInfoVO vo : list) {
                WorkerGroupDataDto dto = new WorkerGroupDataDto();
                dto.setReportsToName(vo.getManagerRealName());
                dto.setReportsTo(vo.getManagerId());
                dto.setAffiliatedOrg(vo.getOrganizeId());
                dto.setAffiliatedOrgName(vo.getOrganizeName());
                dto.setAffiliatedPosition(vo.getPositionId());
                dto.setAffiliatedPositionName(vo.getPositionName());
                dto.setAffiliatedRank(vo.getPositionGradesId());
                dto.setAffiliatedRankName(vo.getPositionGradesName());
                dto.setOrgEncode(vo.getOrganizeEnCode());
                dto.setPositionEncode(vo.getPositionEnCode());
//                //补充门店
//                SimpleStoreUserDto simpleStoreUserDto = queryStoreUser(userId, vo.getOrganizeId(), vo.getPositionId(), vo.getPositionGradesId());
//                if (null != simpleStoreUserDto) {
//                    dto.setAffiliatedShop(simpleStoreUserDto.getStoreId());
//                    dto.setAffiliatedShopName(simpleStoreUserDto.getStoreName());
//                }
                workerGroupDataDtoList.add(dto);
            }
            retMap.put(userId, workerGroupDataDtoList);
        }

        return retMap;
    }


    /**
     * @param userIdList
     * @param isSelectShop true-查询门店信息   false-不查询门店信息
     * @return
     */
    public Map<String, List<WorkerGroupDataDto>> getUserOrgBoundInfoForUserList(List<String> userIdList, Boolean isSelectShop) {
        ActionResult<List<UserBoundVO>> actionResult = v2UserApi.getUserPrimaryBoundBatch(userIdList, UserProvider.getUser().getTenantId());
        if (actionResult == null ||  CollectionUtil.isEmpty(actionResult.getData())) {
            return new HashMap<>();
        }
        //补充门店，如果为true表示要查询门店信息
        List<SimpleStoreUserDto> simpleStoreUserDtos;
        if (isSelectShop) {
            HashSet<String> objects = new HashSet<>();
            objects.addAll(userIdList);
            simpleStoreUserDtos = storeUserRelationMapper.querySimpleStoreUserDto(objects);
        } else {
            simpleStoreUserDtos = new ArrayList<>();
        }
        Map<String, List<WorkerGroupDataDto>> retMap = new HashMap<>();
        actionResult.getData().forEach(vo->{
            String userId = vo.getId();
            List<WorkerGroupDataDto> workerGroupDataDtoList = new ArrayList<>();
            WorkerGroupDataDto dto = new WorkerGroupDataDto();
            dto.setReportsToName(vo.getLeaderName());
            dto.setOrganizeCategory(vo.getOrganizeCategory());
            dto.setReportsTo(vo.getLeaderId());
            dto.setAffiliatedOrg(vo.getOrganizeId());
            dto.setAffiliatedOrgName(vo.getOrganizeName());
            dto.setAffiliatedPosition(vo.getPositionId());
            dto.setAffiliatedPositionName(vo.getPositionName());
            dto.setAffiliatedRank(vo.getGradeId());
            dto.setAffiliatedRankName(vo.getGradeName());
            dto.setOrgEncode(vo.getOrganizeEnCode());
            dto.setPositionEncode(vo.getPositionEnCode());
            dto.setStoreTeamId(vo.getStoreTeamId());
            dto.setStoreTeamName(vo.getStoreTeamName());
            if (isSelectShop && CollUtil.isNotEmpty(simpleStoreUserDtos)) {
                SimpleStoreUserDto simpleStoreUserDto = simpleStoreUserDtos.stream()
                        .filter(item -> userId.equals(item.getUserId())).findFirst().orElse(null);
                if (null != simpleStoreUserDto) {
                    dto.setAffiliatedShop(simpleStoreUserDto.getStoreId());
                    dto.setAffiliatedShopName(simpleStoreUserDto.getStoreName());
                }
            }
            workerGroupDataDtoList.add(dto);
            retMap.put(userId, workerGroupDataDtoList);
        });
        return retMap;
    }


    /**
     * @param userIdList
     * @param isSelectShop true-查询门店信息   false-不查询门店信息
     * @return
     */
    public Map<String, List<WorkerGroupDataDto>> getUserOrgBoundInfoForUserListAndTenantId(List<String> userIdList, String tenantId, Boolean isSelectShop) {
        Map<String, List<WorkerGroupDataDto>> retMap = new HashMap<>();
//        List<UserBoundMoreInfoVO> selectList = userApi.getUserBoundMoreInfosByUserIdsNoToken(userIdList, tenantId);
        ActionResult<List<UserBoundVO>> allUserInfoBatch = v2UserApi.getAllUserInfoBatch(userIdList, tenantId);
        List<UserBoundVO> userBoundVOList = allUserInfoBatch.getData();
        if (CollectionUtil.isEmpty(userBoundVOList)) {
            try {
                TenantDataSourceUtil.switchTenant(tenantId);
                List<FtbPersonnelsTurnoverManagementVO> managementVOS = turnoverManagementService.queryTurnoverList(userIdList);
                managementVOS.forEach(v->{
                    retMap.put(v.getUserId(), v.getOrganizationList());
                });
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
            return retMap;
        }
//        Map<String, List<UserBoundMoreInfoVO>> map = selectList.stream().collect(Collectors.groupingBy(UserBoundMoreInfoVO::getUserId));
        Map<String, List<UserBoundVO>> map = userBoundVOList.stream().collect(Collectors.groupingBy(UserBoundVO::getId));
        for (Map.Entry<String, List<UserBoundVO>> entry : map.entrySet()) {
            String userId = entry.getKey(); // 用户ID
            List<UserBoundVO> list = entry.getValue(); // 获取值列表
            List<WorkerGroupDataDto> workerGroupDataDtoList = new ArrayList<>();
            for (UserBoundVO vo : list) {
                WorkerGroupDataDto dto = new WorkerGroupDataDto();
                dto.setIsDefault(true);
//                dto.setReportsToName(vo.getManagerRealName());
                dto.setReportsTo(vo.getLeaderId());
                dto.setAffiliatedOrg(vo.getOrganizeId());
                dto.setAffiliatedOrgName(vo.getOrganizeName());
                dto.setAffiliatedPosition(vo.getPositionId());
                dto.setAffiliatedPositionName(vo.getPositionName());
                dto.setAffiliatedRank(vo.getGradeId());
                dto.setAffiliatedRankName(vo.getGradeName());
                dto.setOrgEncode(vo.getOrganizeEnCode());
                dto.setPositionEncode(vo.getPositionEnCode());
                dto.setIsPrimaryPosition(true);
                //补充门店，如果为true表示要查询门店信息
                if (isSelectShop) {
                    SimpleStoreUserDto simpleStoreUserDto = queryStoreUser(userId, vo.getOrganizeId(), vo.getPositionId(), vo.getGradeId());
                    if (null != simpleStoreUserDto) {
                        dto.setAffiliatedShop(simpleStoreUserDto.getStoreId());
                        dto.setAffiliatedShopName(simpleStoreUserDto.getStoreName());
                    }
                }
                workerGroupDataDtoList.add(dto);
            }
            retMap.put(userId, workerGroupDataDtoList);
        }
        Set<String> associatedDataUserIds = retMap.keySet();
        // 获取userIdList中，没有关联数据的用户id
        List<String> thereIsNoAffiliationUserIds = userIdList.stream().filter(v -> !associatedDataUserIds.contains(v)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(thereIsNoAffiliationUserIds)){
            try {
                TenantDataSourceUtil.switchTenant(tenantId);
                List<FtbPersonnelsTurnoverManagementVO> managementVOS = turnoverManagementService.queryTurnoverList(thereIsNoAffiliationUserIds);
                managementVOS.forEach(v->{
                    retMap.put(v.getUserId(), v.getOrganizationList());
                });
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
        }
        return retMap;
    }

    public List<WorkerGroupDataDto> getUserOrgBoundInfo(String userId,String... tenantIds) {
        if (StringUtils.isEmpty(userId)) {
            return CollectionUtil.newArrayList();
        }
        String tenantId = tenantIds.length > 0 ? tenantIds[0] : null;
        ActionResult<List<UserBoundVO>> actionResult = v2UserApi.getUserPrimaryBoundBatch(List.of(userId), tenantId);
        if (actionResult == null ||  CollectionUtil.isEmpty(actionResult.getData())) {
            FtbPersonnelsTurOrgInfo userOrganizeInfo = turnoverManagementService.getUserOrganizeInfo(userId, null);
            if (ObjectUtil.isNotEmpty(userOrganizeInfo)){
                WorkerGroupDataDto workerGroupDataDto = userOrganizeInfo.getWorkerGroupDataDto();
                return List.of(workerGroupDataDto);
            }
            return CollectionUtil.newArrayList();
        }
        List<WorkerGroupDataDto> retList = new ArrayList<>();
        for (UserBoundVO vo : actionResult.getData()) {
            WorkerGroupDataDto dto = new WorkerGroupDataDto();
            dto.setIsDefault(true);
            dto.setOrganizeCategory(vo.getOrganizeCategory());
            dto.setIsDefaultOrganize(true);
            dto.setReportsToName(vo.getLeaderName());
            dto.setReportsTo(vo.getLeaderId());
            dto.setAffiliatedOrg(vo.getOrganizeId());
            dto.setAffiliatedOrgName(vo.getOrganizeName());
            dto.setAffiliatedPosition(vo.getPositionId());
            dto.setAffiliatedPositionName(vo.getPositionName());
            dto.setAffiliatedRank(vo.getGradeId());
            dto.setAffiliatedRankName(vo.getGradeName());
            dto.setOrgEncode(vo.getOrganizeEnCode());
            dto.setPositionEncode(vo.getPositionEnCode());
            dto.setIsPrimaryPosition(true);
            dto.setStoreTeamId(vo.getStoreTeamId());
            dto.setStoreTeamName(vo.getStoreTeamName());
            //补充门店
            SimpleStoreUserDto simpleStoreUserDto = queryStoreUser(userId, vo.getOrganizeId(), vo.getPositionId(), vo.getGradeId());
            if (null != simpleStoreUserDto) {
                dto.setAffiliatedShop(simpleStoreUserDto.getStoreId());
                dto.setAffiliatedShopName(simpleStoreUserDto.getStoreName());
            }
            retList.add(dto);
        }
        return retList;
    }

    public Map<String, List<WorkerGroupDataDto>> getUserOrgBoundInfo(List<String> userId) {
        ActionResult<List<UserBoundVO>> actionResult = v2UserApi.getUserPrimaryBoundBatch(userId, UserProvider.getUser().getTenantId());
        List<UserBoundVO> data = actionResult.getData();
        Map<String, UserBoundVO> userIdMap = data.stream().collect(Collectors.toMap(UserBoundVO::getId, Function.identity(), (r1, r2) -> r1));
        if (CollectionUtil.isEmpty(userIdMap)) {
            return Maps.newHashMap();
        }
        HashMap<String, List<WorkerGroupDataDto>> map = Maps.newHashMap();
        userId.forEach(str -> {
            if (ObjectUtil.isNotEmpty(userIdMap) && userIdMap.containsKey(str)) {
               UserBoundVO moreInfoVOS = userIdMap.get(str);
                map.put(str, List.of(coverUserBand(moreInfoVOS)));
            }
        });
        return map;
    }

    public WorkerGroupDataDto coverUserBand(UserBoundVO vo) {
        if (null == vo) {
            return null;
        }
        WorkerGroupDataDto dto = new WorkerGroupDataDto();
        dto.setIsDefault(true);
        dto.setOrganizeCategory(vo.getOrganizeCategory());
        dto.setIsDefaultOrganize(true);
        dto.setReportsToName(vo.getLeaderName());
        dto.setReportsTo(vo.getLeaderId());
        dto.setAffiliatedOrg(vo.getOrganizeId());
        dto.setAffiliatedOrgName(vo.getOrganizeName());
        dto.setAffiliatedPosition(vo.getPositionId());
        dto.setAffiliatedPositionName(vo.getPositionName());
        dto.setAffiliatedRank(vo.getGradeId());
        dto.setAffiliatedRankName(vo.getGradeName());
        dto.setOrgEncode(vo.getOrganizeEnCode());
        dto.setPositionEncode(vo.getPositionEnCode());
        dto.setIsPrimaryPosition(true);
        dto.setStoreTeamId(vo.getStoreTeamId());
        dto.setStoreTeamName(vo.getStoreTeamName());
        return dto;
    }

    public SimpleStoreUserDto queryStoreUser(String userId, String orgId, String postionId, String rankId) {
        QueryWrapper<StoreUserRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(StoreUserRelation::getUserId, userId)
                .eq(StoreUserRelation::getOrganizeId, orgId)
                .eq(StoreUserRelation::getPositionId, postionId)
                .eq(StoreUserRelation::getRankId, rankId)
                .eq(StoreUserRelation::getDeleteMark, 0);
        List<StoreUserRelation> list = storeUserRelationMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            StoreUserRelation storeUserRelation = list.get(0);
            StoreEntity entity = storeMapper.getStoreById(storeUserRelation.getStoreId());
            SimpleStoreUserDto dto = new SimpleStoreUserDto();
            dto.setUserId(userId);
            dto.setStoreId(storeUserRelation.getStoreId());
            if (null != dto) {
                dto.setStoreName(entity.getStorename());
            }
            return dto;
        }
        return null;
    }

    /**
     * 设置今日已经发送短信
     *
     * @param phone
     */
    public Boolean setTodayIsSendPhoneMsg(String phone) {
        Date date = new Date(); // 获取当前日期和时间对象
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        String today = formatter.format(date); // 转换为字符串
        String lockKey = "employment:apply:" + today + ":" + phone;
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 1, TimeUnit.DAYS)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 重置今日发送短信
     *
     * @param phone
     */
    public void resetTodaySendPhoneMsg(String phone) {
        Date date = new Date(); // 获取当前日期和时间对象
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        String today = formatter.format(date); // 转换为字符串
        String lockKey = "employment:apply:" + today + ":" + phone;
        redisTemplate.delete(lockKey);
    }

    /**
     * 设置今日已经发送短信
     *
     * @param phone
     * @return false 未发送   true 已经发送
     */
    public Boolean queryIsSendPhoneMsg(String phone) {
        Date date = new Date(); // 获取当前日期和时间对象
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        String today = formatter.format(date); // 转换为字符串
        String lockKey = "employment:apply:" + today + ":" + phone;
        String val = (String) redisTemplate.opsForValue().get(lockKey);
        if (StringUtils.isNotEmpty(val)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 通过租户ID 查询code
     *
     * @param tenantId
     * @return
     */
    public String queryCodeForTenantId(String tenantId) {
        String tenantIdToCode = redisTenantIdToCode + ":" + tenantId;
        String val = (String) redisTemplate.opsForValue().get(tenantIdToCode);
        if (StringUtils.isNotEmpty(val)) {
            return val;
        }
        String storeCode = randCode();
        while (true) {
            if (redisTemplate.opsForSet().isMember(redisAllCode, storeCode)) {
                storeCode = randCode();
                continue;
            }
            redisTemplate.opsForSet().add(redisAllCode, storeCode);
            break;
        }
        redisTemplate.opsForValue().set(tenantIdToCode, storeCode);
        String codeToTenantId = redisCodeToTenantId + ":" + storeCode;
        redisTemplate.opsForValue().set(codeToTenantId, tenantId);
        return storeCode;
    }

    /**
     * 通过code 查询租户ID
     *
     * @param storeCode
     * @return
     */
    public String queryTenantIdForCode(String storeCode) {

        String codeToTenantId = redisCodeToTenantId + ":" + storeCode;
        String tenantId = (String) redisTemplate.opsForValue().get(codeToTenantId);
        return tenantId;
    }

    private String randCode() {
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数
        return String.valueOf(randomNumber);
    }

    public String getPhoneFormInput(List<SubFormFieldDto> fieldValueList) {
        String phone = "";
        if (CollectionUtil.isNotEmpty(fieldValueList)) {
            for (SubFormFieldDto dto : fieldValueList) {
                if (dto.getId().equals("phone")) {
                    phone = dto.getUserValue();
                    break;
                }
            }
        }
        return phone;
    }


    public Map<String, FtbPersonnelsStaffRegistrationFormData> convertFormValueMap(List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList) {
        Map<String, FtbPersonnelsStaffRegistrationFormData> map = new HashMap<>();
        if (CollectionUtil.isEmpty(formFieldValueList)) {
            return map;
        }
        for (FtbPersonnelsStaffRegistrationFormData vo : formFieldValueList) {
            map.put(vo.getFormFieldId(), vo);
        }
        return map;
    }

    public String getPhoneFormInputForField(List<SubFormFieldDto> fieldValueList, String field) {
        String value = "";
        if (CollectionUtil.isNotEmpty(fieldValueList)) {
            for (SubFormFieldDto dto : fieldValueList) {
                if (dto.getId().equals(field)) {
                    value = dto.getUserValue();
                    break;
                }
            }
        }
        return value;
    }

    /**
     * 获取一个字段的值
     *
     * @param map
     * @return
     */
    public String getFormDataForField(Map<String, FtbPersonnelsStaffRegistrationFormData> map, String fieldId) {
        if (CollectionUtil.isEmpty(map)) {
            return "";
        }
        FtbPersonnelsStaffRegistrationFormData ftbPersonnelsStaffRegistrationFormData = map.get(fieldId);
        if (null != ftbPersonnelsStaffRegistrationFormData) {
            return ftbPersonnelsStaffRegistrationFormData.getValue();
        }
        return "";
    }

    /**
     * @param dto
     * @param formDataList
     * @param isNeedQueryRole 是否需要查询角色  true 需要，false不需要
     */
    public void fillRosterDtoData(FtbPersonnelsStaffRosterDto dto, List<FtbPersonnelsStaffRegistrationFormData> formDataList, Boolean isNeedQueryRole) {
        if (CollectionUtil.isEmpty(formDataList)) {
            return;
        }
        Date now = new Date();
        for (FtbPersonnelsStaffRegistrationFormData formData : formDataList) {
            if (StringUtils.isEmpty(formData.getValue())) {
                continue;
            } else if (formData.getFormFieldId().equals("headLogo")) {
                List<String> headListLogo = personnelOrgUtils.parseHeadLogo(formData.getValue());
                if (CollectionUtil.isNotEmpty(headListLogo)) {
                    dto.setHeadLogo(headListLogo.get(0));
                }
            } else if (formData.getFormFieldId().equals("idCardNum")) {
                dto.setIdCardNum(formData.getValue());
            } else if (formData.getFormFieldId().equals("workerSex")) {
                dto.setWorkerSexName(PersonnelStaffUtils.convertSexName(formData.getValue()));
            } else if (formData.getFormFieldId().equals("flowerName")) {
                dto.setFlowerName(formData.getValue());
            } else if (formData.getFormFieldId().equals("birthday")) {
                dto.setBirthday(formData.getValue());
            } else if (formData.getFormFieldId().equals("age")) {
                dto.setAge(formData.getValue());
            } else if (formData.getFormFieldId().equals("companyAge")) {
                dto.setCompanyAge(formData.getValue());
            } else if (formData.getFormFieldId().equals("probationPeriod")) {
                if (StringUtils.isNotEmpty(formData.getValue()) && formData.getValue().startsWith("{")) {
                    ProbationPeriodDto bean = JSONUtil.toBean(formData.getValue(), ProbationPeriodDto.class);
                    dto.setProbationPeriod(bean.getType());
                    dto.setProbationPeriodDay(bean.getDays());
                    if (dto.getProbationPeriod().equals("100") && dto.getIsTrialJob() != null && dto.getIsTrialJob().equals(1)) {
                        dto.setWorkerStatusFormal(1);
                    }
                }
            } else if (formData.getFormFieldId().equals("planProbationaryDate")) {
                dto.setPlanProbationaryDate((DateUtil.parse(formData.getValue(), "yyyy-MM-dd")));
            } else if (formData.getFormFieldId().equals("contractTaskId")) {
                dto.setContractTaskId(formData.getValue());
            }
        }
        if (null != dto.getActualStartDate()) {
            if (!"305".equals(dto.getWorkerStatus())) {
                dto.setCompanyAge(String.valueOf(DateUtil.between(dto.getActualStartDate(), now, DateUnit.DAY)));
            }
            String s = calculateSeniorityForDate(dto.getActualStartDate().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate());
            dto.setSiLing(s);
        } else {
            dto.setSiLing(calculateSeniority("0天"));
            dto.setCompanyAge("0");
        }
        /**
         * 查询用户的角色
         */
        if (isNeedQueryRole) {
            List<SaffRoleDto> saffRoleDtos = queryRoleListForUserId(dto.getUserId());
            dto.setUserRoleList(saffRoleDtos);
        }
    }

    public String getInputHeadLogo(String headLogo) {
        if (StringUtils.isEmpty(headLogo) || "[]".equals(headLogo)) {
            return "";
        } else {
            List<String> headList = JSONUtil.toList(headLogo, String.class);
            if (CollectionUtil.isNotEmpty(headList)) {
                headLogo = headList.get(0);
            } else {
                headLogo = "";
            }
        }
        return headLogo;
    }

    public List<String> parseHeadLogo(String headLogo) {
        if (StringUtils.isEmpty(headLogo) || "[]".equals(headLogo)) {
            return new ArrayList<>();
        }
        List<String> headList = JSONUtil.toList(headLogo, String.class);
        if (CollectionUtil.isEmpty(headList)) {
            return new ArrayList<>();
        }
        ArrayList<String> list = new ArrayList<>();
        for (String head : headList) {
            if(head.startsWith("http")){
                list.add(head);
            }else if (!head.startsWith("/api")) {
                list.add(UploaderUtil.uploaderImg(head));
            } else {
                list.add(head);
            }
        }
        return list;
    }

    public String convertHeadLogo(String headLogo) {
        if (StringUtils.isEmpty(headLogo) || "[]".equals(headLogo)) {
            return "";
        }
        List<String> headList = JSONUtil.toList(headLogo, String.class);
        if (CollectionUtil.isEmpty(headList)) {
            return "";
        }
        ArrayList<String> list = new ArrayList<>();
        for (String head : headList) {
            if(head.startsWith("http")){
                list.add(head);
            }else if (!head.startsWith("/api")) {
                list.add(UploaderUtil.uploaderImg(head));
            } else {
                list.add(head);
            }
        }
        return list.get(0);
    }

    /**
     * 计算员工从入职日期到现在的司龄（以年、月、天为单位）
     *
     * @return 司龄字符串，格式如 "x年x月x天"
     */
    public String calculateSeniority(String days) {
        if (StringUtils.isEmpty(days) || "0".equals(days)) {
            return "0天";
        }
        try {
            Integer totalDays = Integer.valueOf(days);
            return formatDaysToYearMonthDay(totalDays);
        } catch (Exception e) {
            return "0天";
        }
    }

    public String calculateSeniorityForDate(LocalDate startDate) {
        LocalDate currentDate = LocalDate.now(); // 获取当前日期
        Period period = Period.between(startDate, currentDate); // 计算两个日期之间的差值
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        if (years == 0 && months == 0 && days == 0) {
            return "0天";
        } else if (years == 0 && months == 0 && days != 0) {
            return String.format("%d天", days);
        } else if (years == 0 && months != 0 && days != 0) {
            return String.format("%d月%d天", months, days);
        } else {
            return String.format("%d年%d月%d天", years, months, days);
        }

    }

    public String formatDaysToYearMonthDay(int days) {
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = startDate.plusDays(days);
        long years = ChronoUnit.YEARS.between(startDate, endDate);
        long months = ChronoUnit.MONTHS.between(startDate, endDate);
        long remainingDays = ChronoUnit.DAYS.between(startDate.plusYears(years).plusMonths(months), endDate);
        return years + "年" + months + "月" + remainingDays + "天";
    }

    public Integer convertAccountStatus(String workerStatus) {
        //1.全职-转正、2.全职-试用、3.在校实习、4.企业见习、 5.兼职
        if ("302".equals(workerStatus)) {
            return 2;
        } else if ("303".equals(workerStatus)) {
            return 1;
        }
        return 0;
    }

    public String dateToString(Date date, String parrseFormat) {
        if (null == date) {
            return "";
        }
        if (StringUtils.isEmpty(parrseFormat)) {
            parrseFormat = "yyyy-MM-dd";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(parrseFormat);
        return formatter.format(date);
    }

    public void fillRoster(FtbPersonnelsStaffRoster updateEntity, SubFormFieldDto subFormFieldDto) {
        String userValue = subFormFieldDto.getUserValue();

        if ("workerName".equals(subFormFieldDto.getId())) {
            updateEntity.setName(userValue);
        } else if ("workerNo".equals(subFormFieldDto.getId())) {
            updateEntity.setWorkerNo(userValue);
        } else if ("currOrg".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrOrg(userValue);
        } else if ("currPosition".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrPosition(userValue);
        } else if ("currRank".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrRank(userValue);
        } else if ("currShopId".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrShopId(userValue);
        } else if ("entrySalary".equals(subFormFieldDto.getId())) {
            updateEntity.setEntrySalary(new BigDecimal(userValue));
        } else if ("currReportsTo".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrReportsTo(userValue);
        } else if ("contractEffectiveDate".equals(subFormFieldDto.getId()) && !StringUtils.isEmpty(userValue)) {
            updateEntity.setContractEffectiveDate(DateUtil.parse(userValue, "yyyy-MM-dd"));
        } else if ("actualProbationaryDate".equals(subFormFieldDto.getId()) && !StringUtils.isEmpty(userValue)) {
            updateEntity.setActualProbationaryDate(DateUtil.parse(userValue, "yyyy-MM-dd"));
        } else if ("contractEndDate".equals(subFormFieldDto.getId()) && !StringUtils.isEmpty(userValue)) {
            updateEntity.setContractEndDate(DateUtil.parse(userValue, "yyyy-MM-dd"));
        } else if ("workerType".equals(subFormFieldDto.getId())) {
            updateEntity.setWorkerType(userValue);
        } else if ("contractType".equals(subFormFieldDto.getId())) {
            updateEntity.setContractType(userValue);
        } else if ("workerStatus".equals(subFormFieldDto.getId())) {
            updateEntity.setWorkerStatus(userValue);
        } else if ("currRole".equals(subFormFieldDto.getId())) {
            updateEntity.setCurrRole(userValue);
        } else if ("actualStartDate".equals(subFormFieldDto.getId()) && !StringUtils.isEmpty(userValue)) {
            updateEntity.setActualStartDate(DateUtil.parse(userValue, "yyyy-MM-dd"));
        }

    }

    /**
     * 查询用户角色
     *
     * @param userId
     * @return
     */
    public List<SaffRoleDto> queryRoleListForUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new ArrayList<>();
        }
        List<RoleEntity> roleList = roleApi.getByUserId(userId);
        if (CollectionUtil.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return BeanUtil.copyToList(roleList, SaffRoleDto.class);
    }

    /**
     * 查询用户角色
     *
     * @param userId
     * @return
     */
    public List<SaffRoleDto> queryRoleListForUserIdNoToken(String userId, String tenantId) {
        if (StringUtils.isEmpty(userId)) {
            return new ArrayList<>();
        }
        List<RoleEntity> roleList = roleApi.getByUserIdNoToken(userId, tenantId);
        if (CollectionUtil.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return BeanUtil.copyToList(roleList, SaffRoleDto.class);
    }

    public Map<String, List<RoleListVO>> queryRoleListForUserIds(List<String> userIds) {
        if (CollectionUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }
        ActionResult<List<UserBoundRolesVO>> listActionResult = roleApi.listUsersBound(userIds);
        if (listActionResult == null || CollectionUtil.isEmpty(listActionResult.getData())) {
            return new HashMap<>();
        }

        return listActionResult.getData()
                .stream()
                .collect(Collectors.toMap(UserBasicVO::getId, UserBoundRolesVO::getRoleBounds, (o1, o2) -> o1));
    }


    /**
     * 查询角色信息
     *
     * @param id
     * @return
     */
    public RoleEntity queryRoleInfoForId(String id) {
        RoleEntity roleEntity = roleApi.getInfoById(id);
        return roleEntity;
    }

    /**
     * 同步状态到内推池
     *
     * @param phone
     * @param status
     */
    public void sysWorkerStatusToUchisuike(String phone, String status) {
        ftbPersonnelsUchisuikePondService.updateWorkStatus(status, phone);
    }

    public Map<String, String> getOrgNames(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Maps.newHashMap();
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        List<OrganizeEntity> organizeName = organizeApi.getOrganizeName(ids);
        return CollUtil.isEmpty(organizeName) ? Maps.newHashMap() :
                organizeName.stream()
                        .collect(Collectors.toMap(OrganizeEntity::getId,
                                OrganizeEntity::getFullName,
                                (a, b) -> a));
    }

    public Map<String, String> getPostNames(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Maps.newHashMap();
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        List<PositionEntity> positionEntities = positionApi.getPositionName(ids);
        return CollUtil.isEmpty(positionEntities) ? Maps.newHashMap() :
                positionEntities.stream()
                        .collect(Collectors.toMap(PositionEntity::getId,
                                PositionEntity::getFullName,
                                (a, b) -> a));
    }

    public Map<String, String> getGradesNames(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Maps.newHashMap();
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        List<BasePositionGradesEntity> gradesEntityList = positionApi.getGradesEntityList(ids);
        return CollUtil.isEmpty(gradesEntityList) ? Maps.newHashMap() :
                gradesEntityList.stream()
                        .collect(Collectors.toMap(BasePositionGradesEntity::getId,
                                BasePositionGradesEntity::getFullName,
                                (a, b) -> a));
    }

    public Map<String, String> getRoleNames(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Maps.newHashMap();
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        List<RoleEntity> listByIds = roleApi.getListByIds(ids);
        return CollUtil.isEmpty(listByIds) ? Maps.newHashMap() :
                listByIds.stream()
                        .collect(Collectors.toMap(RoleEntity::getId,
                                RoleEntity::getFullName,
                                (a, b) -> a));
    }

    public Map<String, String> getUserNames(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Maps.newHashMap();
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        List<UserEntity> userName = userApi.getUserName(ids);
        return CollUtil.isEmpty(userName) ? Maps.newHashMap() :
                userName.stream()
                        .collect(Collectors.toMap(UserEntity::getId,
                                UserEntity::getRealName,
                                (a, b) -> a));
    }

    public void fillOtherInfoForItem(TransferPositionDto info) {
        OrganizeEntity organizeEntity = queryOrganizeInfo(info.getFromOrg());
        if (null != organizeEntity) {
            info.setFromOrgName(organizeEntity.getFullName());
        }
        organizeEntity = queryOrganizeInfo(info.getToOrg());
        if (null != organizeEntity) {
            info.setToOrgName(organizeEntity.getFullName());
        }

        PositionEntity positionEntity = queryPosition(info.getFromPositionId());
        if (null != positionEntity) {
            info.setFromPositionIdName(positionEntity.getFullName());
        }
        positionEntity = queryPosition(info.getToPositionId());
        if (null != positionEntity) {
            info.setToPositionIdName(positionEntity.getFullName());
        }

        PositionGradesInfoVO rankVo = queryRank(info.getFromRankId());
        if (null != rankVo) {
            info.setFromRankIdName(rankVo.getFullName());
        }
        rankVo = queryRank(info.getToRankId());
        if (null != rankVo) {
            info.setToRankIdName(rankVo.getFullName());
        }
        List<RoleEntity> roleEntities = queryRoleListForIds(info.getToRole());

        if (CollectionUtil.isNotEmpty(roleEntities)) {
            List<String> roleNames = roleEntities.stream()
                    .filter(Objects::nonNull)
                    .map(RoleEntity::getFullName)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            info.setToRoleName(String.join(",", roleNames));
        }

        UserEntity userEntity = queryUserInfo(info.getToManager());
        if (null != userEntity) {
            info.setToManagerName(userEntity.getRealName());
        }
        userEntity = queryUserInfo(info.getFromManager());
        if (null != userEntity) {
            info.setFromManagerName(userEntity.getRealName());
        }
    }

    private List<RoleEntity> queryRoleListForIds(String toRole) {
        if (StringUtils.isEmpty(toRole)) {
            return new ArrayList<>();
        }
        List<String> list = Arrays.asList(toRole.split(","));
        return roleApi.getListByIds(list);
    }

    /**
     * 检测手机号是否正确
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }
        Pattern pattern = Pattern.compile(RegexPool.MOBILE);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    /**
     * 变更组织岗位职等 直属主管
     * 把旧的 ->新的
     *
     * @param updateUserManagerBoundDTO
     */

    public void updateSysUserBound(UpdateUserManagerBoundDTO updateUserManagerBoundDTO) {
        try {
            Boolean aBoolean = userApi.UserManagerBoundChange(List.of(updateUserManagerBoundDTO));
            log.error("正常日志，updateSysUserBound req={},result={}", JSONUtil.toJsonStr(updateUserManagerBoundDTO), aBoolean);
            if (aBoolean == false) {
                throw new RuntimeException("调整用户组织架构信息失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("调整用户组织架构信息失败");
        }
    }

    public List<List<ExportRosterOneVo>> groupByBatch(List<ExportRosterOneVo> rosterDataList) {
        List<List<ExportRosterOneVo>> groupedData = new ArrayList<>();
        int batchSize = 100;

        for (int i = 0; i < rosterDataList.size(); i += batchSize) {
            int end = Math.min(i + batchSize, rosterDataList.size());
            groupedData.add(new ArrayList<>(rosterDataList.subList(i, end)));
        }

        return groupedData;
    }

    public List<FtbRosterImportTemplateBO> convertToFtbRosterImportTemplateBO(List<ExportFormTypeDto> fieldList,
                                                                              List<FtbPersonnelsRegistrationFormFieldOption> optionList,
                                                                              List<ExportRosterOneVo> rosterDataList) {
        if (CollectionUtil.isEmpty(rosterDataList)) {
            return new ArrayList<>();
        }
        for (ExportFormTypeDto field : fieldList) {
            List<ExportFormFieldDto> fieldDtoList = field.getFieldDtoList();
            if (CollectionUtil.isEmpty(fieldDtoList)) {
                continue;
            }
            List<ExportFormFieldDto> newField = new ArrayList<>();
            for (ExportFormFieldDto dto : fieldDtoList) {
                if (!excludeExportFields.contains(dto.getId())) {
                    newField.add(dto);
                }
            }
            field.setFieldDtoList(newField);
        }

        //分组
        List<List<ExportRosterOneVo>> allList = groupByBatch(rosterDataList);
        // 主线程中获取
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        UserInfo userInfo = UserProvider.getUser();
        String tenantId = userInfo.getTenantId();
        String token = userInfo.getToken();
        Map<String, String> headers = ImmutableMap.of(Constants.AUTHORIZATION.toLowerCase(), token);
        //多线程调用 convertToFtbRosterImportTemplateBatch 这个方法
        List<CompletableFuture<List<FtbRosterImportTemplateBO>>> futures = allList.stream()
                .map(rosterData -> CompletableFuture.supplyAsync(() -> {
                    try {
                        return convertToFtbRosterImportTemplateBatch(fieldList, optionList, rosterData, requestAttributes, tenantId, headers);
                    } finally {
                        FeignHolder.clear();
                    }
                }, rosterExportThreadPool.getExecutor()))
                .collect(Collectors.toList());
        //搜集结果并返回
        return futures.stream()
                .map(CompletableFuture::join)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
    }

    public List<FtbRosterImportTemplateBO> convertToFtbRosterImportTemplateBatch(List<ExportFormTypeDto> allFields, List<FtbPersonnelsRegistrationFormFieldOption> optionList, List<ExportRosterOneVo> rosterDataList, RequestAttributes requestAttributes, String tenantCode, Map<String, String> headers) {
        log.info("requestAttr={},tenantId={}", JSONUtil.toJsonStr(requestAttributes), tenantCode);
        FeignHolder.set(headers);
        try {
            TenantDataSourceUtil.switchTenant(tenantCode);
        } catch (LoginException e) {
            throw new RuntimeException(e);
        } finally {
            FeignHolder.clear();
        }
        List<String> userIds = rosterDataList.stream()
                .map(a -> a.getRoster().getUserId())
                .collect(Collectors.toList());

        List<AttendanceUserGroupVo> attendanceUserGroup = attendanceGroupService.getAttendanceUserGroup(userIds);
        Map<String, AttendanceUserGroupVo> attendanceUserGroupVoMap = attendanceUserGroup.stream()
                .collect(Collectors.toMap(AttendanceUserGroupVo::getUserId, Function.identity(), (a, b) -> a));

        Map<String, List<RoleListVO>> roleDtoMap = queryRoleListForUserIds(userIds);
        Map<String, List<WorkerGroupDataDto>> workerGroupDataDtoMap = getUserOrgBoundInfoForUserList(userIds, true);
        Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap = optionList.stream()
                .collect(Collectors.toMap(FtbPersonnelsRegistrationFormFieldOption::getId, Function.identity(), (a, b) -> a));
        //构建表头
        Map<String, String> contactNameMap = new HashMap<>();//合同ID 到合同名称 缓存
        List<FtbRosterImportTemplateBO> list = new ArrayList<>();
        for (ExportFormTypeDto formType : allFields) {
            FtbRosterImportTemplateBO bo = new FtbRosterImportTemplateBO();
            list.add(bo);
            //header头
            List<List<String>> header = new ArrayList<>();
            header.add(List.of("姓名"));
            header.add(List.of("手机号"));
            List<ExportFormFieldDto> fieldList = formType.getFieldDtoList();
            for (ExportFormFieldDto field : fieldList) {
                if ("phone".equals(field.getId()) || "workerName".equals(field.getId())) {
                    continue;
                }
                if (StringUtils.isNotEmpty(field.getGroupName())) {
                    continue;
                }
                if ("currOrg".equals(field.getId())) {
                    header.add(List.of("组织、岗位、职等、直属主管、门店"));
                } else if ("currPosition".equals(field.getId())) {
                    // header.add(List.of("所属岗位"));
                } else if ("currRank".equals(field.getId())) {
                    //  header.add(List.of("所属职等"));
                } else if ("currReportsTo".equals(field.getId())) {
                    //   header.add(List.of("直属主管"));
                } else if ("currShopId".equals(field.getId())) {
                    //   header.add(List.of("直属主管"));
                } else {
                    header.add(List.of(field.getName()));
                }
            }
            bo.setHeader(header);
            //sheetName
            bo.setSheetName(formType.getName());
            //构建数据
            List<List<Object>> data = new ArrayList<>();

            for (ExportRosterOneVo exportRosterOneVo : rosterDataList) {
                FtbPersonnelsStaffRoster roster = exportRosterOneVo.getRoster();
                List<FtbPersonnelsStaffRegistrationFormData> formValueList = exportRosterOneVo.getFormValue();
                //查询用户
                List<WorkerGroupDataDto> workerGroupDataDtoList = workerGroupDataDtoMap.get(roster.getUserId());
                //查询角色
                List<RoleListVO> roleDtoList = roleDtoMap.get(roster.getUserId());
                Map<String, FtbPersonnelsStaffRegistrationFormData> valueMap = convertFormValueMap(formValueList);
                List<Object> exportDataList = new ArrayList<>();
                exportDataList.add(roster.getName());
                exportDataList.add(roster.getPhone());
                for (ExportFormFieldDto field : fieldList) {
                    String showValue = "";
                    if ("phone".equals(field.getId()) || "workerName".equals(field.getId())) {
                        continue;
                    }
                    if (StringUtils.isNotEmpty(field.getGroupName())) {
                        continue;
                    }
                    if ("currRole".equals(field.getId())) {
                        if (CollectionUtil.isNotEmpty(roleDtoList)) {
                            List<String> tmpString = new ArrayList<>();
                            for (RoleListVO saffRoleDto : roleDtoList) {
                                try {
                                    Field declaredField = RoleListVO.class.getDeclaredField("fullName");
                                    declaredField.setAccessible(true);
                                    String fullName =(String) declaredField.get(saffRoleDto);
                                    tmpString.add(fullName);
                                } catch (NoSuchFieldException | IllegalAccessException e ) {
                                    throw new RuntimeException(e);
                                }
                            }
                            showValue = String.join(", ", tmpString);
                        }
                        exportDataList.add(showValue);
                        continue;
                    } else if ("currOrg".equals(field.getId())) {
                        if (CollectionUtil.isNotEmpty(workerGroupDataDtoList)) {
                            List<String> tmpString = new ArrayList<>();
                            for (int i = 0; i < workerGroupDataDtoList.size(); i++) {
                                WorkerGroupDataDto workerGroupDataDto = workerGroupDataDtoList.get(i);
                                StringBuilder sb = new StringBuilder();
                                sb.append("[");
                                if (StringUtils.isNotEmpty(workerGroupDataDto.getAffiliatedOrgName())) {
                                    sb.append(workerGroupDataDto.getAffiliatedOrgName());
                                }

                                if (StringUtils.isNotEmpty(workerGroupDataDto.getAffiliatedPositionName())) {
                                    sb.append("、");
                                    sb.append(workerGroupDataDto.getAffiliatedPositionName());
                                }

                                if (StringUtils.isNotEmpty(workerGroupDataDto.getAffiliatedRankName())) {
                                    sb.append("、");
                                    sb.append(workerGroupDataDto.getAffiliatedRankName());
                                }


                                if (StringUtils.isNotEmpty(workerGroupDataDto.getReportsToName())) {
                                    sb.append("、");
                                    sb.append(workerGroupDataDto.getReportsToName());
                                }

                                if (StringUtils.isNotEmpty(workerGroupDataDto.getAffiliatedShopName())) {
                                    sb.append("、");
                                    sb.append(workerGroupDataDto.getAffiliatedShopName());
                                }
                                sb.append("]");
                                tmpString.add(sb.toString());
                            }
                            showValue = String.join("\r\n", tmpString);
                        }
                        exportDataList.add(showValue);
                        continue;
                    } else if ("currPosition".equals(field.getId())) {
                        continue;
                    } else if ("currRank".equals(field.getId())) {
                        continue;
                    } else if ("currReportsTo".equals(field.getId())) {
                        continue;
                    } else if ("currShopId".equals(field.getId())) {
                        continue;
                    }

                    FtbPersonnelsStaffRegistrationFormData formFieldValue = valueMap.get(field.getId());
                    FtbPersonnelsRegistrationFormFieldOption optionEntity = null;
                    if (null != formFieldValue) {
                        if (field.getType() == 2 || field.getType() == 3) {

                            if (StringUtils.isNotEmpty(formFieldValue.getValue())) {
                                if ("probationPeriod".equals(field.getId()) && formFieldValue.getValue().startsWith("{")) {
                                    ProbationPeriodDto bean = JSONUtil.toBean(formFieldValue.getValue(), ProbationPeriodDto.class);
                                    String key = bean.getType();
                                    if ("101".equals(key)) {
                                        showValue = bean.getDays() + "天";
                                    } else {
                                        optionEntity = optionMap.get(key);
                                        if (null != optionEntity) {
                                            showValue = optionEntity.getName();
                                        }
                                    }
                                } else if ("contractType".equals(field.getId())) {

                                    String contactName = contactNameMap.get(formFieldValue.getValue());
                                    if (StringUtils.isNotEmpty(contactName)) {
                                        showValue = contactName;
                                    } else {
                                        String contractTypeName = queryContractTypeName(formFieldValue.getValue());
                                        showValue = contractTypeName;
                                        contactNameMap.put(formFieldValue.getValue(), contractTypeName);
                                    }

                                } else if ("attendanceGroup".equals(field.getId())) {
                                    AttendanceUserGroupVo attendanceUserGroupVo = attendanceUserGroupVoMap.get(roster.getUserId());
                                    if (attendanceUserGroupVo != null) {
                                        showValue = attendanceUserGroupVo.getGroupName();
                                    }
                                } else {
                                    if (field.getType() == 3) {
                                        showValue = Stream.of(formFieldValue.getValue().split(","))
                                                .map(optionMap::get)
                                                .filter(Objects::nonNull)
                                                .map(FtbPersonnelsRegistrationFormFieldOption::getName)
                                                .collect(Collectors.joining(","));

                                    } else {
                                        optionEntity = optionMap.get(formFieldValue.getValue());
                                        if (null != optionEntity) {
                                            showValue = optionEntity.getName();
                                        }
                                    }
                                }
                            }
                        } else {
                            if ("workAddress".equals(field.getId())) {
                                if (formFieldValue.getValue().startsWith("{")) {
                                    WorkAddressDto bean = JSONUtil.toBean(formFieldValue.getValue(), WorkAddressDto.class);
                                    showValue = bean.getAddress();
                                }
                            } else {
                                showValue = formFieldValue.getValue();
                            }
                        }
                    }
                    if (PersonnelFormDataSystemRosterFields.CONTRACT_STATUS.getId().equals(field.getId())) {

                        if (formFieldValue != null && StringUtils.isNotEmpty(formFieldValue.getValue())) {
                            optionEntity = optionMap.get(formFieldValue.getValue());
                            if (null != optionEntity) {
                                showValue = optionEntity.getName();
                            }
                        } else {
                            optionEntity = optionMap.get(roster.getContractStatus().toString());
                            if (null != optionEntity) {
                                showValue = optionEntity.getName();
                            }
                        }
                    }
                    exportDataList.add(showValue);

                }
                data.add(exportDataList);
            }
            bo.setData(data);
        }
        return list;
    }

    /**
     * 删除租户用户
     *
     * @param userId
     */

    public void deleteTenantUser(String userId) {
        v2UserApi.removeUser(userId, null);
    }

    /**
     * 根据手机号查询账号
     *
     * @param account
     * @param phone
     * @return
     */
    public UserInfoVO queryTenantAccount(String account, String phone) {
        UserInfoVO info = userApi.getUserInfoByAccount(account, phone);
        return info;
    }

    /**
     * 检测用户是不是直属主管
     *
     * @param userId
     * @return true 是，  false 不是，
     */
    public Boolean checkUserIsManager(String userId) {
        return userApi.checkUserIsManager(userId);
    }

    /**
     * 查询是否是门店负责人
     *
     * @return
     */
    public Boolean queryShopManager(String userId) {
        LambdaQueryWrapper<StoreEntity> queryWrapper = Wrappers.lambdaQuery();
        //queryWrapper.eq(StoreEntity::getDisabled,0);
        queryWrapper.eq(StoreEntity::isDeletemark,0);
        queryWrapper.eq(StoreEntity::getStoreheaduserid,userId);
        List<StoreEntity> entities = storeMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(entities)) {
            return true;
        }
        return false;
    }

    public <T extends StaffBaseInfoDto> void fillRankNameById(T dto) {
        ActionResult<PositionGradesInfoVO> gradesInfo = null;
        try {
            gradesInfo = positionApi.getGradesInfo(dto.getCurrRank());
            if (gradesInfo != null && gradesInfo.getData() != null) {
                dto.setCurrRankName(gradesInfo.getData().getFullName());
            }
        } catch (Exception e) {
            log.error("根据职等ID查询职等信息异常,rankId={},{}", dto.getCurrRank(), e);
        }

    }

    public <T extends StaffBaseInfoDto> void fillPositionNameById(T dto) {
        PositionEntity entity = positionApi.queryInfoById(dto.getCurrPosition());
        if (entity != null) {
            dto.setCurrPositionName(entity.getFullName());
        }
    }

    public <T extends StaffBaseInfoDto> void fillOrgNameById(T dto) {
        OrganizeEntity entity = organizeApi.getInfoById(dto.getCurrOrg());
        if (null != entity) {
            dto.setCurrOrgName(entity.getFullName());
        }
    }


    public void fillContactInfo(FtbPersonnelsStaffRosterDto dto) {
        if (StringUtils.isNotEmpty(dto.getContractType())) {
            String contractTypeName = queryContractTypeName(dto.getContractType());
            dto.setContractTypeName(contractTypeName);
        }
    }

    public void fillCurrRankName(List<FtbPersonnelsStaffRosterDto> records) {
        List<String> list = records.stream().map(StaffBaseInfoDto::getCurrRank).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        ActionResult<List<GradeVO>> listActionResult = v2GradesApi.listGradeByIds(list,null);
        if (listActionResult == null || CollUtil.isEmpty(listActionResult.getData()) ) {
            return;
        }
        Map<String, GradeVO> gradeVOMap = listActionResult.getData().stream().collect(Collectors.toMap(GradeVO::getId, Function.identity(), (v1, v2) -> v1));
        records.forEach(
                item -> {
                    if (StringUtils.isNotEmpty(item.getCurrRank())) {
                        GradeVO gradeVO = gradeVOMap.get(item.getCurrRank());
                        if (null != gradeVO) {
                            item.setCurrRankName(gradeVO.getFullName());
                        }
                    }
                }
        );
    }

    public void fillCurrPositionName(List<FtbPersonnelsStaffRosterDto> list) {
        //获取组织id列表
        List<String> ids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getCurrPosition())) {
                ids.add(item.getCurrPosition());
            }
        });

        ActionResult<List<PositionVO>> listActionResult = v2PositionApi.listPositionDetailInfo(ids);
        if (listActionResult == null && CollectionUtil.isEmpty(listActionResult.getData())) {
            return;
        }
        Map<String, PositionVO> listMap = listActionResult.getData().stream().collect(Collectors.toMap(PositionVO::getId, Function.identity()));
        for (FtbPersonnelsStaffRosterDto dto : list) {
            PositionVO entity = listMap.get(dto.getCurrPosition());
            if (null == entity) {
                continue;
            }
            dto.setCurrPositionName(entity.getFullName());
        }
    }


    public List<PositionEntity> queryPostionInfoForIds(List<String> ids) {

        List<PositionEntity> entityLists = positionApi.getPositionName(ids);
        if (CollectionUtil.isEmpty(entityLists)) {
            return new ArrayList<>();
        }
        return entityLists;
    }


    public void fillCurrOrgName(List<FtbPersonnelsStaffRosterDto> list) {
        //获取组织id列表
        List<String> ids = list.stream().map(FtbPersonnelsStaffRosterDto::getCurrOrg).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        List<String> currGroupId = list.stream().map(FtbPersonnelsStaffRosterDto::getCurrGroupId).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        ids.addAll(currGroupId);
        ActionResult<List<OrganizeGeneralDetailVO>> actionResult = v2OrganizeApi.organizesByOrganizeIds(ids);
        if ( actionResult  == null || CollectionUtil.isEmpty(actionResult.getData())) {
            return;
        }
        Map<String, OrganizeGeneralDetailVO> listMap = actionResult.getData().stream().collect(Collectors.toMap(OrganizeGeneralDetailVO::getId, Function.identity()));
        for (FtbPersonnelsStaffRosterDto dto : list) {
            if (listMap.containsKey(dto.getCurrGroupId())){
                dto.setCurrGroupName(listMap.get(dto.getCurrGroupId()).getName());
            }
            if (listMap.containsKey(dto.getCurrOrg())){
                dto.setCurrOrgName(listMap.get(dto.getCurrOrg()).getName());
            }
        }
    }


    public void fillReportsToInfo(List<FtbPersonnelsStaffRosterDto> list) {
        List<String> ids = new ArrayList<>();
        for (FtbPersonnelsStaffRosterDto dto : list) {
            if (StringUtils.isNotEmpty(dto.getCurrReportsTo())) {
                ids.add(dto.getCurrReportsTo());
            }
        }

        Map<String, UserEntity> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ids)) {
            List<UserEntity> userEntityList = userApi.getUserName(ids);
            if (CollectionUtil.isNotEmpty(userEntityList)) {
                //按照用户ID 转成map
                userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getId, userEntity -> userEntity));
            }
        }
        for (FtbPersonnelsStaffRosterDto vo : list) {
            UserEntity userEntity = userMap.get(vo.getCurrReportsTo());
            if (userEntity != null) {
                vo.setCurrReportsToName(userEntity.getRealName());
            }
        }
    }

    /**
     * 根据用户ID查询用户列表
     *
     * @param userIds
     * @return
     */
    public List<UserEntity> queryUserInfoByIds(List<String> userIds) {
        List<UserEntity> userEntityList = userApi.getUserName(userIds);
        if (CollectionUtil.isNotEmpty(userEntityList)) {
            return userEntityList;
        }
        return new ArrayList<>();
    }

    /**
     * 是否是最高组织
     *
     * @param currOrg
     * @return false 不是，true 是最高组织
     */

    public Boolean checkIsTopOrg(String currOrg) {
        OrganizeEntity organizeEntity = queryOrganizeInfo(currOrg);
        if (null == organizeEntity) {
            log.error("未查询到组织的相关信息,currOrg={}", currOrg);
            throw new RuntimeException("未查询到组织的相关信息");
        }
        if (StringUtils.isEmpty(organizeEntity.getParentId()) || "-1".equals(organizeEntity.getParentId())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 同步用户头像
     *
     * @param userId
     * @param inputHeadLogo
     */
    public void sysUserHeadLog(String userId, String inputHeadLogo) {

        SaveTenantUserForm saveTenantUserForm = new SaveTenantUserForm();
        saveTenantUserForm.setId(userId);
        saveTenantUserForm.setHeadIcon(inputHeadLogo);
        pTenantAccountApi.userInfoSynchronous(saveTenantUserForm);
    }

    public Boolean checkStoreUser(String userId) {
        Integer integer = storeMapper.checkStoreUser(userId);
        if (integer > 0) {
            return true;
        } else {
            return false;
        }
    }


    public List<UserListVO> queryAllUserForOrgAndStatus(QueryUserListDTO req) {
        return userApi.getAllUser(req);
    }

    public void rollbackTenantUser(List<UserAccountDto> addUserList) {
        if (CollectionUtil.isEmpty(addUserList)) {
            return;
        }
        for (UserAccountDto userAccountDto : addUserList) {
            personnelOrgUtils.deleteTenantUser(userAccountDto.getFid());
        }
    }

    public ActionResult<PageListVO<PartUserInfoVo>> getPartUserInfoPage(UserQueryDto queryDto) {
        return ftbApi.getPartUserInfoPage(queryDto);
    }

    public List<RoleListVO> getAllRoleForOrgIds(List<String> orgList) {
        ActionResult<List<RoleListVO>> listActionResult = roleApi.partAllList(orgList);
        if (null == listActionResult || CollectionUtil.isEmpty(listActionResult.getData())) {
            return new ArrayList<>();
        }
        return listActionResult.getData();
    }

    public List<RoleEntity> getRoleInfoForIds(List<String> subRole) {
        return roleApi.getListByIds(subRole);

    }

    public List<UserInfoVO> queryTenantAccountForPhoneList(List<String> phoneList) {
        if (CollectionUtil.isEmpty(phoneList)) {
            return new ArrayList<>();
        }
        ActionResult<List<UserInfoVO>> userInfoByPhones = userApi.getUserInfoByPhones(phoneList);
        if (null == userInfoByPhones) {
            return new ArrayList<>();
        }
        return userInfoByPhones.getData();
    }

    public void sysTenantAccountBase(SaveUserManagerAddDTO dto) {

        if (StringUtils.isNotEmpty(dto.getHeadIcon())) {
            int lastIndex = dto.getHeadIcon().lastIndexOf('/');
            String fileName = dto.getHeadIcon().substring(lastIndex + 1);
            dto.setHeadIcon(fileName);
        }
        UpdateUserDTO userDTO = new UpdateUserDTO();
        userDTO.setId(dto.getUserId());
        userDTO.setAccount(dto.getAccount());
        userDTO.setRealName(dto.getRealName());
        userDTO.setNickName(dto.getNickName());
        userDTO.setHeadIcon(dto.getHeadIcon());
        userDTO.setMobilePhone(dto.getMobilePhone());
        userDTO.setWorkerStatus(dto.getWorkerStatus());
        userDTO.setHeadIcon(dto.getHeadIcon());
        userDTO.setBecomeDate(dto.getBecomeDate());
        userDTO.setDepartDate(dto.getDepartDate());
        v2UserApi.updateUserInfo(dto.getUserId(),userDTO);
    }

    public void batchSysTenantAccountBase(List<SaveUserManagerAddDTO> list) {
        for (SaveUserManagerAddDTO dto : list) {
            sysTenantAccountBase(dto);
        }
    }

    public void sysTenantAccountBaseNoLogin(SaveUserManagerAddDTO dto, String tenantId) {

        if (StringUtils.isNotEmpty(dto.getHeadIcon())) {
            int lastIndex = dto.getHeadIcon().lastIndexOf('/');
            String fileName = dto.getHeadIcon().substring(lastIndex + 1);
            dto.setHeadIcon(fileName);
        }
        log.error("正常日志：sysTenantAccountBase nologin={}", JSONUtil.toJsonStr(dto));
        Boolean aBoolean = userApi.userInfoUpdateNoToken(dto, tenantId);
    }

    /**
     * 同步用户考勤组
     *
     * @param dto
     */
    public void syncAttendanceGroup(GroupUpdateByUserDTO dto) {
        ActionResult actionResult = attendanceUserApi.groupUpdateByPersonnel(dto);
        if (actionResult == null) {
            log.error("考勤组变更失败,req={},result=null", JSONUtil.toJsonStr(dto));
        }
    }

    /**
     * 查询用户考勤组
     *
     * @param userId
     */
    public List<AttendanceUserGroupVo> queryAttendanceGroup(String userId) {
        List<AttendanceUserGroupVo> attendanceUserGroup = attendanceGroupApi.getAttendanceUserGroup(List.of(userId));
        if (CollectionUtil.isEmpty(attendanceUserGroup)) {
            return new ArrayList<>();
        }
        return attendanceUserGroup;
    }

    public String getTenantId() {
        UserInfo userInfo = UserProvider.getUser();
        return userInfo.getTenantId();
    }

    public Map<String, String> getHeadersForLogin() {
        UserInfo userInfo = UserProvider.getUser();
        String token = userInfo.getToken();
        if (StringUtils.isEmpty(token)) {
            token = "";
        }
        Map<String, String> headers = ImmutableMap.of(Constants.AUTHORIZATION.toLowerCase(), token);
        return headers;
    }

    public Integer calMonth(ProbationPeriodDto probationPeriodDto) {
        int month = 0;
        if (probationPeriodDto.getType().equals("101")) {
            month = 1;
        } else if (probationPeriodDto.getType().equals("102")) {
            month = 1;
        } else if (probationPeriodDto.getType().equals("103")) {
            month = 2;
        } else if (probationPeriodDto.getType().equals("104")) {
            month = 3;
        } else if (probationPeriodDto.getType().equals("105")) {
            month = 4;
        } else if (probationPeriodDto.getType().equals("106")) {
            month = 5;
        } else if (probationPeriodDto.getType().equals("107")) {
            month = 6;
        } else if (probationPeriodDto.getType().equals("108")) {
            month = 7;
        } else if (probationPeriodDto.getType().equals("109")) {
            month = 8;
        }
        return month;
    }

    public void updateBaseInfoForBaseUser(FtbPersonnelsStaffRoster entity) {
        //同步姓名 花名册等信息到组织架构
        Boolean isUpdateTenant = false;
        SaveUserManagerAddDTO dto = new SaveUserManagerAddDTO();
        dto.setUserId(entity.getUserId());
        dto.setRealName(entity.getName());

        if (entity.getActualProbationaryDate() != null) {
            dto.setBecomeDate(entity.getActualProbationaryDate());
            isUpdateTenant = true;
        }
        if (entity.getActualStartDate() != null) {
            dto.setEntryDate(entity.getActualStartDate());
            isUpdateTenant = true;
        }
        if (isUpdateTenant) {
            try {
                sysTenantAccountBase(dto);
            } catch (Exception e) {
                log.error("入职同步组织架构失败", e);
            }
        }
    }

    public String convertProbationPeriod(ProbationPeriodDto bean) {
        if (bean == null) {
            return "";
        }
        if ("100".equals(bean.getType())) {
            return "无试用期";
        } else if ("101".equals(bean.getType())) {
            return "1个月内" + "(" + bean.getDays() + "天)";
        } else if ("102".equals(bean.getType())) {
            return "1个月";
        } else if ("103".equals(bean.getType())) {
            return "2个月";
        } else if ("104".equals(bean.getType())) {
            return "3个月";
        } else if ("105".equals(bean.getType())) {
            return "4个月";
        } else if ("106".equals(bean.getType())) {
            return "5个月";
        } else if ("107".equals(bean.getType())) {
            return "6个月";
        } else if ("108".equals(bean.getType())) {
            return "7个月";
        } else if ("109".equals(bean.getType())) {
            return "8个月";
        }
        return "";
    }

    public  int calculateAge(LocalDate birthDate) {
        LocalDate today = LocalDate.now();
        Period period = Period.between(birthDate, today);
        return period.getYears();
    }

    /**
     * 将 java.util.Date 转换为 java.time.LocalDate。
     *
     * @param date 日期对象
     * @return LocalDate 对象
     */
    public  LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
    }

    public  Map<String, OrganizeEntity> queryParentOrgInfo(Set<String> allOrgIds, String tenantCode) {
        return organizeApi.batchQueryParentOrgInfo(new ArrayList<>(allOrgIds),tenantCode);
    }


    public String getLeaderInfo(@NotBlank(message = "原组织不能为空") String fromOrg,
                                String userId,
                                @NotBlank(message = "原岗位不能为空") String fromPositionId,
                                @NotBlank(message = "原职等不能为空") String fromRankId) {
        UserInfoVO leaderInfo = userApi.getLeaderInfo(fromOrg, userId, fromPositionId, fromRankId);
        return leaderInfo != null ?  leaderInfo.getId() : null;
    }
}



