# DbReportImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.database.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.database.DbReportImportLog;
    import cloud.wconnect.workperformance.mapper.database.DbReportImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.database.report.DbReportImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.database.DbReportImportLogQuery;
    import cloud.wconnect.workperformance.service.database.IDbReportImportLogService;
    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.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.google.common.collect.Sets;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.stereotype.Service;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;

    /**
     * <p>
     * Database report import log 服务实现类
     * </p>
     *
     * @author zc
     * @since 2025-12-02
     */
    @Service
    @DS("database")
    public class DbReportImportLogServiceImpl extends ServiceImpl<DbReportImportLogMapper, DbReportImportLog> implements IDbReportImportLogService {

        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 保存导入记录
         *
         * @param propertyDTO  资产DTO
         * @param businessDate 营业日期(yyyyMMdd)
         * @param dateRange    日期范围
         * @param key          S3 key
         * @param importResult 导入结果
         * @param reportType   报告类型
         * @param operatorId   操作人 id
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void save(PropertyDTO propertyDTO, long businessDate, List<Long> dateRange, String key, int importResult, int reportType, int operatorId) {
            DbReportImportLog importLog = new DbReportImportLog();
            importLog.setPropertyId(propertyDTO.getId());
            importLog.setReportType(reportType);
            importLog.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(LocalDate.now(ZoneId.of(propertyDTO.getTimezone())),
                    BaseConstant.DATE_FORMAT_YYYYMMDD)));
            importLog.setBusinessDate(businessDate);
            importLog.setReportType(reportType);
            importLog.setStartDate(dateRange.get(0));
            importLog.setEndDate(dateRange.get(1));
            importLog.setUrl(key);
            importLog.setCreatedBy(operatorId);
            importLog.setCreatedTime(DateTimeUtils.nowTimestamp());
            importLog.setResolvedBy(0);
            importLog.setResolvedTime(0L);
            importLog.setImportResult(importResult);
            save(importLog);
        }

        /**
         * 获取报告导入记录
         *
         * @param propertyDTO 资产
         * @param query       查询条件
         * @return DbReportImportLogDTO 集合
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public ListPagedDTO<DbReportImportLogDTO> list(PropertyDTO propertyDTO, DbReportImportLogQuery query) {
            LambdaQueryWrapper<DbReportImportLog> queryWrapper = new QueryWrapper<DbReportImportLog>().lambda()
                    .eq(DbReportImportLog::getPropertyId, propertyDTO.getId())
                    .in(DbReportImportLog::getReportType, query.getReportType())
                    .in(CollectionUtils.isNotEmpty(query.getStatus()),
                            DbReportImportLog::getImportResult, query.getStatus())
                    .and(Objects.nonNull(query.getStartOperationDate()) && Objects.nonNull(query.getEndOperationDate()),
                            wrapper -> wrapper.between(DbReportImportLog::getCreatedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate())
                                    .or().between(DbReportImportLog::getResolvedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate()))
                    .between(Objects.nonNull(query.getStartBusinessDate()) && Objects.nonNull(query.getEndBusinessDate()),
                            DbReportImportLog::getBusinessDate, query.getStartBusinessDate(), query.getEndBusinessDate())
                    .between(Objects.nonNull(query.getStartFromDataDate()) && Objects.nonNull(query.getStartToDataDate()),
                            DbReportImportLog::getStartDate, query.getStartFromDataDate(), query.getStartToDataDate())
                    .between(Objects.nonNull(query.getEndFromDataDate()) && Objects.nonNull(query.getEndToDataDate()),
                            DbReportImportLog::getEndDate, query.getEndFromDataDate(), query.getEndToDataDate());

            List<DbReportImportLog> importLogList;
            long total;
            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<DbReportImportLog> page = page(new Page<>(query.getPage(), query.getSize()),
                        queryWrapper.orderByDesc(DbReportImportLog::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> userId2UserName = userInternalService.getNameMapByIds(propertyDTO.getTenantId(), userIds);
            return new ListPagedDTO<>(total, beanMapper.mapList(importLogList, DbReportImportLogDTO.class,
                    (item, dto) -> {
                        dto.setCreatedByName(userId2UserName.get(item.getCreatedBy()));
                        dto.setResolvedByName(userId2UserName.get(item.getResolvedBy()));
                    })
            );
        }

        /**
         * 校验是否存在并返回对象
         *
         * @param id 记录 id
         * @return DbReportImportLog
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public DbReportImportLog checkExist(long id) {
            DbReportImportLog importLog = getById(id);
            if (Objects.isNull(importLog)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The import log is not found, id = " + id);
            }
            return importLog;
        }

        /**
         * 校验数据归属
         *
         * @param propertyId 资产 id
         * @param importLog  记录
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void checkBelong(int propertyId, DbReportImportLog importLog) {
            if (importLog.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The import log is not belong to current property, logId:{0}, " +
                                "currentPropertyId:{1}", importLog.getId(), propertyId));
            }
        }

        /**
         * 更新记录
         *
         * @param logId        记录 id
         * @param operatorId   操作人 id
         * @param url          报告 url
         * @param handleResult 处理结果
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void update(long logId, int operatorId, String url, boolean handleResult) {
            DbReportImportLog importLog = getById(logId);
            if (importLog.getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING
                    && handleResult) {
                importLog.setResolvedBy(operatorId);
                importLog.setResolvedTime(DateTimeUtils.nowTimestamp());
            }
            importLog.setUrl(url);
            importLog.setImportResult(handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS
                    : ReportImportResultCons.IMPORT_RESULT_FAIL);
            updateById(importLog);
        }

        /**
         * 忽略异常的记录
         *
         * @param importLog  记录
         * @param operatorId 操作人 id
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void ignore(DbReportImportLog importLog, int operatorId) {
            updateById(new DbReportImportLog()
                    .setId(importLog.getId())
                    .setImportResult(ReportImportResultCons.IMPORT_RESULT_IGNORE)
                    .setResolvedBy(operatorId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }

        /**
         * 保存处理中的记录
         *
         * @param propertyDTO  资产
         * @param reportType   报告类型
         * @param businessDate 营业日期（yyyyMMdd）
         * @param dateRange    报告数据范围（yyyyMMdd）
         * @param operatorId   操作人 id
         * @return DbReportImportLog
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public DbReportImportLog saveInProgress(PropertyDTO propertyDTO, int reportType, long businessDate, List<Long> dateRange, int operatorId) {
            DbReportImportLog importLog = new DbReportImportLog();
            importLog.setPropertyId(propertyDTO.getId());
            importLog.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(LocalDate.now(ZoneId.of(propertyDTO.getTimezone())),
                    BaseConstant.DATE_FORMAT_YYYYMMDD)));
            importLog.setReportType(reportType);
            importLog.setBusinessDate(businessDate);
            importLog.setStartDate(dateRange.get(0));
            importLog.setEndDate(dateRange.get(1));
            importLog.setCreatedBy(operatorId);
            importLog.setCreatedTime(DateTimeUtils.nowTimestamp());
            importLog.setResolvedBy(0);
            importLog.setResolvedTime(0L);
            importLog.setImportResult(ReportImportResultCons.IMPORT_IN_PROGRESS);

            save(importLog);
            return importLog;
        }

        /**
         * 自动解决
         *
         * @param logId        记录 id
         * @param handleResult true:成功，false:失败
         * @param operatorId   操作人 id
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void autoSolve(long logId, boolean handleResult, int operatorId) {
            updateById(new DbReportImportLog().setId(logId)
                    .setImportResult(handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS
                            : ReportImportResultCons.IMPORT_RESULT_FAIL)
                    .setResolvedBy(operatorId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }
    }