# TaImportLogServiceImpl.java

    package cloud.wconnect.finance.service.ta.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    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.finance.entity.ta.TaImportLog;
    import cloud.wconnect.finance.mapper.ta.TaImportLogMapper;
    import cloud.wconnect.finance.pojo.dto.ta.report.TaImportLogDTO;
    import cloud.wconnect.finance.pojo.query.ta.TaImportLogQuery;
    import cloud.wconnect.finance.service.ta.ITaImportLogService;
    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 org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.lang.Nullable;
    import org.springframework.stereotype.Service;

    import jakarta.annotation.Resource;
    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;

    /**
     * <p>
     * TA 报告导入日志 服务实现类
     * </p>
     *
     * @author zc
     * @since 2023-07-07
     */
    @Service
    @DS("finance")
    public class TaImportLogServiceImpl extends ServiceImpl<TaImportLogMapper, TaImportLog> implements ITaImportLogService {
        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 查询报告导入记录
         *
         * @param tenantId       租户 id
         * @param propertyId     资产 id
         * @param importLogQuery 查询条件
         * @return TaImportLogDTO 集合
         * @author zc
         * @date 2023/7/18
         */
        @Override
        public ListPagedDTO<TaImportLogDTO> list(int tenantId, int propertyId, TaImportLogQuery importLogQuery) {
            LambdaQueryWrapper<TaImportLog> queryWrapper = new QueryWrapper<TaImportLog>().lambda()
                    .eq(Objects.nonNull(importLogQuery.getReportType()), TaImportLog::getReportType, importLogQuery.getReportType())
                    .eq(TaImportLog::getPropertyId, propertyId)
                    .in(CollectionUtils.isNotEmpty(importLogQuery.getStatus()),
                            TaImportLog::getImportResult, importLogQuery.getStatus())
                    .and(Objects.nonNull(importLogQuery.getStartOperationDate()) && Objects.nonNull(importLogQuery.getEndOperationDate()),
                            wrapper -> wrapper.between(TaImportLog::getCreatedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate())
                                    .or().between(TaImportLog::getResolvedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate()))
                    .between(Objects.nonNull(importLogQuery.getStartDataDate()) && Objects.nonNull(importLogQuery.getEndDataDate()),
                            TaImportLog::getDataDate, importLogQuery.getStartDataDate(), importLogQuery.getEndDataDate());
            List<TaImportLog> importLogList;
            long total;
            if (Objects.nonNull(importLogQuery.getPage()) && Objects.nonNull(importLogQuery.getSize())) {
                Page<TaImportLog> page = page(new Page<>(importLogQuery.getPage(), importLogQuery.getSize()),
                        queryWrapper.orderByDesc(TaImportLog::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(tenantId, userIds);
            return new ListPagedDTO<>(total, beanMapper.mapList(importLogList,
                    TaImportLogDTO.class, (item, dto) -> {
                        dto.setCreatedByName(id2UserName.get(item.getCreatedBy()));
                        dto.setResolvedByName(id2UserName.get(item.getResolvedBy()));
                    }));
        }

        /**
         * 校验数据是否存在，并返回数据对象
         *
         * @param id 记录 id
         * @return TaCreditCardImportLog
         * @author zc
         * @date 2023/7/18
         */
        @Override
        public TaImportLog checkExist(long id) {
            TaImportLog 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 tenantId    租户 id
         * @param propertyId  资产 id
         * @param taImportLog 日志记录数据
         * @author zc
         * @date 2023/7/11
         */
        @Override
        public void checkBelong(int tenantId, int propertyId, TaImportLog taImportLog) {
            if (!taImportLog.getTenantId().equals(tenantId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The importLog does not belong to this tenant; tenantId:{0}; importLogId:{1}",
                                tenantId, taImportLog.getId()));
            }
            if (!taImportLog.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}; importLogId:{1}",
                                propertyId, taImportLog.getId()));
            }
        }

        /**
         * 根据处理结果更新导入日志
         *
         * @param importLogId  日志 id
         * @param handleResult 处理结果 true：成功 false：失败
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public void update(long importLogId, boolean handleResult, int operatorId, @Nullable String url) {
            TaImportLog importLog = getById(importLogId);
            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 tenantId      租户 id
         * @param propertyId    资产 id
         * @param reportType    报告类型
         * @param dataDate      数据日期
         * @param importResults 导入结果集合
         * @return TaImportLog 数量
         * @author zc
         * @date 2023/7/22
         */
        @Override
        public long count(int tenantId, int propertyId, @Nullable Integer reportType, @Nullable Long dataDate, List<Integer> importResults) {
            return count(new QueryWrapper<TaImportLog>().lambda()
                    .eq(TaImportLog::getTenantId, tenantId)
                    .eq(TaImportLog::getPropertyId, propertyId)
                    .eq(Objects.nonNull(reportType), TaImportLog::getReportType, reportType)
                    .eq(Objects.nonNull(dataDate), TaImportLog::getDataDate, dataDate)
                    .in(CollectionUtils.isNotEmpty(importResults), TaImportLog::getImportResult, importResults));
        }

        /**
         * 记录日志
         *
         * @param propertyDTO  资产
         * @param dataDate     数据日期
         * @param reportType   报告类型
         * @param importResult 导入结果(1:导入成功,2:导入失败)
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @return log id
         * @author zc
         * @date 2023/7/23
         */
        @Override
        public long add(PropertyDTO propertyDTO, long dataDate, int reportType, int importResult, int operatorId, @Nullable String url) {
            TaImportLog importLog = new TaImportLog()
                    .setTenantId(propertyDTO.getTenantId())
                    .setPropertyId(propertyDTO.getId())
                    .setReportType(reportType)
                    .setTheDate(DateTimeUtils.dateNowTimestamp(propertyDTO.getTimezone()))
                    .setDataDate(dataDate)
                    .setImportResult(importResult)
                    .setUrl(StringUtils.isNotBlank(url) ? url : "")
                    .setCreatedBy(operatorId)
                    .setCreatedTime(DateTimeUtils.nowTimestamp());
            save(importLog);
            return importLog.getId();
        }
    }