package cn.com.qmth.examcloud.core.questions.service.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.SpringContextUtils;
import cn.com.qmth.examcloud.core.questions.base.enums.ExportTemplateType;
import cn.com.qmth.examcloud.core.questions.service.ExportTemplateService;
import cn.com.qmth.examcloud.web.config.SystemProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class ExportTemplateUtil {

    private static final String ENCODING = "UTF-8";
    private static SystemProperties systemProperties= (SystemProperties)SpringContextUtils.getBeanByClass(SystemProperties.class);
    private static ExportTemplateService exportTemplateService = SpringContextUtils.getBean(ExportTemplateService.class,
            "exportTemplateService");

    private final static Map<Long, Configuration> configs = new ConcurrentHashMap<Long, Configuration>();

    private final static Map<String, Template> templates = new ConcurrentHashMap<String, Template>();

    private final static Map<String, DocxTemplateBean> doctemplates = new ConcurrentHashMap<String, DocxTemplateBean>();

    public static DocxTemplateBean getDocxTemplateBean(Long rootOrgId, ExportTemplateType type) {
        String key = rootOrgId + "_" + type.getCode();
        DocxTemplateBean temp = doctemplates.get(key);
        File dir = exportTemplateService.getExportTemplateDirectory(type, rootOrgId);
        if (temp == null || !temp.getKey().equals(dir.getName())||!dir.exists()) {
            temp = createDocxTemplateBean(dir);
            doctemplates.put(key, temp);
        }
        return temp;
    }

    private static DocxTemplateBean createDocxTemplateBean(File dir) {
        DocxTemplateBean bean = new DocxTemplateBean();
        bean.setKey(dir.getName());
        Configuration config = new Configuration(Configuration.VERSION_2_3_25);
        // 设置编码
        config.setDefaultEncoding(ENCODING);
        // 设置ftl模板路径
        try {
            config.setDirectoryForTemplateLoading(dir);
            bean.setDocxPath(dir.getAbsolutePath()+File.separator+"data"+File.separator);
            bean.setContentTypes(config.getTemplate("content_types.ftl", ENCODING));
            bean.setDocument(config.getTemplate("document.ftl", ENCODING));
            bean.setDocumentRels(config.getTemplate("document_rels.ftl", ENCODING));
            File head=new File(dir+File.separator+"header.ftl");
            if(head.exists()) {
                bean.setHeader(config.getTemplate("header.ftl", ENCODING));
            }
        } catch (IOException e) {
            throw new StatusException("20001", "模板配置初始化出错 " + e.getMessage());
        }
        return bean;
    }

    public static Template getTemplate(Long rootOrgId, ExportTemplateType type) {
        String key = rootOrgId + "_" + type.getCode();
        Template temp = templates.get(key);
        String tname = exportTemplateService.getExportTemplateName(type, rootOrgId);
        if (temp == null || !temp.getName().equals(tname)) {
            try {
                temp = getConfig(rootOrgId).getTemplate(tname, ENCODING);
                templates.put(key, temp);
            } catch (IOException e) {
                throw new StatusException("10001", "获取模板出错 " + e.getMessage());
            }
        }
        return temp;
    }

    private static Configuration getConfig(Long rootOrgId) {
        Configuration config = configs.get(rootOrgId);
        if (config == null) {
            config = new Configuration(Configuration.VERSION_2_3_25);
            // 设置编码
            config.setDefaultEncoding(ENCODING);
            // 设置ftl模板路径
            String temPath = systemProperties.getTempDataDir();
            File dir = new File(temPath + File.separator + rootOrgId + File.separator);
            try {
                config.setDirectoryForTemplateLoading(dir);
                configs.put(rootOrgId, config);
            } catch (IOException e) {
                throw new StatusException("20001", "模板配置初始化出错 " + e.getMessage());
            }
        }
        return config;
    }
}
