package jnpf.personnels.service.impl;

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.util.StrUtil;
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.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.ActionResult;
import jnpf.model.enums.EmployeeMetaDataType;
import jnpf.model.enums.StaffWorkerStatus;
import jnpf.model.personnels.dto.roster.meta.*;
import jnpf.model.personnels.dto.staff.registerform.ProbationPeriodDto;
import jnpf.model.personnels.dto.staff.roster.FtbPersonnelsStaffRosterDto;
import jnpf.model.personnels.dto.staff.roster.WorkerGroupDataDto;
import jnpf.model.personnels.po.FtbPersonnelsRegistrationFormFieldOption;
import jnpf.model.personnels.po.FtbPersonnelsStaffEmploymentApply;
import jnpf.model.personnels.po.FtbPersonnelsStaffRegistrationFormData;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.req.roster.FtbPersonnelsMetaDataReq;
import jnpf.model.personnels.req.roster.FtbPersonnelsMetaFuctionReq;
import jnpf.model.personnels.req.roster.StaffRosterListReq;
import jnpf.permission.ContractTypeApi;
import jnpf.permission.RoleApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.model.role.RoleListVO;
import jnpf.permission.model.role.UserBoundRolesVO;
import jnpf.permission.vo.contract.ContractTypeVO;
import jnpf.personnels.mapper.FtbPersonnelsStaffEmploymentApplyMapper;
import jnpf.personnels.mapper.FtbPersonnelsStaffRosterMapper;
import jnpf.personnels.service.FtbPersonnelsMetaDataService;
import jnpf.personnels.service.FtbPersonnelsRegistrationFormFieldOptionService;
import jnpf.personnels.service.FtbPersonnelsStaffRegistrationFormDataService;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.personnels.utils.PersonnelOrgUtils;
import jnpf.util.JsonUtil;
import jnpf.yozo.utils.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FtbPersonnelsMetaDataServiceImpl implements FtbPersonnelsMetaDataService {


    @Autowired
    private FtbPersonnelsStaffRegistrationFormDataService registrationFormDataService;
    @Autowired
    private FtbPersonnelsStaffEmploymentApplyMapper ftbPersonnelsStaffEmploymentApplyMapper;

    @Autowired
    private PersonnelOrgUtils personnelOrgUtils;

    @Autowired
    private FtbPersonnelsStaffRosterService staffRosterService;

    @Autowired
    private RoleApi roleApi;

    @Autowired
    private FtbPersonnelsRegistrationFormFieldOptionService fieldOptionService;

    @Autowired
    private ContractTypeApi contractTypeApi;

    @Autowired
    private FtbPersonnelsStaffRosterMapper ftbPersonnelsStaffRosterMapper;

    @Override
    public List<PersonnelsMetaDTO> getMetaData(FtbPersonnelsMetaDataReq info) {
        log.error("getMetaData={}", info);

        List<String> userIds = info.getUserIds();
        List<EmployeeMetaDataType> dataTypeList = info.getDataType();
        List<PersonnelsMetaDTO> retList = new ArrayList<>();
        if (CollectionUtil.isEmpty(userIds)) {
            return retList;
        }
        if (CollectionUtil.isEmpty(dataTypeList)) {
            return retList;
        }
        Page<FtbPersonnelsStaffRosterDto> page = new Page();
        page.setSize(-1);
        page.setCurrent(1);
        Page<FtbPersonnelsStaffRosterDto> ftbPersonnelsStaffRosterDtoPage = ftbPersonnelsStaffRosterMapper.pagingQueryNewWithTurnoverManagerList(new StaffRosterListReq(), userIds, page);
        List<FtbPersonnelsStaffRosterDto> records = ftbPersonnelsStaffRosterDtoPage.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return new ArrayList<>();
        }
        List<FtbPersonnelsStaffRoster> rosterList = records.stream().map(personnel -> {
            FtbPersonnelsStaffRoster ftbPersonnelsStaffRoster = JsonUtil.getJsonToBean(personnel, FtbPersonnelsStaffRoster.class);
            return ftbPersonnelsStaffRoster;
        }).collect(Collectors.toList());


        List<String> rosterIds = new ArrayList<>();
        for (FtbPersonnelsStaffRoster roster : rosterList) {
            if(StrUtil.isNotEmpty(roster.getId())) {
                rosterIds.add(roster.getId());
            }
        }
        List<FtbPersonnelsStaffRegistrationFormData> allList = registrationFormDataService.queryFormFieldValueForRosterIds(rosterIds);
        Map<String, List<FtbPersonnelsStaffRegistrationFormData>> allFormDataMap = allList.stream().collect(Collectors.groupingBy(FtbPersonnelsStaffRegistrationFormData::getRosterId));


        Map<String, List<WorkerGroupDataDto>> orgMap = new HashMap<>();

        if (dataTypeList.contains(EmployeeMetaDataType.ORGANIZATION_INFO)) {
            orgMap = personnelOrgUtils.getUserOrgBoundInfoForUserListAndTenantId(userIds, info.getTenantCode(), false);
            Set<String> allOrgIds = new HashSet<>();
            if (CollectionUtil.isNotEmpty(orgMap)) {
                for (Map.Entry<String, List<WorkerGroupDataDto>> entry : orgMap.entrySet()) {
                    List<WorkerGroupDataDto> workerGroupDataDtos = entry.getValue();
                    for (WorkerGroupDataDto workerGroupDataDto : workerGroupDataDtos) {
                        if (StringUtils.isNotEmpty(workerGroupDataDto.getAffiliatedOrg())) {
                            allOrgIds.add(workerGroupDataDto.getAffiliatedOrg());
                        }
                    }
                }
                Map<String, OrganizeEntity> orgToParentOrgInfoMap = personnelOrgUtils.queryParentOrgInfo(allOrgIds, info.getTenantCode());
                if (CollectionUtil.isNotEmpty(orgToParentOrgInfoMap)) {
                    for (Map.Entry<String, List<WorkerGroupDataDto>> entry : orgMap.entrySet()) {
                        List<WorkerGroupDataDto> workerGroupDataDtos = entry.getValue();
                        for (WorkerGroupDataDto workerGroupDataDto : workerGroupDataDtos) {
                            OrganizeEntity parentOrganizeEntity = orgToParentOrgInfoMap.get(workerGroupDataDto.getAffiliatedOrg());
                            if (parentOrganizeEntity != null) {
                                workerGroupDataDto.setParentOrg(parentOrganizeEntity.getId());
                                workerGroupDataDto.setParentOrgEncode(parentOrganizeEntity.getEnCode());
                                workerGroupDataDto.setParentOrgName(parentOrganizeEntity.getFullName());
                            }
                        }
                    }
                }
            }

        }

        Map<String, List<RoleListVO>> roleDtoMap = new HashMap<>();
        if (dataTypeList.contains(EmployeeMetaDataType.ROLE)) {
            roleDtoMap = queryRoleListForUserIdsNoToken(userIds, info.getTenantCode());
        }

        Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap = queryAllOption();

        for (FtbPersonnelsStaffRoster roster : rosterList) {
            PersonnelsMetaDTO dto = new PersonnelsMetaDTO();
            List<FtbPersonnelsStaffRegistrationFormData> formDataList = allFormDataMap.get(roster.getId());
            List<WorkerGroupDataDto> workerGroupDataDtoList = orgMap.get(roster.getUserId());
            List<RoleListVO> roleListVOS = roleDtoMap.get(roster.getUserId());
            for (EmployeeMetaDataType employeeMetaDataType : dataTypeList) {
                fillMetaData(dto, roster, formDataList, workerGroupDataDtoList, roleListVOS, optionMap, employeeMetaDataType);
            }
            retList.add(dto);
        }

        return retList;
    }

    @Override
    public Boolean queryCurrMonthDepartStatus(String userId, String tenantId) {
        FtbPersonnelsStaffRoster roster = staffRosterService.queryRosterInfoByUserId(userId);
        if (roster == null) {
            throw new RuntimeException("员工不存在");
        }
        if (roster.getEnabledMark() == 1) {
            throw new RuntimeException("员工不存在");
        }
        if (roster.getWorkerStatus().equals(StaffWorkerStatus.RESIGNED.getCode())) {
            if (roster.getDepartDate() != null) {
                if (isSameYearAndMonth(roster.getDepartDate())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Boolean queryCurrMonthDepartStatusByDate(String userId, String tenantId, Date startDate, Date endDate) {
        FtbPersonnelsStaffRoster roster = staffRosterService.queryRosterInfoByUserId(userId);
        if (roster == null) {
            throw new RuntimeException("员工不存在");
        }
        if (roster.getEnabledMark() == 1) {
            throw new RuntimeException("员工不存在");
        }
        if (roster.getWorkerStatus().equals(StaffWorkerStatus.RESIGNED.getCode())) {
            if (roster.getDepartDate() != null) {
                //判断离职离职是否大于开始小于结束
                return roster.getDepartDate().compareTo(startDate) >= 0 && roster.getDepartDate().compareTo(endDate) <= 0;
            }
        }
        return false;
    }

    @Override
    public Map<String, Boolean> queryCurrMonthLeave(FtbPersonnelsMetaFuctionReq req) {
        if (CollUtil.isEmpty(req.getUserIds())){
            throw new RuntimeException("用户ID不能为空");
        }
        Map<String, Boolean> result = new HashMap<>();
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> queryWrapper = Wrappers.<FtbPersonnelsStaffRoster>lambdaQuery()
                .in(FtbPersonnelsStaffRoster::getUserId, req.getUserIds())
                .ge(FtbPersonnelsStaffRoster::getDepartDate,req.getStartDate())
                .le(FtbPersonnelsStaffRoster::getDepartDate,req.getEndDate());
        List<FtbPersonnelsStaffRoster> rosters = ftbPersonnelsStaffRosterMapper.selectList(queryWrapper);
        Map<String, FtbPersonnelsStaffRoster> rosterMap = rosters.stream()
                .collect(Collectors.toMap(FtbPersonnelsStaffRoster::getUserId, Function.identity(), (a, b) -> b));
        for (String userId : req.getUserIds()) {
            Boolean leaveStatus = Boolean.FALSE;
            FtbPersonnelsStaffRoster aDefault = rosterMap.getOrDefault(userId, null);
            if (aDefault != null) {
                leaveStatus = Boolean.TRUE;
            }
            result.put(userId, leaveStatus);
        }
        return result;
    }

    public static boolean isSameYearAndMonth(Date targetDate) {
        Calendar now = Calendar.getInstance();
        Calendar target = Calendar.getInstance();
        target.setTime(targetDate);

        // 获取当前年份和月份
        int currentYear = now.get(Calendar.YEAR);
        int currentMonth = now.get(Calendar.MONTH); // 注意月份是从0开始的

        // 获取目标日期的年份和月份
        int targetYear = target.get(Calendar.YEAR);
        int targetMonth = target.get(Calendar.MONTH);

        // 比较年份和月份
        return currentYear == targetYear && currentMonth == targetMonth;
    }


    private void fillMetaData(PersonnelsMetaDTO dto, FtbPersonnelsStaffRoster roster, List<FtbPersonnelsStaffRegistrationFormData> formDataList,
                              List<WorkerGroupDataDto> workerGroupDataDtoList, List<RoleListVO> roleList,
                              Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap, EmployeeMetaDataType employeeMetaDataType) {
        Map<String, FtbPersonnelsStaffRegistrationFormData> fieldValueMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(formDataList)) {
            for (FtbPersonnelsStaffRegistrationFormData formData : formDataList) {
                fieldValueMap.put(formData.getFormFieldId(), formData);
            }
        }
        dto.setId(roster.getId());
        dto.setName(roster.getName());
        dto.setUserId(roster.getUserId());
        switch (employeeMetaDataType) {
            case BASIC_INFO://员工基本信息
                PersonnelsBaseMetaData baseMetaData = dto.getBaseMetaData();
                baseMetaData.setId(roster.getId());
                baseMetaData.setUserId(roster.getUserId());
                baseMetaData.setName(roster.getName());
                baseMetaData.setFlowerName(getFlowerName(fieldValueMap));
                String workerSex = getWorkerSex(fieldValueMap);
                baseMetaData.setWorkerSex(workerSex);
                if (HttpRequestUtils.StringUtils.isNotEmpty(workerSex)) {
                    FtbPersonnelsRegistrationFormFieldOption option = optionMap.get(workerSex);
                    if (option != null) {
                        baseMetaData.setWorkerSexName(option.getName());
                    }
                }
                baseMetaData.setIdCardNum(getCommonValue(fieldValueMap, "idCardNum"));
                String birthday = getCommonValue(fieldValueMap, "birthday");
                if (StringUtils.isNotEmpty(birthday)) {
                    baseMetaData.setBirthday(personnelOrgUtils.stringDateToDate(birthday));
                    int age = calculateAge(dateToLocalDate(baseMetaData.getBirthday()));
                    baseMetaData.setAge(String.valueOf(age));
                } else {
                    String age = getCommonValue(fieldValueMap, "birthday");
                    baseMetaData.setAge(age);
                }

                String nation = getCommonValue(fieldValueMap, "nation");
                if (StringUtils.isNotEmpty(nation)) {
                    FtbPersonnelsRegistrationFormFieldOption option = optionMap.get(nation);
                    if (option != null) {
                        baseMetaData.setNation(option.getName());
                    }
                }
                String workAge = getCommonValue(fieldValueMap, "workAge");
                if (StringUtils.isNotEmpty(workAge)) {
                    workAge = removeChineseCharacters(workAge);
                    if (StringUtils.isNotEmpty(workAge)) {
                        baseMetaData.setWorkAge(Integer.parseInt(workAge));
                    }
                }
                baseMetaData.setPhone(roster.getPhone());
                baseMetaData.setSystemWokerId(roster.getSystemWokerId());
                baseMetaData.setWorkerNo(roster.getWorkerNo());
                baseMetaData.setActualStartDate(roster.getActualStartDate());
                baseMetaData.setWorkerStatus(roster.getWorkerStatus());
                baseMetaData.setWorkerStatusName(convertWorkerStatusName(roster.getWorkerStatus()));
                //重复入职不显示离职时间
                if (StaffWorkerStatus.RESIGNED.getCode().equals(roster.getWorkerStatus())) {
                    baseMetaData.setDepartDate(roster.getDepartDate());
                }
                if (!StaffWorkerStatus.RESIGNED.getCode().equals(roster.getWorkerStatus())) {
                    baseMetaData.setActualProbationaryDate(Objects.nonNull(roster.getActualProbationaryDate())
                            ?roster.getActualProbationaryDate()
                            :roster.getActualStartDate());
                }
                //司龄
                if (roster.getActualStartDate() == null) {
                    baseMetaData.setCompanyAge(0);
                } else {
                    // 将 Date 转换为 LocalDate
                    LocalDate startDate = roster.getActualStartDate().toInstant()
                            .atZone(ZoneId.of("Asia/Shanghai"))
                            .toLocalDate();
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 计算完整月数差
                    long monthsBetween = ChronoUnit.MONTHS.between(startDate, currentDate);
                    // 计算入职日期到当前日期之间的天数差
                    long daysBetween = ChronoUnit.DAYS.between(startDate, currentDate);
                    // 获取当前月份的天数
                    long daysInMonth = currentDate.lengthOfMonth();
                    // 如果有多出的天数（即非整月的部分），算作多一个月
                    if (daysBetween % daysInMonth > 0) {
                        monthsBetween++;
                    }
                    baseMetaData.setCompanyAge((int) monthsBetween);
                }
                break;
            case EDUCATION_INFO://学历信息
                PersonnelsEducationMetaData educationMetaData = dto.getEducationMetaData();
                String education = getCommonValue(fieldValueMap, "education");
                if (StringUtils.isNotEmpty(education)) {
                    FtbPersonnelsRegistrationFormFieldOption option = optionMap.get(education);
                    if (option != null) {
                        educationMetaData.setEducation(option.getName());
                    }
                }
                break;
            case JOB_INFO://工作信息
                PersonnelsWorkerMetaData workerMetaData = dto.getWorkerMetaData();
                workerMetaData.setWorkerStatus(roster.getWorkerStatus());
                workerMetaData.setWorkerStatusName(convertWorkerStatusName(roster.getWorkerStatus()));

                workerMetaData.setWorkerType(roster.getWorkerType());
                if (StringUtils.isNotEmpty(roster.getWorkerType())) {
                    FtbPersonnelsRegistrationFormFieldOption option = optionMap.get(roster.getWorkerType());
                    if (option != null) {
                        workerMetaData.setWorkerTypeName(option.getName());
                    }
                }
                workerMetaData.setSystemWokerId(roster.getSystemWokerId());
                workerMetaData.setWorkerNo(roster.getWorkerNo());
                //司龄
                if (roster.getActualStartDate() == null) {
                    workerMetaData.setCompanyAge(0);
                } else {
                    // 将 Date 转换为 LocalDate
                    LocalDate startDate = roster.getActualStartDate().toInstant()
                            .atZone(ZoneId.of("Asia/Shanghai"))
                            .toLocalDate();
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 计算完整月数差
                    long monthsBetween = ChronoUnit.MONTHS.between(startDate, currentDate);
                    // 计算入职日期到当前日期之间的天数差
                    long daysBetween = ChronoUnit.DAYS.between(startDate, currentDate);
                    // 获取当前月份的天数
                    long daysInMonth = currentDate.lengthOfMonth();
                    // 如果有多出的天数（即非整月的部分），算作多一个月
                    if (daysBetween % daysInMonth > 0) {
                        monthsBetween++;
                    }
                    workerMetaData.setCompanyAge((int) monthsBetween);
                }
                workerMetaData.setTrialJobDay(roster.getTrialJobDay());
                String probationPeriod = getCommonValue(fieldValueMap, "probationPeriod");
                ProbationPeriodDto bean = new ProbationPeriodDto();

                if (org.apache.commons.lang3.StringUtils.isNotEmpty(probationPeriod) && probationPeriod.startsWith("{")) {
                    bean = JSONUtil.toBean(probationPeriod, ProbationPeriodDto.class);
                    if (StringUtils.isEmpty(bean.getDays())) {
                        bean.setDays("0");
                    }
                    workerMetaData.setProbationPeriodDto(bean);
                } else {
                    bean.setType("100");
                    bean.setDays("0");
                    workerMetaData.setProbationPeriodDto(bean);
                }
                workerMetaData.setPeriodDay(runPeriodDay(bean));
                break;
            case CONTRACT_INFO://合同信息
                PersonnelsContactMetaData contactMetaData = dto.getContactMetaData();

                String contractType = getCommonValue(fieldValueMap, "contractType");
                if (StringUtils.isNotEmpty(contractType)) {
                    // 合同类型 转换
                    ActionResult<ContractTypeVO> info = contractTypeApi.getInfo(contractType);
                    if (Objects.nonNull(info.getData())) {
                        Optional.ofNullable(info.getData().getFullName())
                                .ifPresentOrElse(contactMetaData::setContractType,
                                        () -> contactMetaData.setContractType(""));
                    } else {
                        contactMetaData.setContractType("");
                    }
                }

                String contractNum = getCommonValue(fieldValueMap, "contractNum");
                if (StringUtils.isNotEmpty(contractNum)) {
                    contactMetaData.setContractNum(Integer.valueOf(contractNum));
                }

                break;
            case PERSONAL_MATERIAL://个人材料
                PersonnelsMaterialMetaData materialMetaData = dto.getMaterialMetaData();
                String educationCertificate = getCommonValue(fieldValueMap, "educationCertificate");
                if (StringUtils.isNotEmpty(educationCertificate)) {
                    materialMetaData.setEducationCertificate(educationCertificate);
                }

                String academicDegreeCertificate = getCommonValue(fieldValueMap, "academicDegreeCertificate");
                if (StringUtils.isNotEmpty(academicDegreeCertificate)) {
                    materialMetaData.setAcademicDegreeCertificate(academicDegreeCertificate);
                }
                break;
            case ORGANIZATION_INFO://组织信息
                PersonnelsOrgMetaData orgMetaData = dto.getOrgMetaData();
                if (orgMetaData != null) {
                    if (CollectionUtil.isEmpty(workerGroupDataDtoList)){
                        orgMetaData.setList(new ArrayList<>());
                    }else {
                        orgMetaData.setList(workerGroupDataDtoList);
                    }
                    orgMetaData.getList().stream().filter(WorkerGroupDataDto::getIsPrimaryPosition).findFirst().ifPresent(data -> {
                        orgMetaData.setAffiliatedOrg(data.getAffiliatedOrg());
                        orgMetaData.setAffiliatedOrgName(data.getAffiliatedOrgName());
                        orgMetaData.setAffiliatedPosition(data.getAffiliatedPosition());
                        orgMetaData.setAffiliatedPositionName(data.getAffiliatedPositionName());
                        orgMetaData.setAffiliatedRank(data.getAffiliatedRank());
                        orgMetaData.setAffiliatedRankName(data.getAffiliatedRankName());
                        orgMetaData.setParentOrg(data.getParentOrg());
                        orgMetaData.setParentOrgName(data.getParentOrgName());
                    });
                    // 获取入职失败的组织信息
                    if (CollectionUtil.isEmpty(orgMetaData.getList())) {
                        LambdaQueryWrapper<FtbPersonnelsStaffEmploymentApply> query = new LambdaQueryWrapper<>();
                        query.eq(FtbPersonnelsStaffEmploymentApply::getUserId, roster.getUserId());
                        query.last("limit 1");
                        FtbPersonnelsStaffEmploymentApply apply = ftbPersonnelsStaffEmploymentApplyMapper.selectOne(query);
                        if (apply != null) {
                            orgMetaData.setAffiliatedOrg(apply.getCurrOrg());
                            orgMetaData.setAffiliatedOrgName(apply.getCurrOrgName());
                            orgMetaData.setAffiliatedPosition(apply.getCurrPosition());
                            orgMetaData.setAffiliatedPositionName(apply.getCurrPositionName());
                            orgMetaData.setAffiliatedRank(apply.getCurrRank());
                            orgMetaData.setAffiliatedRankName(apply.getCurrRankName());
                        }
                    }
                }
                break;
            case ROLE://角色
                Optional.ofNullable(dto.getRoleMetaData()).ifPresentOrElse(roleListItem->{
                    PersonnelsRoleMetaData roleMetaData = dto.getRoleMetaData();
                    if (CollectionUtil.isNotEmpty(roleList)){
                        roleList.forEach(role -> {
                            Optional.ofNullable(role.getGlobalMark()).ifPresentOrElse(global -> {
                                role.setType(global == 0 ? "组织" : "全局");
                            }, () -> {
                                role.setType("无效类型");
                            });
                        });
                        roleMetaData.setList(roleList);
                    }
                },()->{
                    dto.setRoleMetaData(new PersonnelsRoleMetaData(){{setList(new ArrayList<>());}});
                });

                break;
        }
    }

    private Integer runPeriodDay(ProbationPeriodDto probationPeriodDto) {
        if (probationPeriodDto == null) {
            return 0;
        }
        if ("100".equals(probationPeriodDto.getType())) {
            return 0;
        }
        int month = 0;
        if (probationPeriodDto.getType().equals("101")) {
            if (StringUtils.isNotEmpty(probationPeriodDto.getDays())) {
                return Integer.valueOf(probationPeriodDto.getDays());
            } else {
                return 0;
            }
        } 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 30 * month;
    }

    private String getWorkerSex(Map<String, FtbPersonnelsStaffRegistrationFormData> fieldValueMap) {
        FtbPersonnelsStaffRegistrationFormData formData = fieldValueMap.get("workerSex");
        if (formData != null) {
            return formData.getValue();
        }
        return "";
    }

    private String getFlowerName(Map<String, FtbPersonnelsStaffRegistrationFormData> fieldValueMap) {
        FtbPersonnelsStaffRegistrationFormData formData = fieldValueMap.get("flowerName");
        if (formData != null) {
            return formData.getValue();
        }
        return "";
    }

    private String getCommonValue(Map<String, FtbPersonnelsStaffRegistrationFormData> fieldValueMap, String fieldId) {
        FtbPersonnelsStaffRegistrationFormData formData = fieldValueMap.get(fieldId);
        if (formData != null) {
            return formData.getValue();
        }
        return "";
    }

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

        Map<String, List<RoleListVO>> ret = new HashMap<>();
        List<UserBoundRolesVO> list = listActionResult.getData();
        for (UserBoundRolesVO userBoundRolesVO : list) {
            ret.put(userBoundRolesVO.getId(), userBoundRolesVO.getRoleBounds());
        }
        return ret;
    }


    public Map<String, FtbPersonnelsRegistrationFormFieldOption> queryAllOption() {
        QueryWrapper<FtbPersonnelsRegistrationFormFieldOption> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbPersonnelsRegistrationFormFieldOption::getEnabledMark, 0).orderByAsc(FtbPersonnelsRegistrationFormFieldOption::getId);
        List<FtbPersonnelsRegistrationFormFieldOption> optionList = fieldOptionService.list(wrapper);
        if (CollectionUtil.isEmpty(optionList)) {
            return new HashMap<>();
        }
        Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap = optionList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormFieldOption::getId, Function.identity()));
        return optionMap;
    }


    /**
     * 计算年龄
     *
     * @param birthDate
     * @return
     */
    public static 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 对象
     */
    private static LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
    }


    /**
     * 去掉字符串中的汉字。
     *
     * @param input 输入字符串
     * @return 去掉汉字后的字符串
     */
    public static String removeChineseCharacters(String input) {
        // 正则表达式匹配汉字
        String regex = "[\\u4e00-\\u9fa5]";
        // 替换掉所有匹配到的汉字
        return input.replaceAll(regex, "");
    }


    public String convertWorkerStatusName(String workerStatus) {
        if (StringUtils.isEmpty(workerStatus)) {
            return "";
        }
        if ("301".equals(workerStatus)) {
            return "预入职";
        } else if ("302".equals(workerStatus)) {
            return "试用";
        } else if ("303".equals(workerStatus)) {
            return "正式";
        } else if ("304".equals(workerStatus)) {
            return "待离职";
        } else if ("305".equals(workerStatus)) {
            return "离职";
        } else if ("306".equals(workerStatus)) {
            return "试岗";
        }
        return "";
    }

    public String convertContactStatusName(String contractStatus) {
        if (StringUtils.isEmpty(contractStatus)) {
            return "";
        }

        // 合同签署状态，500-未发起 501-待签署 502-已到期 503-已签署
        if ("500".equals(contractStatus)) {
            return "未发起";
        } else if ("501".equals(contractStatus)) {
            return "待签署";
        } else if ("502".equals(contractStatus)) {
            return "已到期";
        } else if ("503".equals(contractStatus)) {
            return "已签署";
        }
        return "";
    }


    /**
     * 查询在A和B天数范围内入职的用户ID
     *
     * @param startDays 开始天数
     * @param endDays   结束天数
     * @return 用户id集合
     */
    @Override
    public List<String> queryUserIdsForCompanyAge(Integer startDays, Integer endDays) {
        List<String> retList = new ArrayList<>();
        //查询用户信息
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = new LambdaQueryWrapper<FtbPersonnelsStaffRoster>()
                .select(FtbPersonnelsStaffRoster::getId, FtbPersonnelsStaffRoster::getUserId, FtbPersonnelsStaffRoster::getPhone, FtbPersonnelsStaffRoster::getActualStartDate)
                .in(FtbPersonnelsStaffRoster::getWorkerStatus, "302", "303", "306")
                .eq(FtbPersonnelsStaffRoster::getEnabledMark, 0);
        List<FtbPersonnelsStaffRoster> rosterList = staffRosterService.list(wrapper);
        if (CollectionUtil.isEmpty(rosterList)) {
            return retList;
        }
        Set<String> retSet = new HashSet<>();
        Date now = DateUtil.date();
        for (FtbPersonnelsStaffRoster ftbPersonnelsStaffRoster : rosterList) {
            if (ftbPersonnelsStaffRoster.getActualStartDate() == null) {
                continue;
            }
            //计数入职天数
            Integer days = Integer.parseInt(String.valueOf(DateUtil.between(ftbPersonnelsStaffRoster.getActualStartDate(), now, DateUnit.DAY)));
            if (days >= startDays && days <= endDays) {
                retSet.add(ftbPersonnelsStaffRoster.getUserId());
            }
        }
        return new ArrayList<>(retSet);
    }

    /**
     * 查询指定用户的司龄
     *
     * @param userIds 用户ID
     * @return
     */
    @Override
    public Map<String, Integer> queryCompanyAge(List<String> userIds) {
        Map<String, Integer> retMap = new HashMap<>();
        //查询用户信息
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = new LambdaQueryWrapper<FtbPersonnelsStaffRoster>()
                .select(FtbPersonnelsStaffRoster::getId, FtbPersonnelsStaffRoster::getUserId, FtbPersonnelsStaffRoster::getPhone, FtbPersonnelsStaffRoster::getActualStartDate)
                .in(FtbPersonnelsStaffRoster::getUserId, userIds)
                .eq(FtbPersonnelsStaffRoster::getEnabledMark, 0);
        List<FtbPersonnelsStaffRoster> rosterList = staffRosterService.list(wrapper);
        if (CollectionUtil.isEmpty(rosterList)) {
            return retMap;
        }

        Date now = DateUtil.date();
        for (FtbPersonnelsStaffRoster ftbPersonnelsStaffRoster : rosterList) {
            if (ftbPersonnelsStaffRoster.getActualStartDate() == null) {
                continue;
            }
            //计数入职天数
            Integer days = Integer.parseInt(String.valueOf(DateUtil.between(ftbPersonnelsStaffRoster.getActualStartDate(), now, DateUnit.DAY)));
            retMap.put(ftbPersonnelsStaffRoster.getUserId(), days);
        }

        return retMap;
    }

    @Override
    public Integer queryCompanyAgeByRosterId(String rosterId) {

        List<FtbPersonnelsStaffRegistrationFormData> allList = registrationFormDataService.queryListForRosterIdAndField(List.of(rosterId), List.of("companyAge"));
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        for (FtbPersonnelsStaffRegistrationFormData formData : allList) {
            String companyAge = formData.getValue();
            if (StringUtils.isEmpty(companyAge)) {
                continue;
            }
            return Integer.parseInt(companyAge);
        }
        return null;
    }

    /**
     * 查询所有用户的年龄
     *
     * @return
     */
    @Override
    public Map<String, Integer> queryAllUserCompanyAge() {
        Map<String, Integer> retMap = new HashMap<>();
        //查询用户信息
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = new LambdaQueryWrapper<FtbPersonnelsStaffRoster>()
                .select(FtbPersonnelsStaffRoster::getId, FtbPersonnelsStaffRoster::getUserId, FtbPersonnelsStaffRoster::getPhone)
                .in(FtbPersonnelsStaffRoster::getWorkerStatus, "302", "303", "306")
                .eq(FtbPersonnelsStaffRoster::getEnabledMark, 0);
        List<FtbPersonnelsStaffRoster> rosterList = staffRosterService.list(wrapper);
        if (CollectionUtil.isEmpty(rosterList)) {
            return retMap;
        }
        Map<String, FtbPersonnelsStaffRoster> rosterMap = new HashMap<>();//id->FtbPersonnelsStaffRoster

        List<String> rosterIds = new ArrayList<>();
        for (FtbPersonnelsStaffRoster roster : rosterList) {
            rosterIds.add(roster.getId());
            rosterMap.put(roster.getId(), roster);
        }
        List<FtbPersonnelsStaffRegistrationFormData> allList = registrationFormDataService.queryListForRosterIdAndField(rosterIds, List.of("companyAge"));
        if (CollUtil.isEmpty(allList)) {
            return retMap;
        }

        for (FtbPersonnelsStaffRegistrationFormData formData : allList) {
            String companyAge = formData.getValue();
            if (StringUtils.isEmpty(companyAge)) {
                continue;
            }
            Integer companyAgeInt = Integer.parseInt(companyAge);

            FtbPersonnelsStaffRoster roster = rosterMap.get(formData.getRosterId());
            if (roster != null) {
                retMap.put(roster.getUserId(), companyAgeInt);
            }

        }
        return retMap;
    }

}
