# CbJournalImportLogServiceImpl.java

    package cloud.wconnect.finance.service.chargeback.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.service.UserInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.finance.entity.chargeback.CbJournalImportLog;
    import cloud.wconnect.finance.mapper.chargeback.CbJournalImportLogMapper;
    import cloud.wconnect.finance.pojo.dto.chargeback.journal.JournalImportLogDTO;
    import cloud.wconnect.finance.pojo.query.chargeback.JournalImportLogQuery;
    import cloud.wconnect.finance.service.chargeback.ICbJournalImportLogService;
    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.lang.Nullable;
    import org.springframework.stereotype.Service;

    import java.util.*;

    /**
     * <p>
     *  服务实现类
     * </p>
     *
     * @author yyt
     * @since 2023-08-22
     */
    @Service
    @DS("finance")
    public class CbJournalImportLogServiceImpl extends ServiceImpl<CbJournalImportLogMapper, CbJournalImportLog> implements ICbJournalImportLogService {

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

        /**
         * 校验存在
         *
         * @param id 日志 id
         * @return 日志
         * @author yyt
         * @date 2023/9/8
         */
        @Override
        public CbJournalImportLog checkExist(long id) {
            CbJournalImportLog importLog = getById(id);
            if (Objects.isNull(importLog)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the cbJournalImportLog is not found;id:" + id);
            }
            return importLog;
        }

        /**
         * 根据导入结果修改日志状态
         *
         * @param id           日志 id
         * @param importResult 导入状态
         * @param url          文件路径
         * @param userId       操作人
         * @author yyt
         * @date 2023/9/8
         */
        @Override
        public void updateLogStatus(long id, boolean importResult, String url, int userId) {
            CbJournalImportLog updateLog = new CbJournalImportLog();
            updateLog.setId(id).setUrl(url).setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                    ReportImportResultCons.IMPORT_RESULT_FAIL);

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

            updateById(updateLog);
        }

        /**
         * 插入导入记录
         *
         * @param propertyId 资产 id
         * @param theDate    指定日期
         * @param status     状态
         * @param path       文件路径
         * @param userId     操作人
         * @return 导入记录
         * @author yyt
         * @date 2023/10/31
         */
        @Override
        public CbJournalImportLog saveRecord(Integer propertyId, Long theDate, int status, @Nullable String path, int userId) {
            CbJournalImportLog importLog = new CbJournalImportLog()
                    .setPropertyId(propertyId)
                    .setTheDate(theDate)
                    .setStatus(status)
                    .setUrl(path)
                    .setCreateBy(userId)
                    .setCreatedTime(DateTimeUtils.nowTimestamp())
                    .setResolvedBy(BaseConstant.ZERO)
                    .setResolvedTime(BaseConstant.LONG_ZERO);
            save(importLog);
            return importLog;
        }

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

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

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

        /**
         * 查询导入记录
         *
         * @param tenantId   租户 id
         * @param propertyId 资产 id
         * @param query      查询条件
         * @return 导入记录
         * @author yyt
         * @date 2026/1/19
         **/
        @Override
        public ListPagedDTO<JournalImportLogDTO> listImportLogDTO(int tenantId, int propertyId, JournalImportLogQuery query) {
            long total;
            List<CbJournalImportLog> importLogs;
            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<CbJournalImportLog> page = listPage(propertyId, query);
                total = page.getTotal();
                importLogs = page.getRecords();
            } else {
                importLogs = list(propertyId, query);
                total = importLogs.size();
            }

            Map<Integer, String> userNameById = summaryUserName(tenantId, importLogs);

            return new ListPagedDTO<>(total, beanMapper.mapList(importLogs, JournalImportLogDTO.class,
                    item -> {
                        item.setCreateByName(userNameById.get(item.getCreateBy()));
                        item.setResolvedName(userNameById.get(item.getResolvedBy()));
                    }));
        }

        /**
         * 获取操作用户名称
         *
         * @param tenantId   租户 id
         * @param importLogs 导入记录
         * @return 用户名称
         * @author yyt
         * @date 2026/1/19
         **/
        private Map<Integer, String> summaryUserName(int tenantId, List<CbJournalImportLog> importLogs) {
            if (CollectionUtils.isNotEmpty(importLogs)) {
                Set<Integer> userIds = Sets.newHashSetWithExpectedSize(importLogs.size());
                importLogs.forEach(item -> {
                    userIds.add(item.getCreateBy());
                    if (item.getResolvedBy() > BaseConstant.ZERO) {
                        userIds.add(item.getResolvedBy());
                    }
                });
                return userInternalService.getNameMapByIds(tenantId, userIds);
            }
            return Collections.emptyMap();
        }

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

    }