package com.rongwei.trainingcommon.sys.service;

import com.aspose.words.Document;
import com.aspose.words.MailMergeCleanupOptions;
import com.aspose.words.SaveFormat;
import com.aspose.words.net.System.Data.DataTable;
import com.rongwei.rwcommon.base.exception.CustomException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;


public interface ExportTrainingDemandService {
    void generatePaper(String surveyId, HttpServletResponse response);

    void generateUserPaper(String surveyId, String userId, HttpServletResponse response);

    void generateRecord(String surveyId, HttpServletResponse response);

    default Document wordDrawing(String[] wordKey, String[] wordValue, DataTable dataTable, String tempPatch) {
        Resource resource = new ClassPathResource(tempPatch);
        try (InputStream inputStream = resource.getInputStream()) {
            Document doc = new Document(inputStream);
            doc.getMailMerge().execute(wordKey, wordValue);
            doc.getMailMerge().executeWithRegions(dataTable);
            //自定义字段
            doc.getMailMerge().setUseNonMergeFields(true);
            //去除未替换到的域，防止页面显示域代码
            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS);
            doc.getMailMerge().deleteFields();
            return doc;
        } catch (Exception e) {
            throw new CustomException("word生成异常");
        }
    }

    default void exportSingleWord(Document doc, HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=paper.docx");
            doc.save(response.getOutputStream(), SaveFormat.DOCX);
        } catch (Exception e) {
            throw new CustomException("文件导出异常");
        }
    }
}
