# ScheduleByOther.java

    package cloud.wconnect.workperformance.service.schedule.scheduleinfo;

    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleInfoImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.schedule.IScheduleInfoImportLogService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleInfoService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import jakarta.annotation.Resource;

    import java.io.IOException;
    import java.io.InputStream;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;

    /**
     * Schedule By Other
     *
     * @author yyt
     * 2024/8/6
     */
    @Slf4j
    @Component
    @DS("work_performance")
    public class ScheduleByOther implements IScheduleFileParse {

        @Resource
        private IScheduleInfoImportLogService scheduleInfoImportLogService;
        @Resource
        private IScheduleInfoService scheduleInfoService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        @Value("${aws-s3.third-party.key.schedule.manual-import}")
        private String s3ManualImportKey;

        @Value("${file-max-size.import-report.schedule}")
        private Long importReportFileMaxSize;

        private static final String SOURCE = SystemPlatformEnum.OTHER.getDesc();

        /**
         * 判断可导入文件条件
         *
         * @param source 平台数据源
         * @return boolean
         * @author yyt
         * @date 2024/8/6
         */
        @Override
        public boolean supports(String source) {
            return source.equals(SOURCE);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param inputStream 文件流
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @return ScheduleBO
         * @author yyt
         * @date 2024/8/6
         */
        @Override
        public List<ScheduleBO> parsReport(PropertyDTO propertyDTO, InputStream inputStream, Long startDate, Long endDate) throws IOException {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            String timezone = propertyDTO.getTimezone();

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            // 循环标题，获取导入数据日期
            Row titleRow = sheet.getRow(0);
            int allColumn = titleRow.getPhysicalNumberOfCells();
            Map<Integer, String> effectiveDateByColumn = Maps.newHashMapWithExpectedSize(allColumn - 1);
            for (int i = 1; i < allColumn; i++) {
                LocalDate targetDate = LocalDate.parse(CellUtils.convertCellStr(titleRow.getCell(i),
                        BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                long tartDateSecond = DateTimeUtils.localDateToLong(targetDate, timezone);
                if (tartDateSecond >= startDate && tartDateSecond <= endDate) {
                    effectiveDateByColumn.put(i, dateTimeFormatter.format(targetDate));
                }
            }

            if (!effectiveDateByColumn.isEmpty()) {
                // 最大数据量：有效人数 * 14天（最大支持选择 14 天导入）
                List<ScheduleBO> schedules = Lists.newArrayListWithExpectedSize(sheet.getLastRowNum() * 14);
                // 循环数据信息
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    // 循环处理每个人的排班信息
                    String employeeName = row.getCell(0).toString();
                    effectiveDateByColumn.forEach((column, date) -> {
                        Cell contentCel = row.getCell(column);
                        if (Objects.nonNull(contentCel) && StringUtils.isNotBlank(contentCel.toString())) {
                            ScheduleBO scheduleBO = new ScheduleBO();
                            scheduleBO.setTargetDate(date);
                            scheduleBO.setContent(contentCel.toString());
                            scheduleBO.setName(employeeName);
                            schedules.add(scheduleBO);
                        }
                    });
                }

                workbook.close();

                return schedules;
            }

            workbook.close();

            return Collections.emptyList();
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));

            try (InputStream in = file.getInputStream();Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                // 循环标题检查日期格式
                Row titleRow = sheet.getRow(0);
                if (Objects.isNull(titleRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                int allColumn = titleRow.getPhysicalNumberOfCells();
                for (int i = 1; i < allColumn; i++) {
                    Cell dateCell = titleRow.getCell(i);
                    if (Objects.isNull(dateCell) || StringUtils.isBlank(dateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.DATE),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "the date must not be null");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            LinkedHashMap<String, Boolean> map = new LinkedHashMap<>();
                            map.put(CommonFieldI18nConstant.DATE, true);
                            map.put(BaseConstant.DATE_FORMAT_YYYY_MM_DD, false);
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMap(map),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The date format error");
                        }
                    }
                }

                String employeeNameTitle = CellUtils.convertCellStr(titleRow.getCell(0));

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell employeeNameCell = row.getCell(0);
                    if (Objects.isNull(employeeNameCell) || StringUtils.isBlank(employeeNameCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(employeeNameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The employee name cannot be empty");
                    } else {
                        // 最大255
                        if (CellUtils.convertCellStr(employeeNameCell).length() > 255) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(employeeNameTitle, 255),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The employee name cannot be more than 255 characters");
                        }
                    }
                }
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param file        文件
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        public ScheduleInfoImportLog handleImportLog(PropertyDTO propertyDTO, Long startDate, Long endDate,
                                                     MultipartFile file, int userId) {
            String key = toS3(propertyDTO.getTenantSymbol(), propertyDTO.getAbbr(), file);
            ScheduleInfoImportLog importLog = new ScheduleInfoImportLog().setPropertyId(propertyDTO.getId())
                    .setFromDate(startDate).setToDate(endDate).setUrl(key)
                    .setStatus(ReportImportResultCons.IMPORT_IN_PROGRESS)
                    .setCreatedBy(userId).setCreatedTime(DateTimeUtils.nowTimestamp());
            scheduleInfoImportLogService.save(importLog);
            return importLog;
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/8/6
         **/
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + s3ManualImportKey +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());
            try {
                // 上传文件
                amazonS3Service.uploadFile(S3BucketFunctionCons.SCHEDULE_IMPORT_RECORD, file, key);
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Uploading to s3 failure", e);
            }
            return key;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/6
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, ScheduleInfoImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<ScheduleBO> scheduleBOS = parsReport(propertyDTO, inputStream, importLog.getFromDate(), importLog.getToDate());
                if (CollectionUtils.isNotEmpty(scheduleBOS)) {
                    scheduleInfoService.handleInsertSchedule(propertyDTO, scheduleBOS, userId);
                }
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse schedule report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/8/6
         **/
        private void importSuccess(ScheduleInfoImportLog importLog) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                ScheduleInfoImportLog updateLog = new ScheduleInfoImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                scheduleInfoImportLogService.updateById(updateLog);
            });
        }

        /**
         * 导入失败
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/8/6
         **/
        private void importFail(ScheduleInfoImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                ScheduleInfoImportLog updateLog = new ScheduleInfoImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_FAIL);
                scheduleInfoImportLogService.updateById(updateLog);
            });
        }

    }