# OvertimeImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.mor.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.ListPagedDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.workperformance.entity.mor.OvertimeImportLog;
    import cloud.wconnect.workperformance.mapper.mor.OvertimeImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.mor.overtime.MorImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.mor.overtime.OvertimeImportLogQuery;
    import cloud.wconnect.workperformance.service.mor.IOvertimeImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Sets;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.lang.Nullable;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.text.MessageFormat;
    import java.util.*;

    /**
     * <p>
     * 加班信息导入日志 服务实现类
     * </p>
     *
     * @author zc
     * @since 2023-04-01
     */
    @Service
    @DS("work_performance")
    public class OvertimeImportLogServiceImpl extends ServiceImpl<OvertimeImportLogMapper, OvertimeImportLog> implements IOvertimeImportLogService {
        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 校验日志是否存在
         *
         * @param id 日志 id
         * @return 日志
         * @author zc
         * @date 2023/4/1
         */
        @Override
        public OvertimeImportLog checkExist(long id) {
            OvertimeImportLog importLog = getById(id);
            if (Objects.isNull(importLog)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The log is not found by this id; id: " + id);
            }
            return importLog;
        }

        /**
         * 忽略指定的报告异常记录
         *
         * @param id         异常记录 id
         * @param operatorId 操作人 id
         * @author zc
         * @date 2023/4/1
         */
        @Override
        public void ignore(long id, int operatorId) {
            updateById(OvertimeImportLog.builder()
                    .id(id)
                    .importResult(ReportImportResultCons.IMPORT_RESULT_IGNORE)
                    .resolvedBy(operatorId)
                    .resolvedTime(DateTimeUtils.nowTimestamp())
                    .build());
        }

        /**
         * 校验归属
         *
         * @param propertyId 资产 id
         * @param importLog  导入记录
         * @author zc
         * @date 2023/10/20
         */
        @Override
        public void checkBelong(int propertyId, OvertimeImportLog importLog) {
            if (!importLog.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The importLog does not belong to this property; propertyId:{0}; importLogPropertyId:{1}",
                                propertyId, importLog.getPropertyId()));
            }
        }

        /**
         * 查询报告导入记录
         *
         * @param propertyDTO 资产
         * @param query       查询条件
         * @return MorImportLogDTO 集合
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public ListPagedDTO<MorImportLogDTO> list(PropertyDTO propertyDTO, OvertimeImportLogQuery query) {
            LambdaQueryWrapper<OvertimeImportLog> queryWrapper = new QueryWrapper<OvertimeImportLog>().lambda()
                    .eq(OvertimeImportLog::getPropertyId, propertyDTO.getId())
                    .eq(Objects.nonNull(query.getReportType()),
                            OvertimeImportLog::getReportType, query.getReportType())
                    .in(CollectionUtils.isNotEmpty(query.getStatus()),
                            OvertimeImportLog::getImportResult, query.getStatus())
                    .and(Objects.nonNull(query.getStartOperationDate()) && Objects.nonNull(query.getEndOperationDate()),
                            wrapper -> wrapper.between(OvertimeImportLog::getCreatedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate())
                                    .or().between(OvertimeImportLog::getResolvedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate()))
                    .between(Objects.nonNull(query.getStartFromDataDate()) && Objects.nonNull(query.getStartToDataDate()),
                            OvertimeImportLog::getStartDate, query.getStartFromDataDate(), query.getStartToDataDate())
                    .between(Objects.nonNull(query.getEndFromDataDate()) && Objects.nonNull(query.getEndToDataDate()),
                            OvertimeImportLog::getEndDate, query.getEndFromDataDate(), query.getEndToDataDate());
            List<OvertimeImportLog> importLogList;
            long total;
            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<OvertimeImportLog> page = page(new Page<>(query.getPage(), query.getSize()),
                        queryWrapper.orderByDesc(OvertimeImportLog::getId));
                importLogList = page.getRecords();
                total = page.getTotal();
            } else {
                importLogList = list(queryWrapper);
                total = importLogList.size();
            }
            if (CollectionUtils.isEmpty(importLogList)) {
                return new ListPagedDTO<>();
            }

            Set<Integer> userIds = Sets.newHashSet();
            importLogList.forEach(item -> {
                userIds.add(item.getCreatedBy());
                userIds.add(item.getResolvedBy());
            });
            Map<Integer, String> id2UserName = userInternalService.getNameMapByIds(propertyDTO.getTenantId(), userIds);
            return new ListPagedDTO<>(total, beanMapper.mapList(importLogList,
                    MorImportLogDTO.class, (item, dto) -> {
                        dto.setCreatedByName(id2UserName.get(item.getCreatedBy()));
                        dto.setResolvedByName(id2UserName.get(item.getResolvedBy()));
                    }));
        }

        /**
         * 批量新增日志
         *
         * @param propertyDTOList      资产集合
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param reportType           报告类型
         * @param importResult         报告导入结果
         * @param operatorId           操作人 id
         * @param url                  S3 key
         * @return 日志 id 集合
         * @author zc
         * @date 2025/3/16
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public List<Long> addBatch(List<PropertyDTO> propertyDTOList, Map<Integer, List<Long>> propertyId2DateRange,
                                   int reportType, int importResult, int operatorId, @Nullable String url) {
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            List<OvertimeImportLog> importLogList = Lists.newArrayList();
            propertyDTOList.forEach(propertyDTO -> {
                List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                importLogList.add(new OvertimeImportLog()
                        .setPropertyId(propertyDTO.getId())
                        .setReportType(reportType)
                        .setTheDate(Long.parseLong(DateTimeUtils.dateNowStr(propertyDTO.getTimezone(),
                                BaseConstant.DATE_FORMAT_YYYYMMDD)))
                        .setStartDate(CollectionUtils.isEmpty(dateRangeList) ? null : dateRangeList.get(0))
                        .setEndDate(CollectionUtils.isEmpty(dateRangeList) ? null : dateRangeList.get(1))
                        .setImportResult(importResult)
                        .setUrl(StringUtils.isNotBlank(url) ? url : "")
                        .setCreatedBy(operatorId)
                        .setCreatedTime(nowTimestamp)
                        .setResolvedBy(BaseConstant.ZERO)
                        .setResolvedTime(BaseConstant.LONG_ZERO));
            });
            saveBatch(importLogList);

            return importLogList.stream().map(OvertimeImportLog::getId).toList();
        }

        /**
         * 根据处理结果更新导入日志
         *
         * @param importLogIds 日志 id 集合
         * @param handleResult 处理结果 true：成功 false：失败
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public void updateBatch(List<Long> importLogIds, boolean handleResult, int operatorId, @Nullable String url) {
            // 获取日志并判断导入状态
            List<OvertimeImportLog> importLogs = listByIds(importLogIds);
            if (CollectionUtils.isEmpty(importLogs)) {
                return;
            }

            LambdaUpdateWrapper<OvertimeImportLog> updateWrapper = new UpdateWrapper<OvertimeImportLog>().lambda()
                    .in(OvertimeImportLog::getId, importLogIds)
                    .set(StringUtils.isNotBlank(url), OvertimeImportLog::getUrl, url)
                    .set(OvertimeImportLog::getImportResult, handleResult ?
                            ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL);
            if (importLogs.get(0).getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING
                    && handleResult) {
                updateWrapper.set(OvertimeImportLog::getResolvedBy, operatorId)
                        .set(OvertimeImportLog::getResolvedTime, DateTimeUtils.nowTimestamp());
            }
            update(updateWrapper);
        }

        /**
         * 新增日志
         *
         * @param propertyDTO  资产
         * @param startDate    报告数据开始日期(yyyyMMdd)
         * @param endDate      报告数据结束日期(yyyyMMdd)
         * @param reportType   报告类型
         * @param importResult 报告导入结果
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @author zc
         * @date 2025/3/15
         */
        @Override
        public void add(PropertyDTO propertyDTO, @Nullable Long startDate, @Nullable Long endDate,
                        int reportType, int importResult, int operatorId, @Nullable String url) {
            save(new OvertimeImportLog()
                    .setPropertyId(propertyDTO.getId())
                    .setReportType(reportType)
                    .setTheDate(Long.parseLong(DateTimeUtils.dateNowStr(propertyDTO.getTimezone(),
                            BaseConstant.DATE_FORMAT_YYYYMMDD)))
                    .setStartDate(startDate)
                    .setEndDate(endDate)
                    .setImportResult(importResult)
                    .setUrl(StringUtils.isNotBlank(url) ? url : "")
                    .setCreatedBy(operatorId)
                    .setCreatedTime(DateTimeUtils.nowTimestamp())
                    .setResolvedBy(BaseConstant.ZERO)
                    .setResolvedTime(BaseConstant.LONG_ZERO));
        }
    }