# AttendanceEmpImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.sva.employees.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.sva.employees.AttendanceEmpImportLog;
    import cloud.wconnect.workperformance.mapper.sva.employees.AttendanceEmpImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.sva.employee.SvaEmployeesImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.ImportLogQuery;
    import cloud.wconnect.workperformance.service.sva.employees.IAttendanceEmpImportLogService;
    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.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.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;

    /**
     * <p>
     * 服务实现类：考勤系统员工报告导入日志
     * </p>
     *
     * @author zc
     * @since 2023-02-21
     */
    @Service
    @DS("work_performance")
    public class AttendanceEmpImportLogServiceImpl extends ServiceImpl<AttendanceEmpImportLogMapper, AttendanceEmpImportLog> implements IAttendanceEmpImportLogService {
        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 根据报告数据日期获取导入记录数量
         *
         * @param propertyId   property id
         * @param theDate      报告数据日期
         * @param resultStatus 报告导入结果
         * @return Employee报告记录数量
         * @author zc
         * @date 2023/2/21
         */
        @Override
        public long count(int propertyId, long theDate, @Nullable Integer resultStatus) {
            return count(new QueryWrapper<AttendanceEmpImportLog>().lambda()
                    .eq(AttendanceEmpImportLog::getPropertyId, propertyId)
                    .eq(AttendanceEmpImportLog::getTheDate, theDate)
                    .eq(Objects.nonNull(resultStatus), AttendanceEmpImportLog::getImportResult, resultStatus));
        }

        /**
         * 忽略指定的报告异常记录
         *
         * @param id         id
         * @param operatorId 操作人 id
         * @author zc
         * @date 2023/3/27
         */
        @Override
        public void ignore(long id, int operatorId) {
            updateById(new AttendanceEmpImportLog()
                    .setId(id)
                    .setImportResult(ReportImportResultCons.IMPORT_RESULT_IGNORE)
                    .setResolvedBy(operatorId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }

        /**
         * 批量新增日志
         *
         * @param propertyDTOList 资产集合
         * @param importResult    报告导入结果
         * @param operatorId      操作人 id
         * @param url             S3 key
         * @return 日志 id 集合
         * @author zc
         * @date 2024/8/19
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public List<Long> addBatch(List<PropertyDTO> propertyDTOList, int importResult, int operatorId, @Nullable String url) {
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            List<AttendanceEmpImportLog> importLogList = propertyDTOList.stream()
                    .map(item -> new AttendanceEmpImportLog()
                            .setPropertyId(item.getId())
                            .setTheDate(DateTimeUtils.dateNowTimestamp(item.getTimezone()))
                            .setImportResult(importResult)
                            .setUrl(StringUtils.isNotBlank(url) ? url : "")
                            .setCreatedBy(operatorId)
                            .setCreatedTime(nowTimestamp)
                            .setResolvedBy(BaseConstant.ZERO)
                            .setResolvedTime(BaseConstant.LONG_ZERO)).toList();
            saveBatch(importLogList);

            return importLogList.stream().map(AttendanceEmpImportLog::getId).toList();
        }

        /**
         * 新增日志
         *
         * @param propertyDTO  资产
         * @param importResult 报告导入结果
         * @param operatorId   操作人 id
         * @param url          S3 key
         * @author zc
         * @date 2023/10/18
         */
        @Override
        public void add(PropertyDTO propertyDTO, int importResult, int operatorId, @Nullable String url) {
            save(new AttendanceEmpImportLog()
                    .setPropertyId(propertyDTO.getId())
                    .setTheDate(DateTimeUtils.dateNowTimestamp(propertyDTO.getTimezone()))
                    .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
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public void updateBatch(List<Long> importLogIds, boolean handleResult, int operatorId, @Nullable String url) {
            // 获取日志并判断导入状态
            List<AttendanceEmpImportLog> importLogs = listByIds(importLogIds);
            if (CollectionUtils.isEmpty(importLogs)) {
                return;
            }

            LambdaUpdateWrapper<AttendanceEmpImportLog> updateWrapper = new UpdateWrapper<AttendanceEmpImportLog>().lambda()
                    .in(AttendanceEmpImportLog::getId, importLogIds)
                    .set(StringUtils.isNotBlank(url), AttendanceEmpImportLog::getUrl, url)
                    .set(AttendanceEmpImportLog::getImportResult, handleResult ?
                            ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL);
            if (importLogs.get(0).getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING
                    && handleResult) {
                updateWrapper.set(AttendanceEmpImportLog::getResolvedBy, operatorId)
                        .set(AttendanceEmpImportLog::getResolvedTime, DateTimeUtils.nowTimestamp());
            }
            update(updateWrapper);
        }

        /**
         * 校验日志是否存在
         *
         * @param id 日志 id
         * @return AttendanceEmpImportLog
         * @author zc
         * @date 2023/10/18
         */
        @Override
        public AttendanceEmpImportLog checkExist(long id) {
            AttendanceEmpImportLog 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, AttendanceEmpImportLog 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 tenantId       租户 id
         * @param propertyId     资产 id
         * @param importLogQuery 查询条件
         * @return SvaEmployeesImportLogDTO
         * @author zc
         * @date 2023/10/19
         */
        @Override
        public ListPagedDTO<SvaEmployeesImportLogDTO> list(int tenantId, int propertyId, ImportLogQuery importLogQuery) {
            LambdaQueryWrapper<AttendanceEmpImportLog> queryWrapper = new QueryWrapper<AttendanceEmpImportLog>().lambda()
                    .eq(AttendanceEmpImportLog::getPropertyId, propertyId)
                    .in(CollectionUtils.isNotEmpty(importLogQuery.getStatus()),
                            AttendanceEmpImportLog::getImportResult, importLogQuery.getStatus())
                    .and(Objects.nonNull(importLogQuery.getStartOperationDate()) && Objects.nonNull(importLogQuery.getEndOperationDate()),
                            wrapper -> wrapper.between(AttendanceEmpImportLog::getCreatedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate())
                                    .or().between(AttendanceEmpImportLog::getResolvedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate()));

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