package jnpf.personnels.controller.web.roster;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.ActionResult;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.enums.GrowthLogEnum;
import jnpf.model.personnels.dto.roster.meta.FtbPersonnlesJobTenureDTO;
import jnpf.model.personnels.dto.roster.meta.FtbPersonnlesJoeInfo;
import jnpf.model.personnels.dto.staff.employment.*;
import jnpf.model.personnels.dto.staff.roster.StaffDepartDto;
import jnpf.model.personnels.dto.staff.roster.StaffPromotionDto;
import jnpf.model.personnels.dto.staff.roster.StaffRegularDto;
import jnpf.model.personnels.dto.staff.transfer.TransferGrowthLogDto;
import jnpf.model.personnels.po.FtbPersonnelsSecondmentManagement;
import jnpf.model.personnels.po.FtbPersonnelsStaffGrowthLog;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.po.FtbPersonnelsTransferManage;
import jnpf.model.personnels.vo.roster.FtbHomePageRewardVO;
import jnpf.model.personnels.vo.roster.FtbPersonnelsChangeInfoVO;
import jnpf.model.personnels.vo.roster.FtbPersonnlesJobTenureVO;
import jnpf.model.personnels.vo.secondment.FtbPersonnelsSecondRecordVO;
import jnpf.permission.V2UserApi;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.service.*;
import jnpf.util.NoDataSourceBind;
import jnpf.util.UserProvider;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * web-app员工主页信息
 *
 * @author wangchunxiang
 * @date 2024/10/08
 */
@RestController
@RequestMapping("/web-app/staff-home-page")
public class FtbPersonnelsStaffHomePageController {

    @Resource
    private FtbPersonnelsStaffHomePageService ftbPersonnelsStaffHomePageService;

    @Resource
    private FtbPersonnelsStaffGrowthLogService staffGrowthLogService;

    @Resource
    private FtbPersonnelsStaffRosterService staffRosterService;

    @Resource
    FtbPersonnelsTransferManageService transferManageService;
    @Resource
    private FtbPersonnelsSecondmentManagementService ftbPersonnelsSecondmentService;


    @Autowired
    private V2UserApi userApi;

    /**
     * web员工主页-查询个人承诺
     *
     * @param id 用户主键id
     * @return {@link ActionResult } 图片云存储路径
     */
    @GetMapping("/check-personal-commitments/{id}")
    public ActionResult<String> checkPersonalCommitments(@PathVariable("id") String id) {
        return ActionResult.success("",ftbPersonnelsStaffHomePageService.checkPersonalCommitments(id));
    }

    /**
     * 员工主页-奖励记录
     *
     * @param id 用户主键id
     * @return {@link ActionResult }<{@link List }<{@link FtbHomePageRewardVO }>>
     */
    @GetMapping("/award-record/{id}")
    public ActionResult<List<FtbHomePageRewardVO>> getRewardList(@PathVariable("id") String id) {
        List<FtbHomePageRewardVO> ftbHomePageRewardVOList = ftbPersonnelsStaffHomePageService.getRewardList(id);
        return ActionResult.success(ftbHomePageRewardVOList);
    }

    /**
     * 员工主页-乐捐记录
     *
     * @param id 用户主键id
     * @return {@link ActionResult }<{@link List }<{@link FtbHomePageRewardVO }>>
     */
    @GetMapping("/donation-records/{id}")
    public ActionResult<List<FtbHomePageRewardVO>> donationRecords(@PathVariable("id") String id) {
        List<FtbHomePageRewardVO> ftbHomePageRewardVOList = ftbPersonnelsStaffHomePageService.donationRecords(id);
        return ActionResult.success(ftbHomePageRewardVOList);
    }


    /**
     * 员工主页-异动记录-入职
     */
    @GetMapping("/entry-list")
    public ActionResult<List<FtbPersonnelsEmployApplyListDto>> getEntryList(@RequestParam(name = "userId") String userId) {
        List<FtbPersonnelsEmployApplyListDto> collect = getFtbPersonnelsEmployApplyListDtos(userId);
        return ActionResult.success(collect);
    }

    @NotNull
    private List<FtbPersonnelsEmployApplyListDto> getFtbPersonnelsEmployApplyListDtos(String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId, userId);
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,0,3);
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsEmployApplyListDto> collect = list.stream().map(item -> {
            FtbPersonnelsEmployApplyListDto covert = FtbPersonnelsEmployApplyListDto.covert(item);
            covert.setWorkName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setOperator(userNameMap.getOrDefault(item.getCreatorUserId(), "-"));
            return covert;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 员工主页-异动记录-转正
     *
     * 变化类型
     * - {@link GrowthLogEnum 类型}
     *
     */
    @GetMapping("/regularization-list")
    public ActionResult<List<FtbPersonnelsRegularVO>> getRegularizationList(@RequestParam(name = "userId") String userId) {
        List<FtbPersonnelsRegularVO> regularVOS = getFtbPersonnelsRegularVOS(userId);
        return ActionResult.success(regularVOS);
    }

    @NotNull
    private List<FtbPersonnelsRegularVO> getFtbPersonnelsRegularVOS(String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId, userId);
        // 转正
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,GrowthLogEnum.BECOME_REGULAR_WORKER.getCode());
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsRegularVO> regularVOS = list.stream().map(item -> {
            StaffRegularDto staffRegularDto = JSONUtil.toBean(item.getDetail(), StaffRegularDto.class);
            FtbPersonnelsRegularVO covert = FtbPersonnelsRegularVO.covert(staffRegularDto);
            covert.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setProcessingDate(item.getCreatorTime());
            covert.setEmployeeID(item.getEmployeeId());
            covert.setOperator(userNameMap.getOrDefault(item.getCreatorUserId(), "-"));
            return covert;
        }).collect(Collectors.toList());
        return regularVOS;
    }

    /**
     * 员工主页-异动记录-调岗
     */
    @GetMapping("/transfer-list")
    public ActionResult<List<FtbPersonnelsTransferVO>> getTransferList(@RequestParam(name = "userId") String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId,userId);
        // 调岗
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,GrowthLogEnum.TRANSFER_POSITION.getCode());
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsTransferVO> regularVOS = list.stream().map(item -> {
            TransferGrowthLogDto staffRegularDto = JSONUtil.toBean(item.getDetail(), TransferGrowthLogDto.class);
            FtbPersonnelsTransferVO covert = FtbPersonnelsTransferVO.covert(staffRegularDto);
            covert.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setProcessingDate(item.getCreatorTime());
            covert.setEmployeeID(item.getEmployeeId());
            return covert;
        }).collect(Collectors.toList());
        return ActionResult.success(regularVOS);
    }
    /**
     * 员工主页-异动记录-晋升
     */
    @GetMapping("/promotion-list")
    public ActionResult<List<FtbPersonnelsPromotionLogVO>> getPromotionList(@RequestParam(name = "userId") String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId,userId);
        // 晋升
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,GrowthLogEnum.promotion.getCode());
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsPromotionLogVO> regularVOS = list.stream().map(item -> {
            StaffPromotionDto staffRegularDto = JSONUtil.toBean(item.getDetail(), StaffPromotionDto.class);
            FtbPersonnelsPromotionLogVO covert = FtbPersonnelsPromotionLogVO.covert(staffRegularDto);
            covert.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setProcessingDate(item.getCreatorTime());
            covert.setEmployeeID(item.getEmployeeId());
            return covert;
        }).collect(Collectors.toList());
        return ActionResult.success(regularVOS);
    }
    /**
     * 员工主页-异动记录-离职
     */
    @GetMapping("/leave-list")
    public ActionResult<List<FtbPersonnelsTurnoverLogVO>> getLeaveList(@RequestParam(name = "userId") String userId) {
        List<FtbPersonnelsTurnoverLogVO> regularVOS = getFtbPersonnelsTurnoverLogVOS(userId);
        return ActionResult.success(regularVOS);
    }

    @NotNull
    private List<FtbPersonnelsTurnoverLogVO> getFtbPersonnelsTurnoverLogVOS(String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId, userId);
        // 离职
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,GrowthLogEnum.DEPART.getCode(),GrowthLogEnum.PRE_TRAIL.getCode());
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsTurnoverLogVO> regularVOS = list.stream().map(item -> {
            FtbPersonnelsTurnoverLogVO covert = new FtbPersonnelsTurnoverLogVO();
            if (StringUtils.isNotEmpty(item.getDetail()) && !"[]".equals(item.getDetail())) {
                // 数据兼容
                StaffDepartDto staffDepartDto;
                try {
                    List<StaffDepartDto> staffDepartDtos = JSONArray.parseArray(item.getDetail(), StaffDepartDto.class);
                    staffDepartDto = staffDepartDtos.stream().findFirst().orElse(null);
                }catch (Exception e){
                    staffDepartDto = JSONObject.parseObject(item.getDetail(), StaffDepartDto.class);
                }
                covert = FtbPersonnelsTurnoverLogVO.covert(staffDepartDto);
            }
            covert.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setProcessingDate(item.getChangeDate());
            covert.setEmployeeID(item.getEmployeeId());
            covert.setOperator(userNameMap.getOrDefault(item.getCreatorUserId(), "-"));
            return covert;
        }).collect(Collectors.toList());
        return regularVOS;
    }

    /**
     * 员工主页-异动记录-调动
     */
    @GetMapping("/mobilize-list")
    public ActionResult<List<FtbPersonnelsMoveLogVO>> getMobilizeList(@RequestParam(name = "userId") String userId) {
        List<FtbPersonnelsMoveLogVO> regularVOS = getFtbPersonnelsMoveLogVOS(userId);
        return ActionResult.success(regularVOS);
    }

    @NotNull
    private List<FtbPersonnelsMoveLogVO> getFtbPersonnelsMoveLogVOS(String userId) {
        LambdaQueryWrapper<FtbPersonnelsStaffGrowthLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffGrowthLog::getUserId, userId);
        // 晋升 调岗
        queryWrapper.in(FtbPersonnelsStaffGrowthLog::getGrowthType,GrowthLogEnum.promotion.getCode(),GrowthLogEnum.TRANSFER_POSITION.getCode());
        List<FtbPersonnelsStaffGrowthLog> list = staffGrowthLogService.list(queryWrapper);
        Map<String, String> userNameMap = getUserNameMap(list);
        List<FtbPersonnelsMoveLogVO> regularVOS = list.stream().map(item -> {
            FtbPersonnelsMoveLogVO covert = new FtbPersonnelsMoveLogVO();
            if (item.getGrowthType().equals(GrowthLogEnum.promotion.getCode())) {
                StaffPromotionDto staffRegularDto = JSONUtil.toBean(item.getDetail(), StaffPromotionDto.class);
                covert = FtbPersonnelsMoveLogVO.covert(staffRegularDto);
            }
            if (item.getGrowthType().equals(GrowthLogEnum.TRANSFER_POSITION.getCode())) {
                TransferGrowthLogDto staffRegularDto = JSONUtil.toBean(item.getDetail(), TransferGrowthLogDto.class);
                covert = FtbPersonnelsMoveLogVO.covertTransfer(staffRegularDto);
            }
            covert.setOperator(userNameMap.getOrDefault(item.getCreatorUserId(), "-"));
            covert.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            covert.setProcessingDate(item.getCreatorTime());
            covert.setEmployeeID(item.getEmployeeId());
            return covert;
        }).collect(Collectors.toList());
        //新数据 调动类型0调岗1晋升2降职3调店
        LambdaQueryWrapper<FtbPersonnelsTransferManage> wrapper = Wrappers.lambdaQuery();
        wrapper.in(FtbPersonnelsTransferManage::getProcessingStatus,List.of(6,2));
        wrapper.eq(FtbPersonnelsTransferManage::getImplementType,1);
        wrapper.eq(FtbPersonnelsTransferManage::getUserId, userId);
        List<FtbPersonnelsTransferManage> transferManages = transferManageService.list(wrapper);
        List<FtbPersonnelsMoveLogVO> personnelsMoveLogVOS = transferManages.stream().map(item -> {
            FtbPersonnelsMoveLogVO logVO = FtbPersonnelsMoveLogVO.covertPromotion(item);
            logVO.setName(userNameMap.getOrDefault(item.getUserId(), "-"));
            Integer state = item.getState();
            if (state == 0) {
                logVO.setType("调岗");
            } else if (state == 1) {
                logVO.setType("晋升");
            } else if (state == 2) {
                logVO.setType("降职");
            } else if (state == 3) {
                logVO.setType("调店");
            }
            List<String> list1 = new ArrayList<>();
            if (item.getLastModifyUserId() != null) {
                list1.add(item.getLastModifyUserId());
            }
            list1.add(item.getCreatorUserId());
            ActionResult<List<UserBoundVO>> boundBatch = userApi.getUserPrimaryBoundBatch(list1, UserProvider.getUser().getTenantId());
            Map<String, UserBoundVO> userBoundVOMap = new HashMap<>();
            if (boundBatch.getData() != null) {
                userBoundVOMap = boundBatch.getData().stream().collect(Collectors.toMap(UserBoundVO::getId, Function.identity(), (r1, r2) -> r1));
            }
            if (item.getLastModifyUserId() != null && item.getProcessingStatus() == 2) {
                if (userBoundVOMap.containsKey(item.getLastModifyUserId())) {
                    logVO.setOperator(userBoundVOMap.get(item.getLastModifyUserId()).getUserName());
                } else {
                    logVO.setOperator("-");
                }
            }else if (item.getLastModifyUserId() != null && item.getProcessingStatus() == 6) {
                if (userBoundVOMap.containsKey(item.getCreatorUserId())) {
                    logVO.setOperator(userBoundVOMap.get(item.getCreatorUserId()).getUserName());
                } else {
                    logVO.setOperator("-");
                }
            }
            return logVO;
        }).collect(Collectors.toList());
        regularVOS.addAll(personnelsMoveLogVOS);
        return regularVOS;
    }

    @NotNull
    private Map<String, String> getUserNameMap(List<FtbPersonnelsStaffGrowthLog> list) {
        List<String> userIds = new ArrayList<>();
        userIds.addAll(list.stream().map(FtbPersonnelsStaffGrowthLog::getUserId).collect(Collectors.toList()));
        userIds.addAll( list.stream().map(SuperBaseEntity.SuperCBaseEntity::getCreatorUserId).collect(Collectors.toList()));

        ActionResult<List<UserBoundVO>> boundBatch = userApi.getUserPrimaryBoundBatch(userIds, UserProvider.getUser().getTenantId());
        Map<String, String> userBoundVOMap = new HashMap<>();
        if (boundBatch.getData() != null) {
            userBoundVOMap = boundBatch.getData().stream().collect(Collectors.toMap(UserBoundVO::getId, UserBoundVO::getUserName, (r1, r2) -> r1));
        }
        return userBoundVOMap;
    }

    /**
     * 员工主页-异动记录-借调
     */
    @GetMapping("/borrow-list")
    public ActionResult<List<FtbPersonnelsSecondRecordVO>> getBorrowList(@RequestParam(name = "userId") String userId) {
        List<FtbPersonnelsSecondRecordVO> regularVOS = getFtbPersonnelsSecondRecordVOS(userId);
        return ActionResult.success(regularVOS);
    }

    @NotNull
    private List<FtbPersonnelsSecondRecordVO> getFtbPersonnelsSecondRecordVOS(String userId) {
        LambdaQueryWrapper<FtbPersonnelsSecondmentManagement> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsSecondmentManagement::getUserId, userId);
        queryWrapper.in(FtbPersonnelsSecondmentManagement::getTransferStatus,6,2);
        List<FtbPersonnelsSecondmentManagement> secondmentManagements = ftbPersonnelsSecondmentService.list(queryWrapper);
        List<String> userIds = new ArrayList<>();
        userIds.addAll( secondmentManagements.stream().map(SuperBaseEntity.SuperCBaseEntity::getCreatorUserId).collect(Collectors.toList()))  ;
        userIds.addAll(  secondmentManagements.stream().map(FtbPersonnelsSecondmentManagement::getUserId).collect(Collectors.toList()));
        Map<String, FtbPersonnelsStaffRoster> userNameMap = new HashMap<>();
        if (CollUtil.isNotEmpty(userIds)) {
            LambdaQueryWrapper<FtbPersonnelsStaffRoster> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.in(FtbPersonnelsStaffRoster::getUserId, userIds);
            List<FtbPersonnelsStaffRoster> serviceOne = staffRosterService.list(queryWrapper1);
            userNameMap = serviceOne.stream().collect(Collectors.toMap(FtbPersonnelsStaffRoster::getUserId, Function.identity()));
        }
        ActionResult<List<UserBoundVO>> boundBatch = userApi.getUserPrimaryBoundBatch(userIds, UserProvider.getUser().getTenantId());
        Map<String, String> userBoundVOMap = new HashMap<>();
        if (boundBatch.getData() != null) {
            userBoundVOMap = boundBatch.getData().stream().collect(Collectors.toMap(UserBoundVO::getId, UserBoundVO::getUserName, (r1, r2) -> r1));
        }
        Map<String, FtbPersonnelsStaffRoster> finalUserNameMap = userNameMap;
        Map<String, String> finalUserBoundVOMap = userBoundVOMap;
        List<FtbPersonnelsSecondRecordVO> regularVOS = secondmentManagements.stream().map(item -> {
            FtbPersonnelsSecondRecordVO secondRecordVO = FtbPersonnelsSecondRecordVO.covert(item);
            secondRecordVO.setCreatorUserName(finalUserBoundVOMap.getOrDefault(secondRecordVO.getCreatorUserId(), "-"));
            FtbPersonnelsStaffRoster personnelsStaffRoster = finalUserNameMap.get(secondRecordVO.getUserId());
            secondRecordVO.setEmployeeId( personnelsStaffRoster == null ? "-" : personnelsStaffRoster.getSystemWokerId());
            secondRecordVO.setUserName(personnelsStaffRoster == null ? "-" : personnelsStaffRoster.getName());
            return secondRecordVO;
        }).collect(Collectors.toList());
        return regularVOS;
    }

    /**
     *根据userId 查询人事异动信息
     */
    @GetMapping("/get-personnel-change-info")
    public FtbPersonnelsChangeInfoVO getPersonnelChangeInfo(@RequestParam(name = "userId") String userId) {
        // 入
        List<FtbPersonnelsEmployApplyListDto> ftbPersonnelsEmployApplyListDtos = getFtbPersonnelsEmployApplyListDtos(userId);
        // 转正
        List<FtbPersonnelsRegularVO> regularVOS = getFtbPersonnelsRegularVOS(userId);
        // 调动
        List<FtbPersonnelsMoveLogVO> ftbPersonnelsMoveLogVOS = getFtbPersonnelsMoveLogVOS(userId);
        // 借调
        List<FtbPersonnelsSecondRecordVO> secondRecordVOS = getFtbPersonnelsSecondRecordVOS(userId);
        // 离职
        List<FtbPersonnelsTurnoverLogVO> ftbPersonnelsTurnoverLogVOS = getFtbPersonnelsTurnoverLogVOS(userId);

        FtbPersonnelsChangeInfoVO ftbPersonnelsChangeInfoVO = new FtbPersonnelsChangeInfoVO();
        ftbPersonnelsChangeInfoVO.setOnboarding(ftbPersonnelsEmployApplyListDtos);
        ftbPersonnelsChangeInfoVO.setRegularization(regularVOS);
        ftbPersonnelsChangeInfoVO.setMobilize(ftbPersonnelsMoveLogVOS);
        ftbPersonnelsChangeInfoVO.setSeconded(secondRecordVOS);
        ftbPersonnelsChangeInfoVO.setTurnover(ftbPersonnelsTurnoverLogVOS);
        return ftbPersonnelsChangeInfoVO;
    }


    /**
     * 查询当前用户岗龄
     */
    @PostMapping("/query-positionTenure-age")
    @NoDataSourceBind
    public List<FtbPersonnlesJobTenureVO> queryPositionTenureAge(@RequestBody FtbPersonnlesJobTenureDTO req) {

        List<FtbPersonnlesJoeInfo> personnlesJoeInfos = req.getUserInfo();
        return personnlesJoeInfos.parallelStream().map(item -> {
            try {
                TenantDataSourceUtil.switchTenant(req.getTenantId());
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
            // 查询调动是否有数据没有数据就查询实际入职时间
            List<FtbPersonnelsEmployApplyListDto> listDtoList = getFtbPersonnelsEmployApplyListDtos(item.getUserId());
            if (CollUtil.isEmpty(listDtoList)) {
                return null;
            }
            // 取最后一条数据（按入职时间排序后最新的）
            FtbPersonnelsEmployApplyListDto latestRecord = listDtoList.stream().peek(v->{
                if (v.getActualStartDate() == null) {
                    v.setActualStartDate(v.getCreationTime());
                }
                    })
                    .max(Comparator.comparing(FtbPersonnelsEmployApplyListDto::getActualStartDate, Comparator.nullsLast(Comparator.naturalOrder())))
                    .orElse(null);
            if (latestRecord == null) {
                return null;
            }
            List<FtbPersonnelsMoveLogVO> moveLogVOS = getFtbPersonnelsMoveLogVOS(item.getUserId());
            // 实际入职日期
            Date actualStartDate = latestRecord.getActualStartDate() == null ? latestRecord.getCreationTime() : latestRecord.getActualStartDate();
            // 过滤调动记录在 actualStartDate 之前的数据
            List<FtbPersonnelsMoveLogVO> ftbPersonnelsMoveLogVOList = moveLogVOS.stream().filter(v -> ObjectUtil.isNotEmpty(v.getProcessingDate()) &&  v.getProcessingDate().after(actualStartDate)).collect(Collectors.toList());
            // 没有调动数据 且 岗位id一致 直接以当前时间进行计算岗龄
            if(CollUtil.isEmpty(ftbPersonnelsMoveLogVOList) && item.getPositionId().equals(latestRecord.getCurrPosition())){
                long betweenedDay = DateUtil.betweenDay(actualStartDate, new Date(), true);
                FtbPersonnlesJobTenureVO tenureVO = new FtbPersonnlesJobTenureVO();
                tenureVO.setUserId(item.getUserId());
                tenureVO.setPositionId(item.getPositionId());
                tenureVO.setJobTenure(Math.toIntExact(betweenedDay));
                return tenureVO;
            }else{
                // 调动数据不为空 调动前或者调动后的岗位一致,或者岗位没有发生变化
                List<FtbPersonnelsMoveLogVO> ftbPersonnelsMoveLogVOS = moveLogVOS.stream().filter(v -> v.getOldPosition().equals(item.getPositionId()) || v.getNewPosition().equals(item.getPositionId())).collect(Collectors.toList());
                if(CollUtil.isEmpty(ftbPersonnelsMoveLogVOS)){
                    return null;
                }
                ftbPersonnelsMoveLogVOS.sort(Comparator.comparing(FtbPersonnelsMoveLogVO::getProcessingDate));
                int size = ftbPersonnelsMoveLogVOS.size();

                // 累计岗龄天数
                long totalJobTenure = 0;

                // 如果第一条调动记录的调动前岗位等于入职岗位且等于查询岗位，则计算从入职到第一次调动的时间
                if(item.getPositionId().equals(latestRecord.getCurrPosition()) &&
                   item.getPositionId().equals(ftbPersonnelsMoveLogVOS.get(0).getOldPosition())){
                    long betweenedDay = DateUtil.betweenDay(actualStartDate, ftbPersonnelsMoveLogVOS.get(0).getProcessingDate(), true);
                    totalJobTenure += betweenedDay;
                }

                // 遍历调动记录，查找当前岗位的所有任职区间并累加
                for (int i = 0; i < size; i++) {
                    FtbPersonnelsMoveLogVO currentMove = ftbPersonnelsMoveLogVOS.get(i);
                    // 如果当前岗位是调动后的岗位，计算该段任职时间
                    if (item.getPositionId().equals(currentMove.getNewPosition())) {
                        if (i < size - 1) {
                            // 有下一次调动，计算到下一次调动的时间
                            FtbPersonnelsMoveLogVO nextMove = ftbPersonnelsMoveLogVOS.get(i + 1);
                            long betweenedDay = DateUtil.betweenDay(currentMove.getProcessingDate(), nextMove.getProcessingDate(), true);
                            totalJobTenure += betweenedDay;
                        } else {
                            // 是最后一条记录，计算到现在的时间
                            long betweenedDay = DateUtil.betweenDay(currentMove.getProcessingDate(), new Date(), true);
                            totalJobTenure += betweenedDay;
                        }
                    }
                }

                // 如果累计岗龄大于 0，返回结果
                if (totalJobTenure > 0) {
                    FtbPersonnlesJobTenureVO tenureVO = new FtbPersonnlesJobTenureVO();
                    tenureVO.setUserId(item.getUserId());
                    tenureVO.setPositionId(item.getPositionId());
                    tenureVO.setJobTenure(Math.toIntExact(totalJobTenure));
                    return tenureVO;
                }
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }



    @PostMapping("/get-personnel-change-info-batch")
    public Map<String, FtbPersonnelsChangeInfoVO> getPersonnelChangeInfoBatch(@RequestBody List<String> userIds) {
        return ftbPersonnelsStaffHomePageService.getBatchPersonnelChangeInfo(userIds);
    }
}
