package com.qmth.exam.reserve.template.execute;

import com.alibaba.excel.EasyExcel;
import com.qmth.boot.tools.uuid.FastUUID;
import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.bean.stdapply.StudentApplyExport;
import com.qmth.exam.reserve.entity.AsyncTaskEntity;
import com.qmth.exam.reserve.enums.AsyncTaskResult;
import com.qmth.exam.reserve.enums.AsyncTaskStatus;
import com.qmth.exam.reserve.enums.AsyncTaskType;
import com.qmth.exam.reserve.enums.FileUploadType;
import com.qmth.exam.reserve.service.AsyncTaskService;
import com.qmth.exam.reserve.service.FileUploadService;
import com.qmth.exam.reserve.service.StudentApplyService;
import com.qmth.exam.reserve.template.export.AsyncExportTaskTemplate;
import com.qmth.exam.reserve.util.DateUtil;
import com.qmth.exam.reserve.util.FileUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @Description 考生预约详情导出异步执行类
 */
@Service
public class StudentApplyDetailExportService extends AsyncExportTaskTemplate {

    private final static Logger log = LoggerFactory.getLogger(StudentApplyDetailExportService.class);

    public static final String OBJ_TITLE = "考生预约详情";

    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private StudentApplyService studentApplyService;

    @Autowired
    private FileUploadService fileUploadService;

    @Override
    public void exportTask(Map<String, Object> map) {
        AsyncTaskEntity task = (AsyncTaskEntity) map.get(Constants.ASYNC_TASK);
        StringJoiner summary = new StringJoiner("\n").add(
                MessageFormat.format("{0}{1}{2}", DateFormatUtils.format(new Date(), DateUtil.LongDateString), BEGIN_TITLE, OBJ_TITLE));
        task.setStatus(AsyncTaskStatus.RUNNING);
        task.setSummary(summary.toString());
        asyncTaskService.updateById(task);

        try {
            Long teachingId = null;
            if (map.get("teachingId") != null) {
                teachingId = Long.parseLong(map.get("teachingId").toString());
            }
            List<StudentApplyExport> studentApplyDetailList = studentApplyService.listStudentApplyDetail(teachingId);
            String url = createExportFile(studentApplyDetailList);

            //设置导出的条数
            summary.add(MessageFormat.format("{0}{1}{2}{3}", DateFormatUtils.format(new Date(), DateUtil.LongDateString), FINISH_TITLE,
                    !CollectionUtils.isEmpty(studentApplyDetailList) ? studentApplyDetailList.size() : 0, FINISH_SIZE));

            //更新异步任务状态
            task.setSummary(summary.toString());
            task.setExportFilePath(url);
            task.setImportFileName(AsyncTaskType.STUDENT_APPLY_EXPORT.getTitle());
            task.setResult(AsyncTaskResult.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            task.setResult(AsyncTaskResult.ERROR);
            summary.add(MessageFormat.format("{0}{1}{2}{3}", DateFormatUtils.format(new Date(), DateUtil.LongDateString),
                    EXCEPTION_CREATE_TXT_TITLE, EXCEPTION_DATA, e.getMessage()));
            task.setSummary(summary.toString());
        } finally {
            task.setStatus(AsyncTaskStatus.FINISH);
            asyncTaskService.updateById(task);
        }

    }

    private String createExportFile(List<StudentApplyExport> studentExportList) throws IOException {
        File fileTemp = null;
        try {
            fileTemp = FileUtil.getFileTemp(Constants.XLSX_PREFIX);
            EasyExcel.write(fileTemp, StudentApplyExport.class).sheet("考生预约详情").doWrite(studentExportList);
            String fileName = FastUUID.get();
            StringJoiner stringJoiner = FileUtil.getDirName(FileUploadType.UPLOAD, true).add(fileName).add(Constants.XLSX_PREFIX);
            String path = stringJoiner.toString().replaceAll("\\\\", "/");
            fileUploadService.uploadFile(path, fileTemp);
            return path;
        } finally {
            if (fileTemp != null) {
                boolean deleted = fileTemp.delete();
                if (!deleted) {
                    log.warn("[考生预约详情导出] 临时文件删除失败,tempFileName:{}", fileTemp.getAbsolutePath());
                }
            }
        }
    }
}
