# OperStatisImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.sva.operatingstatistics.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.sva.operatingstatistics.OperStatisImportLog;
    import cloud.wconnect.workperformance.mapper.sva.operatingstatistics.OperStatisImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.sva.operatingstatistics.OperatingStatisticsImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.ImportLogQuery;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperStatisImportLogService;
    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.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-03-17
     */
    @Service
    @DS("work_performance")
    public class OperStatisImportLogServiceImpl extends ServiceImpl<OperStatisImportLogMapper, OperStatisImportLog> implements IOperStatisImportLogService {
        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 根据报告数据日期获取导入记录数量
         *
         * @param propertyId   资产 id
         * @param theDate      报告数据日期
         * @param resultStatus 导入结果
         * @return 导入记录数量
         * @author zc
         * @date 2023/10/2
         */
        @Override
        public long count(int propertyId, long theDate, @Nullable Integer resultStatus) {
            return count(new QueryWrapper<OperStatisImportLog>().lambda()
                    .eq(OperStatisImportLog::getTheDate, theDate)
                    .eq(OperStatisImportLog::getPropertyId, propertyId)
                    .eq(Objects.nonNull(resultStatus), OperStatisImportLog::getImportResult, resultStatus));
        }

        /**
         * 查询报告导入记录
         *
         * @param propertyDTO 资产
         * @param query       查询条件
         * @return OperatingStatisticsImportLogDTO 集合
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public ListPagedDTO<OperatingStatisticsImportLogDTO> list(PropertyDTO propertyDTO, ImportLogQuery query) {
            LambdaQueryWrapper<OperStatisImportLog> queryWrapper = new QueryWrapper<OperStatisImportLog>().lambda()
                    .eq(OperStatisImportLog::getPropertyId, propertyDTO.getId())
                    .in(CollectionUtils.isNotEmpty(query.getStatus()),
                            OperStatisImportLog::getImportResult, query.getStatus())
                    .and(Objects.nonNull(query.getStartOperationDate()) && Objects.nonNull(query.getEndOperationDate()),
                            wrapper -> wrapper.between(OperStatisImportLog::getCreatedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate())
                                    .or().between(OperStatisImportLog::getResolvedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate()))
                    .between(Objects.nonNull(query.getStartFromDataDate()) && Objects.nonNull(query.getStartToDataDate()),
                            OperStatisImportLog::getStartDate, query.getStartFromDataDate(), query.getStartToDataDate())
                    .between(Objects.nonNull(query.getEndFromDataDate()) && Objects.nonNull(query.getEndToDataDate()),
                            OperStatisImportLog::getEndDate, query.getEndFromDataDate(), query.getEndToDataDate());

            List<OperStatisImportLog> importLogList;
            long total;
            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<OperStatisImportLog> page = page(new Page<>(query.getPage(), query.getSize()),
                        queryWrapper.orderByDesc(OperStatisImportLog::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,
                    OperatingStatisticsImportLogDTO.class, (item, dto) -> {
                        dto.setCreatedByName(id2UserName.get(item.getCreatedBy()));
                        dto.setResolvedByName(id2UserName.get(item.getResolvedBy()));
                    }));
        }

        /**
         * 忽略异常记录
         *
         * @param id         异常记录 id
         * @param operatorId 操作人 id
         * @author zc
         * @date 2023/10/20
         */
        @Override
        public void ignore(long id, int operatorId) {
            updateById(new OperStatisImportLog()
                    .setId(id)
                    .setImportResult(ReportImportResultCons.IMPORT_RESULT_IGNORE)
                    .setResolvedBy(operatorId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }

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

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

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

            // 当前批量更新的日志，是否修复中
            boolean isRepairing = importLogs.get(0).getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING;

            ArrayList<OperStatisImportLog> updateBatchList = Lists.newArrayListWithCapacity(importLogs.size());
            for (OperStatisImportLog importLog : importLogs) {
                OperStatisImportLog updateEntity = new OperStatisImportLog();
                updateEntity.setId(importLog.getId());
                updateEntity.setUrl(StringUtils.isNotBlank(url) ? url : "");
                updateEntity.setImportResult(handleResult ?
                        ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL);
                if(isRepairing && handleResult){
                    updateEntity.setResolvedBy(operatorId);
                    updateEntity.setResolvedTime(DateTimeUtils.nowTimestamp());
                }
                updateEntity.setDataUpdateResult(propertyId2DataUpdateResult.getOrDefault(importLog.getPropertyId(), BaseConstant.ZERO));
                updateBatchList.add(updateEntity);
            }

            updateBatchById(updateBatchList);
        }

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

        /**
         * 校验日志归属
         *
         * @param propertyId 资产 id
         * @param importLog  日志
         * @author zc
         * @date 2023/10/18
         */
        @Override
        public void checkBelong(int propertyId, OperStatisImportLog 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()));
            }
        }
    }