package com.yeejoin.precontrol.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sqy
 */
@Slf4j
public class WordTemplateUtils {

    private static WordTemplateUtils wordTemplateUtils;
    private Configuration configuration = null;

    private WordTemplateUtils() {
        configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
    }

    public static synchronized WordTemplateUtils getInstance() {
        if (wordTemplateUtils == null) {
            wordTemplateUtils = new WordTemplateUtils();
        }
        return wordTemplateUtils;
    }

    public void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,
                                          String title, String ftlFile) throws IOException {
        configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
        Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8");

        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map, freemarkerTemplate);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = (StringUtil.isNotEmpty(title) ? title : FileUtil.getUuid()) + ".doc";
            response.setHeader("Content-Disposition",
                    "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            response.addHeader("Access-Control-Allow-Headers", "Content-Disposition");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");

            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            log.error("export doc error e:{}", e.toString());
            e.printStackTrace();
        } finally {
            if (fin != null) {
                fin.close();
            }
            if (out != null) {
                out.close();
            }
            if (file != null) {
                file.delete();
            } // 删除临时文件
        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = "sellPlan.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

    // 将javabean转为map类型，然后返回一个map类型的值
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!StringUtils.equals(name, "class")) {
                    Object feild = propertyUtilsBean.getNestedProperty(obj, name);
//					if(feild == null) {
//						feild = "无";
//					}
                    params.put(name, feild);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
}
