# SalesImportLogServiceImpl.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.SalesImportLog;
    import cloud.wconnect.workperformance.mapper.mor.SalesImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.mor.sales.SalesImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.mor.sales.SalesImportLogQuery;
    import cloud.wconnect.workperformance.service.mor.ISalesImportLogService;
    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>
     * Monthly OT Report - Sales source 报告导入记录 服务实现类
     * </p>
     *
     * @author zc
     * @since 2024-06-01
     */
    @Service
    @DS("work_performance")
    public class SalesImportLogServiceImpl extends ServiceImpl<SalesImportLogMapper, SalesImportLog> implements ISalesImportLogService {

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

        /**
         * 获取报告导入记录
         *
         * @param tenantId   租户 id
         * @param propertyId 资产 id
         * @param query      查询条件
         * @return SalesImportLogDTO 集合
         * @author zc
         * @date 2024/6/1
         */
        @Override
        public ListPagedDTO<SalesImportLogDTO> list(int tenantId, int propertyId, SalesImportLogQuery query) {
            LambdaQueryWrapper<SalesImportLog> queryWrapper = new QueryWrapper<SalesImportLog>().lambda()
                    .eq(Objects.nonNull(query.getReportType()), SalesImportLog::getReportType, query.getReportType())
                    .eq(SalesImportLog::getPropertyId, propertyId)
                    .in(CollectionUtils.isNotEmpty(query.getStatus()),
                            SalesImportLog::getImportResult, query.getStatus())
                    .and(Objects.nonNull(query.getStartOperationDate()) && Objects.nonNull(query.getEndOperationDate()),
                            wrapper -> wrapper.between(SalesImportLog::getCreatedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate())
                                    .or().between(SalesImportLog::getResolvedTime,
                                            query.getStartOperationDate(), query.getEndOperationDate()))
                    .between(Objects.nonNull(query.getStartFromDataDate()) && Objects.nonNull(query.getStartToDataDate()),
                            SalesImportLog::getStartDate, query.getStartFromDataDate(), query.getStartToDataDate())
                    .between(Objects.nonNull(query.getEndFromDataDate()) && Objects.nonNull(query.getEndToDataDate()),
                            SalesImportLog::getEndDate, query.getEndFromDataDate(), query.getEndToDataDate());

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

        /**
         * 校验是否存在并返回对象
         *
         * @param id 记录 id
         * @return SalesImportLog
         * @author zc
         * @date 2024/6/1
         */
        @Override
        public SalesImportLog checkExist(long id) {
            SalesImportLog 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 2024/6/1
         */
        @Override
        public void checkBelong(int propertyId, SalesImportLog 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 propertyDTOList             资产集合
         * @param propertyId2DateRange        报告数据日期范围(yyyyMMdd)
         * @param reportType                  报告类型
         * @param importResult                报告导入结果
         * @param operatorId                  操作人 id
         * @param url                         S3 key
         * @param propertyId2DataUpdateResult 数据更新结果
         * @return 日志 id 集合
         * @author zc
         * @date 2024/6/3
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public List<Long> addBatch(List<PropertyDTO> propertyDTOList, Map<Integer, List<Long>> propertyId2DateRange,
                                   int reportType, int importResult, int operatorId, String url,
                                   Map<Integer, Integer> propertyId2DataUpdateResult) {
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            List<SalesImportLog> importLogList = Lists.newArrayList();
            propertyDTOList.forEach(propertyDTO -> {
                List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                if (CollectionUtils.isEmpty(dateRangeList)) {
                    return;
                }
                long theDate = Long.parseLong(DateTimeUtils.localDateToStr(DateTimeUtils.longToLocalDate(nowTimestamp,
                        propertyDTO.getTimezone()), BaseConstant.DATE_FORMAT_YYYYMMDD));
                importLogList.add(new SalesImportLog()
                        .setPropertyId(propertyDTO.getId())
                        .setReportType(reportType)
                        .setTheDate(theDate)
                        .setStartDate(dateRangeList.get(0))
                        .setEndDate(dateRangeList.get(1))
                        .setImportResult(importResult)
                        .setUrl(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(SalesImportLog::getId).toList();
        }

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

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

            ArrayList<SalesImportLog> updateBatchList = Lists.newArrayListWithCapacity(importLogs.size());

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