# HotelKpiImportLogServiceImpl.java

    package cloud.wconnect.workperformance.service.hotelkpi.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.hotelkpi.HotelKpiImportLog;
    import cloud.wconnect.workperformance.mapper.hotelkpi.HotelKpiImportLogMapper;
    import cloud.wconnect.workperformance.pojo.dto.hotelkpi.report.HotelKpiImportLogDTO;
    import cloud.wconnect.workperformance.pojo.query.hotelkpi.HotelKpiImportLogQuery;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiImportLogService;
    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.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.stereotype.Service;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;

    /**
     * <p>
     * Hotel KPI report import log 服务实现类
     * </p>
     *
     * @author zc
     * @since 2024-06-24
     */
    @Service
    @DS("work_performance")
    public class HotelKpiImportLogServiceImpl extends ServiceImpl<HotelKpiImportLogMapper, HotelKpiImportLog> implements IHotelKpiImportLogService {

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

        /**
         * 保存导入记录
         *
         * @param propertyDTO  资产DTO
         * @param dateRange    日期范围
         * @param key          S3 key
         * @param importResult 导入结果
         * @param reportType   报告类型
         * @param operatorId   操作人 id
         * @author zc
         * @date 2024/7/1
         */
        @Override
        public void save(PropertyDTO propertyDTO, List<Long> dateRange, String key, int importResult,
                         int reportType, int operatorId) {
            HotelKpiImportLog importLog = new HotelKpiImportLog();
            importLog.setPropertyId(propertyDTO.getId());
            importLog.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(LocalDate.now(ZoneId.of(propertyDTO.getTimezone())),
                    BaseConstant.DATE_FORMAT_YYYYMMDD)));
            importLog.setReportType(reportType);
            importLog.setStartDate(dateRange.get(0));
            importLog.setEndDate(dateRange.get(1));
            importLog.setUrl(key);
            importLog.setCreatedBy(operatorId);
            importLog.setCreatedTime(DateTimeUtils.nowTimestamp());
            importLog.setResolvedBy(0);
            importLog.setResolvedTime(0L);
            importLog.setImportResult(importResult);
            save(importLog);
        }

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

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

        /**
         * 校验是否存在并返回对象
         *
         * @param id 记录 id
         * @return HotelKpiImportLog
         * @author zc
         * @date 2024/7/1
         */
        @Override
        public HotelKpiImportLog checkExist(long id) {
            HotelKpiImportLog 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/7/1
         */
        @Override
        public void checkBelong(int propertyId, HotelKpiImportLog 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 logId        记录 id
         * @param operatorId   操作人 id
         * @param url          报告 url
         * @param handleResult 处理结果
         * @author zc
         * @date 2024/7/1
         */
        @Override
        public void update(long logId, int operatorId, String url, boolean handleResult) {
            HotelKpiImportLog importLog = getById(logId);
            if (importLog.getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING
                    && handleResult) {
                importLog.setResolvedBy(operatorId);
                importLog.setResolvedTime(DateTimeUtils.nowTimestamp());
            }
            importLog.setUrl(url);
            importLog.setImportResult(handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS
                    : ReportImportResultCons.IMPORT_RESULT_FAIL);
            updateById(importLog);
        }

        /**
         * 保存处理中的记录
         *
         * @param propertyDTO 资产
         * @param reportType  报告类型
         * @param dateRange   报告数据范围（yyyyMMdd）
         * @param operatorId  操作人 id
         * @return HotelKpiImportLog
         * @author zc
         * @date 2024/7/1
         */
        @Override
        public HotelKpiImportLog saveInProgress(PropertyDTO propertyDTO, int reportType, List<Long> dateRange, int operatorId) {
            HotelKpiImportLog reportImportLog = new HotelKpiImportLog();
            reportImportLog.setPropertyId(propertyDTO.getId());
            reportImportLog.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(LocalDate.now(ZoneId.of(propertyDTO.getTimezone())),
                    BaseConstant.DATE_FORMAT_YYYYMMDD)));
            reportImportLog.setReportType(reportType);
            reportImportLog.setStartDate(dateRange.get(0));
            reportImportLog.setEndDate(dateRange.get(1));
            reportImportLog.setCreatedBy(operatorId);
            reportImportLog.setCreatedTime(DateTimeUtils.nowTimestamp());
            reportImportLog.setResolvedBy(0);
            reportImportLog.setResolvedTime(0L);
            reportImportLog.setImportResult(ReportImportResultCons.IMPORT_IN_PROGRESS);

            save(reportImportLog);
            return reportImportLog;
        }
    }