# RevenueImportLogServiceImpl.java

    package cloud.wconnect.rateshop.service.revenue.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.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.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.mapper.revenue.RevenueImportLogMapper;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ImportLogDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ResolveExceptionDTO;
    import cloud.wconnect.rateshop.pojo.query.revenue.ImportLogQuery;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    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.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import jakarta.annotation.Nullable;

    import java.util.*;

    /**
     * <p>
     * 服务实现类
     * </p>
     *
     * @author yyt
     * @since 2023-10-26
     */
    @Service
    @DS("rate_shop")
    public class RevenueImportLogServiceImpl extends ServiceImpl<RevenueImportLogMapper, RevenueImportLog> implements IRevenueImportLogService {

        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private BeanMapper beanMapper;

        /**
         * 校验存在
         *
         * @param id 记录 id
         * @return 导入记录
         * @author yyt
         * @date 2023/10/30
         */
        @Override
        public RevenueImportLog checkExist(long id) {
            RevenueImportLog importLog = getById(id);
            if (Objects.isNull(importLog)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the revenueImportLog is not found;id:" + id);
            }
            return importLog;
        }

        /**
         * 修改状态
         *
         * @param id           记录 id
         * @param importResult 导入状态
         * @param url          文件路径
         * @param userId       操作人
         * @author yyt
         * @date 2023/10/30
         */
        @Override
        public void updateLogStatus(long id, boolean importResult, @Nullable String url, int userId) {
            RevenueImportLog updateLog = new RevenueImportLog();
            updateLog.setId(id).setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                    ReportImportResultCons.IMPORT_RESULT_FAIL);

            RevenueImportLog importLog = getById(id);
            if (importLog.getStatus() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                updateLog.setResolvedBy(importResult ? userId : BaseConstant.ZERO)
                        .setResolvedTime(importResult ? DateTimeUtils.nowTimestamp() : BaseConstant.LONG_ZERO);
            }

            updateLog.setUrl(url);
            updateById(updateLog);
        }

        /**
         * 生成进行中导入记录
         *
         * @param propertyId          资产 id
         * @param resolveExceptionDTO 选择条件
         * @param status              状态
         * @param key                 文件路径
         * @param userId              操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/14
         */
        @Override
        public RevenueImportLog saveInProgressRecord(Integer propertyId, ResolveExceptionDTO resolveExceptionDTO, int status, String key, int userId) {
            RevenueImportLog importLog = new RevenueImportLog().setPropertyId(propertyId)
                    .setReportType(resolveExceptionDTO.getFileType())
                    .setTheDate(Objects.isNull(resolveExceptionDTO.getDate()) ? BaseConstant.LONG_ZERO : resolveExceptionDTO.getDate())
                    .setStartDate(resolveExceptionDTO.getStartDate())
                    .setEndDate(resolveExceptionDTO.getEndDate())
                    .setStatus(status)
                    .setUrl(key)
                    .setCreatedBy(userId).setCreatedTime(DateTimeUtils.nowTimestamp())
                    .setResolvedBy(BaseConstant.ZERO).setResolvedTime(BaseConstant.LONG_ZERO);
            save(importLog);
            return importLog;
        }

        /**
         * 添加记录
         *
         * @param propertyId 资产 id
         * @param type       报告类型
         * @param theDate    指定日期
         * @param starDate   开始日期
         * @param endDate    结束日期
         * @param status     状态
         * @param path       文件路径
         * @param userId     操作人
         * @author yyt
         * @date 2024/6/5
         **/
        @Override
        public void saveRecord(Integer propertyId, int type, Long theDate, Long starDate, Long endDate, int status,
                               @Nullable String path, int userId) {
            RevenueImportLog importLog = new RevenueImportLog().setPropertyId(propertyId)
                    .setReportType(type).setTheDate(theDate)
                    .setStartDate(starDate).setEndDate(endDate).setUrl(path)
                    .setStatus(status).setCreatedBy(userId).setCreatedTime(DateTimeUtils.nowTimestamp())
                    .setResolvedBy(BaseConstant.ZERO).setResolvedTime(BaseConstant.LONG_ZERO);
            save(importLog);
        }

        /**
         * 处理保存系统导入记录
         *
         * @param property   资产
         * @param reportType 报告类型
         * @param theDate    报告类型
         * @param startDate  开始日期
         * @param endDate    结束日期
         * @param status     状态
         * @param url        文件路径
         * @author yyt
         * @date 2023/11/1
         */
        @Override
        public void handleSaveSystemImportRecord(PropertyDTO property, int reportType, Long theDate, Long startDate,
                                                 Long endDate, Integer status, @Nullable String url) {
            if (status == ReportImportResultCons.IMPORT_RESULT_MISSED) {
                // 报告缺失的异常，如果已经存在，则不插入
                RevenueImportLog importLog = getOne(new QueryWrapper<RevenueImportLog>().lambda()
                        .eq(RevenueImportLog::getPropertyId, property.getId())
                        .eq(RevenueImportLog::getTheDate, theDate).eq(RevenueImportLog::getReportType, reportType)
                        .eq(RevenueImportLog::getStartDate, startDate).eq(RevenueImportLog::getEndDate, endDate)
                        .eq(RevenueImportLog::getStatus, ReportImportResultCons.IMPORT_RESULT_MISSED)
                        .eq(RevenueImportLog::getCreatedBy, BaseConstant.ZERO).last("limit 1"));
                if (Objects.nonNull(importLog)) {
                    return;
                }
            }

            long now = DateTimeUtils.nowTimestamp();
            save(new RevenueImportLog().setPropertyId(property.getId()).setTheDate(theDate).setReportType(reportType)
                    .setStartDate(startDate).setEndDate(endDate).setStatus(status)
                    .setCreatedBy(BaseConstant.ZERO).setCreatedTime(now)
                    .setResolvedBy(BaseConstant.ZERO).setResolvedTime(BaseConstant.LONG_ZERO)
                    .setUrl(url));
        }

        /**
         * 分页查询数据
         *
         * @param propertyId 资产 id
         * @param query      查询条件
         * @return 导入记录
         * @author yyt
         * @date 2024/12/2
         **/
        @Override
        public Page<RevenueImportLog> listPage(Integer propertyId, ImportLogQuery query) {
            return page(new Page<>(query.getPage(), query.getSize()), packageSql(propertyId, query).orderByDesc(RevenueImportLog::getId));
        }

        /**
         * 查询数据
         *
         * @param propertyId 资产 id
         * @param query      查询条件
         * @return 导入记录
         * @author yyt
         * @date 2024/12/2
         **/
        @Override
        public List<RevenueImportLog> list(Integer propertyId, ImportLogQuery query) {
            return list(packageSql(propertyId, query));
        }

        /**
         * 封装查询 sql
         *
         * @param propertyId 资产 id
         * @param query      查询条件
         * @return sql
         * @author yyt
         * @date 2024/12/2
         **/
        private LambdaQueryWrapper<RevenueImportLog> packageSql(Integer propertyId, ImportLogQuery query) {
            return new QueryWrapper<RevenueImportLog>().lambda()
                    .eq(RevenueImportLog::getPropertyId, propertyId)
                    .in(CollectionUtils.isNotEmpty(query.getStatus()), RevenueImportLog::getStatus, query.getStatus())
                    .in(RevenueImportLog::getReportType, query.getReportTypes())
                    .between(Objects.nonNull(query.getStartDate()) && Objects.nonNull(query.getEndDate()),
                            RevenueImportLog::getTheDate, query.getStartDate(), query.getEndDate())
                    .nested(Objects.nonNull(query.getStartOperationDate()) && Objects.nonNull(query.getEndOperationDate()),
                            sql -> {
                                sql.between(RevenueImportLog::getCreatedTime, query.getStartOperationDate(), query.getEndOperationDate())
                                        .or()
                                        .between(RevenueImportLog::getResolvedTime, query.getStartOperationDate(), query.getEndOperationDate());
                            });
        }

        /**
         * 获取导入记录
         *
         * @param propertyDTO 资产
         * @param query       查询条件
         * @return 导入记录
         * @author yyt
         * @date 2024/12/2
         **/
        @Override
        public ListPagedDTO<ImportLogDTO> listImportLog(PropertyDTO propertyDTO, ImportLogQuery query) {
            Integer propertyId = propertyDTO.getId();
            long total;
            List<RevenueImportLog> importLogs;
            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<RevenueImportLog> page = listPage(propertyId, query);
                total = page.getTotal();
                importLogs = page.getRecords();
            } else {
                importLogs = list(propertyId, query);
                total = importLogs.size();
            }

            Map<Integer, String> userNameById = Collections.emptyMap();
            if (CollectionUtils.isNotEmpty(importLogs)) {
                Set<Integer> userIds = Sets.newHashSetWithExpectedSize(importLogs.size());
                importLogs.forEach(item -> {
                    userIds.add(item.getCreatedBy());
                    if (item.getResolvedBy() > BaseConstant.ZERO) {
                        userIds.add(item.getResolvedBy());
                    }
                });
                userNameById = userInternalService.getNameMapByIds(propertyDTO.getTenantId(), userIds);
            }

            Map<Integer, String> finalUserNameById = userNameById;
            return new ListPagedDTO<>(total, beanMapper.mapList(importLogs, ImportLogDTO.class,
                    item -> {
                        item.setCreatedByName(finalUserNameById.get(item.getCreatedBy()));
                        item.setResolvedByName(finalUserNameById.get(item.getResolvedBy()));
                    }));
        }

        /**
         * 更新导入记录状态
         *
         * @param id     导入记录 id
         * @param status 状态
         * @param userId 操作人
         * @author yyt
         * @date 2026/1/19
         **/
        @Override
        public void updateLogStatus(long id, int status, int userId) {
            RevenueImportLog updateContent = new RevenueImportLog();
            updateContent.setId(id);
            updateContent.setResolvedBy(userId);
            updateContent.setResolvedTime(DateTimeUtils.nowTimestamp());
            updateContent.setStatus(ReportImportResultCons.IMPORT_RESULT_IGNORE);
            updateById(updateContent);
        }

    }