# HkEfficiencyImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.hkefficiency.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.hkefficiency.HkEfficiencyImportLog;
    import cloud.wconnect.workperformance.mapper.hkefficiency.HkEfficiencyImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.hkefficiency.HkEfficiencyImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.hkefficiency.HkEfficiencyImportLogQuery;
    import cloud.wconnect.workperformance.service.hkefficiency.IHkEfficiencyImportLogService;
    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 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 jakarta.annotation.Resource;

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

    /**
     * <p>
     * Housekeeping Efficiency 报告导入日志 服务实现类
     * </p>
     *
     * @author zc
     * @since 2023-03-31
     */
    @Service
    @DS("work_performance")
    public class HkEfficiencyImportLogServiceImpl extends ServiceImpl<HkEfficiencyImportLogMapper, HkEfficiencyImportLog> implements IHkEfficiencyImportLogService {
        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 批量新增日志
         *
         * @param propertyDTOList             资产集合
         * @param propertyId2DateRange        报告数据日期范围(yyyyMMdd)
         * @param reportType                  报告类型
         * @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 reportType, int importResult, int operatorId, @Nullable String url,
                                   Map<Integer, Integer> propertyId2DataUpdateResult) {
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            List<HkEfficiencyImportLog> 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 HkEfficiencyImportLog()
                        .setPropertyId(propertyDTO.getId())
                        .setReportType(reportType)
                        .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(HkEfficiencyImportLog::getId).toList();
        }

        /**
         * 新增日志
         *
         * @param propertyDTO  资产
         * @param fromDate     报告数据开始日期(yyyyMMdd)
         * @param toDate       报告数据结束日期(yyyyMMdd)
         * @param reportType   报告类型
         * @param importResult 报告导入结果
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @author zc
         * @date 2024/2/28
         */
        @Override
        public void add(PropertyDTO propertyDTO, long fromDate, long toDate,
                        int reportType, int importResult, int operatorId, @Nullable String url) {
            String timezone = propertyDTO.getTimezone();
            save(new HkEfficiencyImportLog()
                    .setPropertyId(propertyDTO.getId())
                    .setReportType(reportType)
                    .setTheDate(DateTimeUtils.dateNowTimestamp(timezone))
                    .setStartDate(DateTimeUtils.dateStrToEpochSecond(Long.valueOf(fromDate).toString(),
                            BaseConstant.DATE_FORMAT_YYYYMMDD, timezone))
                    .setEndDate(DateTimeUtils.dateStrToEpochSecond(Long.valueOf(toDate).toString(),
                            BaseConstant.DATE_FORMAT_YYYYMMDD, timezone))
                    .setImportResult(importResult)
                    .setUrl(StringUtils.isNotBlank(url) ? url : "")
                    .setCreatedBy(operatorId)
                    .setCreatedTime(DateTimeUtils.nowTimestamp())
                    .setResolvedBy(BaseConstant.ZERO)
                    .setResolvedTime(BaseConstant.LONG_ZERO));
        }

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

            // 是否修复中
            boolean isRepairing = importLogs.get(0).getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING;

            ArrayList<HkEfficiencyImportLog> updateList = Lists.newArrayListWithCapacity(importLogs.size());

            for (HkEfficiencyImportLog importLog : importLogs) {
                HkEfficiencyImportLog updateEntity = new HkEfficiencyImportLog();
                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));
                updateList.add(updateEntity);
            }

            updateBatchById(updateList);
        }

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

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

        /**
         * 校验日志是否存在
         *
         * @param id 日志 id
         * @return HousekeepingEfficiencyImportLog
         * @author zc
         * @date 2023/10/18
         */
        @Override
        public HkEfficiencyImportLog checkExist(long id) {
            HkEfficiencyImportLog 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, HkEfficiencyImportLog 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 id         id
         * @param operatorId 操作人 id
         * @author zc
         * @date 2023/3/22
         */
        @Override
        public void ignore(long id, int operatorId) {
            HkEfficiencyImportLog importLog = new HkEfficiencyImportLog();
            importLog.setId(id);
            importLog.setImportResult(ReportImportResultCons.IMPORT_RESULT_IGNORE);
            importLog.setResolvedBy(operatorId);
            importLog.setResolvedTime(DateTimeUtils.nowTimestamp());
            updateById(importLog);
        }

    }