package org.ts.ddcs.datatemplate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.ts.ddcs.common.enums.AgreementEnum;
import org.ts.ddcs.itemdatatemplate.ItemTemplate;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;


/**
 * 数据报文模板管理主模块
 *
 * @author swp
 */
@Data
@Slf4j
public class DataTemplateManager {

    private Map<String, List<Template>> templateMap = new HashMap<>(10);
    private Map<String, List<ItemTemplate>> itemTemplateMap = new HashMap<>(200);

    /**
     * 初始化模板
     *
     * @param dir       模板文档目录
     * @param templates 模板名称
     */
    public boolean init(String dir, String templates) {
        try {
            String[] list = templates.split(",");
            if (list.length > 0) {
                for (String t : list) {
                    if (AgreementEnum.AGREEMENT_SW.getName().equals(t)) {
                        //加载模板配置文件
                        String templateDoc = dir + File.separator + t.toLowerCase() + ".xml";
                        File templateFile = new File(templateDoc);
                        if (!templateFile.exists()) {
                            return false;
                        }
                        List<Template> templateList = this.loadTemplateConfig(templateDoc);
                        this.templateMap.put(AgreementEnum.AGREEMENT_SW.getName(), templateList);
                        //加载编码要素配置文件
                        String itemTemplateDoc = dir + File.separator + t.toLowerCase() + "-item.xml";
                        File itemTemplateFile = new File(itemTemplateDoc);
                        if (itemTemplateFile.exists()) {
                            List<ItemTemplate> itemTemplateList = this.loadItemTemplateConfig(itemTemplateDoc);
                            this.itemTemplateMap.put(AgreementEnum.AGREEMENT_SW.getName(), itemTemplateList);
                        }
                    } else if (AgreementEnum.AGREEMENT_SW_EXT.getName().equals(t)) {
                        //加载模板配置文件
                        String templateDoc = dir + File.separator + t.toLowerCase() + ".xml";
                        File templateFile = new File(templateDoc);
                        if (!templateFile.exists()) {
                            return false;
                        }
                        List<Template> templateList = this.loadTemplateConfig(templateDoc);
                        this.templateMap.put(AgreementEnum.AGREEMENT_SW_EXT.getName(), templateList);
                        //加载编码要素配置文件
                        String itemTemplateDoc = dir + File.separator + t.toLowerCase() + "-item.xml";
                        File itemTemplateFile = new File(itemTemplateDoc);
                        if (itemTemplateFile.exists()) {
                            List<ItemTemplate> itemTemplateList = this.loadItemTemplateConfig(itemTemplateDoc);
                            this.itemTemplateMap.put(AgreementEnum.AGREEMENT_SW_EXT.getName(), itemTemplateList);
                        }
                    } else if (AgreementEnum.AGREEMENT_SZY.getName().equals(t)) {
                        //加载模板配置文件
                        String templateDoc = dir + File.separator + t.toLowerCase() + ".xml";
                        File templateFile = new File(templateDoc);
                        if (!templateFile.exists()) {
                            return false;
                        }
                        List<Template> templateList = this.loadTemplateConfig(templateDoc);
                        this.templateMap.put(AgreementEnum.AGREEMENT_SZY.getName(), templateList);
                        //加载编码要素配置文件
                        String itemTemplateDoc = dir + File.separator + t.toLowerCase() + "-item.xml";
                        File itemTemplateFile = new File(itemTemplateDoc);
                        if (itemTemplateFile.exists()) {
                            List<ItemTemplate> itemTemplateList = this.loadItemTemplateConfig(itemTemplateDoc);
                            this.itemTemplateMap.put(AgreementEnum.AGREEMENT_SZY.getName(), itemTemplateList);
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("error", e);
            return false;
        }
    }

//    public boolean hasTemplate(String agreement) {
//        if (this.templateMap.containsKey(agreement.toUpperCase())) {
//            return true;
//        }
//        return false;
//    }

    /**
     * 加载配置文件
     *
     * @param templates
     * @return
     * @throws DocumentException
     */
    private List<Template> loadTemplateConfig(String templates) throws DocumentException {
        List<Template> templateList = new LinkedList<>();
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(templates));
        Element root = document.getRootElement();
        Element templateNode = root.element("Templates");
        List items = templateNode.elements("Item");
        for (Object o : items
        ) {
            Element e = (Element) o;
            String enable = e.element("Enable").getTextTrim();
            if ("1".equals(enable)) {
                Template template = new Template();
                template.setType(e.element("Type").getTextTrim());
                template.setStreamProcessorClass(e.element("StreamProcessor").getTextTrim());
                template.setProcessorName(e.element("ProcessorName").getTextTrim());
                template.setTemplateName(e.element("TemplateName").getTextTrim());
                templateList.add(template);
            }
        }
        return templateList;
    }

    /**
     * 导入编码要素配置模板
     *
     * @param templates
     * @return
     * @throws DocumentException
     */
    private List<ItemTemplate> loadItemTemplateConfig(String templates) throws DocumentException {
        List<ItemTemplate> templateList = new LinkedList<>();
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(templates));
        Element root = document.getRootElement();
        Element templatesNode = root.element("Templates");
        List items = templatesNode.elements("Item");
        for (Object o : items
        ) {
            Element e = (Element) o;
            String enable = e.element("Enable").getTextTrim();
            if ("1".equals(enable)) {
                ItemTemplate t = new ItemTemplate();
                String dataTemplateClass = e.element("DataTemplate").getTextTrim();
                t.setItemTemplateClass(dataTemplateClass);
                String func = e.element("Func").getTextTrim();
                t.setFunc(func);
                String desc = e.element("Desc").getTextTrim();
                t.setDesc(desc);
                String funcName = e.element("FuncName").getTextTrim();
                t.setFuncName(funcName);
                String unit = e.element("Unit").getTextTrim();
                t.setUnit(unit);
                templateList.add(t);
            }
        }
        return templateList;
    }

    /**
     * 返回指定规约的模板配置
     *
     * @param agreement
     * @return
     */
    public List<Template> cloneTemplateLine(String agreement) {
        if (this.templateMap.containsKey(agreement)) {
            return this.templateMap.get(agreement);
        }
        return null;
    }

    /**
     * 生成模板配置实例
     *
     * @param template
     * @return
     */
//    private Template cloneTemplate(Template template) {
//        Template newTemplate = new Template();
//        newTemplate.setTemplateName(template.getTemplateName());
//        newTemplate.setDataTemplateClass(template.getDataTemplateClass());
//        newTemplate.setStreamProcessorClass(template.getStreamProcessorClass());
//        newTemplate.setDataProcessorClass(template.getDataProcessorClass());
//        newTemplate.setFeatureWeight(template.getFeatureWeight());
//        if (null != template.getFeatureKey()) {
//            byte[] featureKey = new byte[template.getFeatureKey().length];
//            System.arraycopy(template.getFeatureKey(), 0, featureKey, 0, featureKey.length);
//            newTemplate.setFeatureKey(featureKey);
//        }
//        if (null != template.getFeatureIndex()) {
//            byte[] featureIndex = new byte[template.getFeatureIndex().length];
//            System.arraycopy(template.getFeatureIndex(), 0, featureIndex, 0, featureIndex.length);
//            newTemplate.setFeatureIndex(featureIndex);
//        }
//        return newTemplate;
//    }

    /**
     * 返回编码要素配置模板
     *
     * @param agreement
     * @return
     */
    public List<ItemTemplate> cloneItemTemplateLine(String agreement) {
        if (this.itemTemplateMap.containsKey(agreement)) {
            return this.itemTemplateMap.get(agreement);
        }
        return null;
    }

    /**
     * 生成编码要素配置模板
     *
     * @param itemTemplate
     * @return
     */
//    private ItemTemplate cloneItemTemplate(ItemTemplate itemTemplate) {
//        ItemTemplate newTemplate = new ItemTemplate();
//        newTemplate.setFunc(itemTemplate.getFunc());
//        newTemplate.setDesc(itemTemplate.getDesc());
//        newTemplate.setItemTemplateClass(itemTemplate.getItemTemplateClass());
//        return newTemplate;
//    }
}
