package com.yiboshi.science.utils;

import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import freemarker.cache.ClassTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;


public class HtmlBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(HtmlBuilder.class);

    private ThreadLocal<Map<String, Object>> map = ThreadLocal.withInitial(HashMap::new);

    private FreeMarkerConfigurer freeMarkerConfigurer;

    public HtmlBuilder(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }

    public static boolean loop(List<String> list, String value) {
        for (String str : list) {
            if (Objects.equals(str, value)) {
                return true;
            }
        }
        return false;
    }

    public void exportWord(Object dataModel, HttpServletRequest request, HttpServletResponse response) {
        String url = request.getRequestURL().toString();
        String s2 = url.substring(0,url.indexOf("v1"));
        Map<String, Object> data1 = obj2Map(dataModel);
        //这里是根据数据替换模板中的字段并返回一个字符串
        String html = getHtmlText("tmp-pov.html",data1);
        //对html中的中文进行Unicode编码,这里是最关键的一步，必须，不然导出的wordoffice打开乱码
        html = EncodingUtil.setUrlForChn(html.replace("img src=\"","img src=\""+s2));
        System.out.println(html);
        String encodedFileName = "";
        InputStream inputStream = new ByteArrayInputStream(html.getBytes());
        FileDownloadUtil.download(inputStream, request, response, encodedFileName);
    }

    public static String getDomainName(String url) {
        String host = "";
        try {
            URL Url = new URL(url);
            host = Url.getHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return host;
    }

    public static Map<String, Object> obj2Map(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 获取f对象对应类中的所有属性域
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
//            varName = varName.toLowerCase();//将key置为小写，默认为对象的属性
            try {
                // 获取原来的访问控制权限
                boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                fields[i].setAccessible(true);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o = fields[i].get(obj);
//                if (o != null)
                    map.put(varName, o);
                // 恢复访问控制权限
                fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 生成html文件
     *
     * @param htmlFile     html文件
     * @param templateName 模板名
     */
    public File convertHtml(File htmlFile, String templateName) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            BeansWrapper myWrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            template.setObjectWrapper(myWrapper);
            fos = new FileOutputStream(htmlFile);
            osw = new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8");
            bw = new BufferedWriter(osw);
//            template.process(getRootMap(), bw);
//            getRootMap().clear();
        } catch (Exception e) {
            LOGGER.error("FREEMARKER - create html by template error with templateName : " + templateName, e);
        } finally {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(bw);
        }
        return htmlFile;
    }

    /**
     * 生成html模板字符串
     *
     * @return 模板字符串
     */
    public  String getHtmlText(String templateName,Map<String, Object> map) {
        String htmlText = "";
        try {
            // 通过指定模板名获取FreeMarker模板实例
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(this.getClass(), "/template");
            configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/template"));
            Template tpl = configuration.getTemplate(templateName, "utf-8");
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
            map.clear();
        } catch (Exception e) {
            LOGGER.error("FREEMARKER - create html by template error with templateName : " + templateName, e);
        }
        return htmlText;
    }

    public FreeMarkerConfigurer getFreeMarkerConfigurer() {
        return freeMarkerConfigurer;
    }

    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }

}

