# ScheduleDepartmentEmployeeImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.schedule.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.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleDepartmentEmployeeImportLog;
    import cloud.wconnect.workperformance.mapper.schedule.ScheduleDepartmentEmployeeImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.schedule.EmployeeImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.schedule.ImportLogQuery;
    import cloud.wconnect.workperformance.service.schedule.IScheduleDepartmentEmployeeImportLogService;
    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 jakarta.annotation.Nullable;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.util.*;

    /**
     * <p>
     * 员工导入记录 服务实现类
     * </p>
     *
     * @author yyt
     * @since 2023-06-28
     */
    @Service
    @DS("work_performance")
    public class ScheduleDepartmentEmployeeImportLogServiceImpl extends ServiceImpl<ScheduleDepartmentEmployeeImportLogMapper, ScheduleDepartmentEmployeeImportLog> implements IScheduleDepartmentEmployeeImportLogService {

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

        /**
         * 根据导入状态修改导入记录状态
         *
         * @param id           导入记录 id
         * @param importResult 导入状态
         * @param url          文件路径
         * @param userId       操作人
         * @author yyt
         * @date 2023/11/20
         */
        @Override
        public void updateLogStatus(int id, boolean importResult, String url, int userId) {
            ScheduleDepartmentEmployeeImportLog updateLog = new ScheduleDepartmentEmployeeImportLog();
            updateLog.setId(id).setUrl(url).setImportResult(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                    ReportImportResultCons.IMPORT_RESULT_FAIL);

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

            updateById(updateLog);
        }

        /**
         * 检查存在
         *
         * @param id 导入记录 id
         * @return 导入记录
         * @author yyt
         * @date 2023/11/20
         */
        @Override
        public ScheduleDepartmentEmployeeImportLog checkExist(int id) {
            ScheduleDepartmentEmployeeImportLog 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 propertyIds 资产 id
         * @param url         文件路径
         * @param status      状态
         * @param userId      操作人
         * @return 日志 id
         * @author yyt
         * @date 2023/11/20
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public List<ScheduleDepartmentEmployeeImportLog> addBatch(List<Integer> propertyIds, @Nullable String url, int status, int userId) {
            long nowTimestamp = DateTimeUtils.nowTimestamp();
            List<ScheduleDepartmentEmployeeImportLog> importLogList = propertyI18nRedisService.list(propertyIds).stream()
                    .map(item -> new ScheduleDepartmentEmployeeImportLog()
                            .setPropertyId(item.getId())
                            .setTheDate(DateTimeUtils.dateNowTimestamp(item.getTimezone()))
                            .setImportResult(status)
                            .setCreatedBy(userId)
                            .setCreatedTime(nowTimestamp)
                            .setResolvedBy(BaseConstant.ZERO)
                            .setResolvedTime(BaseConstant.LONG_ZERO)
                            .setUrl(url)).toList();
            saveBatch(importLogList);

            return importLogList;
        }

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

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

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

        /**
         * 获取员工导入记录
         *
         * @param propertyId     资产 id
         * @param importLogQuery 查询条件
         * @return 员工导入记录
         * @author yyt
         * @date 2024/11/22
         **/
        @Override
        public ListPagedDTO<EmployeeImportLogDTO> listEmployeeImportLog(Integer propertyId, ImportLogQuery importLogQuery) {
            List<ScheduleDepartmentEmployeeImportLog> importLogs;
            long total;

            if (Objects.nonNull(importLogQuery.getPage()) && Objects.nonNull(importLogQuery.getSize())) {
                Page<ScheduleDepartmentEmployeeImportLog> page = listPage(propertyId, importLogQuery);
                importLogs = page.getRecords();
                total = page.getTotal();
            } else {
                importLogs = list(propertyId, importLogQuery);
                total = importLogs.size();
            }

            Map<Integer, String> userNameById = Collections.emptyMap();
            if (CollectionUtils.isNotEmpty(importLogs)) {
                Set<Integer> userIds = Sets.newHashSetWithExpectedSize(importLogs.size());
                for (ScheduleDepartmentEmployeeImportLog item : importLogs) {
                    if (item.getCreatedBy() > 0) {
                        userIds.add(item.getCreatedBy());
                    }
                    if (item.getResolvedBy() > 0) {
                        userIds.add(item.getResolvedBy());
                    }
                }
                if (CollectionUtils.isNotEmpty(userIds)) {
                    userNameById = userInternalService.getNameMapByIds(propertyI18nRedisService.get(propertyId).getTenantId(), userIds);
                }
            }

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

        /**
         * 修改导入记录状态
         *
         * @param id     导入记录 id
         * @param status 状态
         * @param userId 操作人
         * @author yyt
         * @date 2024/11/22
         **/
        @Override
        public void update(int id, int status, int userId) {
            updateById(new ScheduleDepartmentEmployeeImportLog()
                    .setId(id)
                    .setImportResult(status)
                    .setResolvedBy(userId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }

    }