package com.yeejoin.amos.boot.module.jg.biz.utils;

import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

public class FileExporter {

    public static void exportFile(FileType fileType, String fileName, byte[] data, HttpServletResponse response) {
        try {
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType(fileType.getContentType());
            fileName = fileName.replaceAll("\\..*", "");
            fileName = URLEncoder.encode(fileName + fileType.getFileSufix(), "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "");
            response.getOutputStream().write(data);
            response.getOutputStream().flush();
        } catch (Exception e) {
            throw new BadRequest("导出文档出错");
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件类型
     */
    public enum FileType {
        // word文档
        docx(".docx", "application/msword"),
        // pdf文档
        pdf(".pdf", "application/pdf");

        private String fileSufix;
        private String contentType;

        private FileType(String fileSufix, String contentType) {
            this.fileSufix = fileSufix;
            this.contentType = contentType;
        }

        public String getFileSufix() {
            return fileSufix;
        }

        public String getContentType() {
            return contentType;
        }

        public static FileType getInstance(String fileSufix) {
            FileType knowledgeRoleName = null;
            for (FileType fileType : FileType.values()) {
                if (fileType.getFileSufix().equals(fileSufix)) {
                    knowledgeRoleName = fileType;
                }
            }
            return knowledgeRoleName;
        }
    }
}
