package com.tofly.gpsboot.util;


import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import static com.tofly.common.core.util.ServletUtil.getRequest;

@Component
public class WordUtil {
    @Autowired
    private static Logger logger = LogManager.getLogger(WordUtil.class);



    //    @Value("${com.dv.path}")
    public static String path;//文件路径

//    private static String url;

    // 记得去掉static
    @Value("${word.path}")
    public void setDriver(String path) {
        WordUtil.path= path;
    }

    private static final String FTL_FP = "/report/word/"; //模板路径
    //private static final String FTL_FP = "/etc/ftl/"; //模板路径

    //解决中文乱码
//    fileName = URLDecoder.decode(fileName, "UTF-8");



    private static Configuration configuration = null;
    static{
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");//设置默认的编码
        //读配置文件
//        path = PropertiesUtil.get("FILE_PATH")+"/";

    }

    /**
     *
     * @param dataMap 数据库数据
     * @param ftl  替换的模板
     * @return
     * @throws IOException
     */
    public static String createDoc(Map dataMap, String ftl) throws IOException {

        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
        // ftl文件存放路径
        //configuration.setClassForTemplateLoading(,FTL_FP);
//        TemplateLoader templateLoader = new FileTemplateLoader(new File(FTL_FP));
//        configuration.setDirectoryForTemplateLoading(new File(FTL_FP));
//        TemplateLoader templateLoader = new ClassTemplateLoader(WordUtil.class, FTL_FP);
//        configuration.setTemplateLoader(templateLoader);
        configuration.setClassForTemplateLoading(WordUtil.class,FTL_FP);
        Template t = null;
        try {
            // test.ftl为要装载的模板
            t = configuration.getTemplate(ftl);
            t.setEncoding("utf-8");

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出文档路径及名称
        String file_name= dataMap.get("title")+ DateTimeUtil.getCurrentDate(DateTimeUtil.NUMBER_FORMAT) +System.currentTimeMillis()+".doc";

        System.out.println(path);
        File outFile = new File(path+file_name);
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
        } catch (Exception e1) {
            logger.error(e1);
            file_name = "";
        }
        try {
            t.process(dataMap, out);
            out.close();
        } catch (TemplateException e2) {
            logger.error(e2);
            file_name = "";
        } catch (IOException e) {
            logger.error(e);
            file_name = "";
        }
        return file_name;
    }

    /**
     * 通用文件下载方法
     *
     * @param response
     * @param filePath
     *            文件绝对路径
     *            this.getClass().getClassLoader().getResource("file").getPath
     *            ();
     * @param fileName
     *            文件名
     * @throws IOException
     */
    public static void responseDownloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws IOException {
        // 读到流中
        InputStream inStream = new FileInputStream(filePath + fileName);// 文件的存放路径

        String agent = request.getHeader("User-Agent").toUpperCase();

        String encodedfileName = "";
        if (agent.indexOf("MSIE") != -1 || agent.indexOf("TRIDENT") != -1) { // IE
            encodedfileName = URLEncoder.encode(fileName, "utf-8");
        } else if (agent.indexOf("CHROME") != -1 || agent.indexOf("FIREFOX") != -1) { // 谷歌或火狐
            encodedfileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
        } else {
            encodedfileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
        }

        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");

        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        while ((len = inStream.read(b)) > 0) {
            response.getOutputStream().write(b, 0, len);
        }
        inStream.close();
    }

    /**
     * 获得图片的base64码
     * @param src
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String getImageBase(String src) {
        if(src==null||src==""){
            return "";
        }
        File file = new File(getRequest().getRealPath("/")+src.replace(getRequest().getContextPath(), ""));
        if(!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 处理转义字符
     * @param str
     * @return
     */
    public static String transform(String str){
        if(!StringUtils.isEmpty(str)){
            if(str.contains("<")||str.contains(">")||str.contains("&")){
                str=str.replaceAll("&", "&amp;");
                str=str.replaceAll("<", "&lt;");
                str=str.replaceAll(">", "&gt;");
            }

        }

        return str;
    }
}
