package com.mortals.xhx.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.framework.config.FreemarkerApplicationConfig;
import com.mortals.xhx.base.system.gentable.model.GentableColumnEntity;
import com.mortals.xhx.base.system.gentable.model.GentableEntity;
import com.mortals.xhx.base.system.gentable.model.ProjectInfoEntity;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.GenConstants;
import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

import static com.mortals.xhx.common.utils.GenUtils.getBusinessName;

public class FreeMarkerUtils {


    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";

    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "main/resources/sqlmap";

    /**
     * 默认上级菜单，系统工具
     */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    public static Configuration cfg = null;

    public static StringBuilder dbSql = new StringBuilder();
    public static StringBuilder menuSql = new StringBuilder();

    /**
     * 初始化freeMaker方法
     */
    @SneakyThrows
    public static void initFreeMarker(String path) {
        //初始化模板引擎
        cfg = new Configuration(Configuration.VERSION_2_3_29);
        cfg.setClassForTemplateLoading(FreemarkerApplicationConfig.class, "/template/" + path);
        //cfg.setClassForTemplateLoading(FreemarkerApplicationConfig.class,"/template/sql");
        //指定模板文件存放的地方
        //cfg.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir") + "\\government-manager\\target\\classes\\template\\java"));
        //cfg.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir") + "\\government-manager\\target\\classes\\template\\xml\\"));
        //cfg.set

        // cfg.setTemplateLoader(new ClassTemplateLoader(FreeMarkerUtils.class,"/template/java/entity.ftl"));

        // cfg.setClassForTemplateLoading(FreeMarkerUtils.class, "/template/");
        // cfg.setClassForTemplateLoading(FreeMarkerUtils.class, "\\template\\sql");
        //cfg.setClassForTemplateLoading(FreeMarkerUtils.class, "\\template\\vue");
        //cfg.setClassForTemplateLoading(FreeMarkerUtils.class, "\\template\\xml");
        //设置字符编码集
        cfg.setDefaultEncoding("UTF-8");
        //设置异常的处理方式
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        //设置输出时间格式
        cfg.setDateFormat("yyyy-MM-dd HH:mm:ss");

    }

    /**
     * 初始化freeMaker方法
     */
    @SneakyThrows
    public static void initFreeMarkerPath(String templatePath) {
        //初始化模板引擎
        cfg = new Configuration(Configuration.VERSION_2_3_29);
        cfg.setDirectoryForTemplateLoading(new File(templatePath));

        //设置字符编码集
        cfg.setDefaultEncoding("UTF-8");
        //设置异常的处理方式
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        //设置输出时间格式
        cfg.setDateFormat("yyyy-MM-dd HH:mm:ss");

    }


    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory) {
        List<String> templates = new ArrayList<String>();
        templates.add("vo.java.ftl");
        templates.add("entity.java.ftl");
        templates.add("entityQuery.java.ftl");
        templates.add("dao.java.ftl");
        templates.add("daoImpl.java.ftl");
        templates.add("service.java.ftl");
        templates.add("serviceImpl.java.ftl");
        templates.add("web.java.ftl");
        templates.add("webForm.java.ftl");
        templates.add("sqlMap.xml.ftl");
        templates.add("webVueList.vue.ftl");
        templates.add("webVueShow.vue.ftl");
        templates.add("db.sql.ftl");
        templates.add("menu.sql.ftl");
        //templates.add("db.doc.ftl");
        if (GenConstants.TPL_CRUD.equals(tplCategory)) {
            // templates.add("vm/vue/index.vue.vm");
        } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
            //templates.add("vm/vue/index-tree.vue.vm");
        } else if (GenConstants.TPL_SUB.equals(tplCategory)) {
            //templates.add("vm/vue/index.vue.vm");
            //templates.add("vm/java/sub-domain.java.vm");
        }
        return templates;
    }

    // 获取模板对象
    public static Template getTemplate(String templateName) {
        try {
            return cfg.getTemplate(templateName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static Map prepareSetFreeMarkerData(GentableEntity genTable) {

        Map data = new HashMap();
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName().replace("\\.", "");

        //包路径=basepackage+businessName去除.号
        //basepackage=com.mortals.xhx
        //module=moduleName
        //b
        //String packageName = genTable.getPackageName();
        String packageName = genTable.getPackageName() + "." + moduleName + "." + businessName;
        String tplCategory = genTable.getTplCategory();
        String functionName = genTable.getFunctionName();

        data.put("tplCategory", genTable.getTplCategory());
        data.put("tableName", genTable.getTableName());
        data.put("tableComment", genTable.getTableComment());
        data.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : genTable.getTableComment());
        data.put("ClassName", genTable.getClassName());
        data.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        data.put("moduleName", genTable.getModuleName());
        data.put("BusinessName", StringUtils.capitalize(businessName));
        data.put("businessName", businessName);
        data.put("basePackage", getPackagePrefix(packageName));
        data.put("packageName", packageName);
        data.put("author", genTable.getFunctionAuthor());
        data.put("datetime", DateUtils.getCurrStrDate());
        data.put("pkColumn", genTable.getPkColumn());
        data.put("importList", getImportList(genTable));
        data.put("columns", genTable.getColumns());
        data.put("table", genTable);

        String RequestMapping = Arrays.stream(getBusinessName(genTable.getTableName()).split("\\.")).collect(Collectors.joining("/"));
        data.put("RequestMapping", RequestMapping);
        if (GenConstants.TPL_TREE.equals(tplCategory)) {
            setTreeFreeMarkerData(data, genTable);
        }
        if (GenConstants.TPL_SUB.equals(tplCategory)) {
            setSubFreeMarkerData(data, genTable);
        }
        if (GenConstants.TPL_SUB_ONE.equals(tplCategory)) {
            setSubFreeMarkerData(data, genTable);
        }
        return data;
    }


    /**
     * 设置文档生成模板变量信息
     *
     * @return 模板列表
     */
    public static Map prepareSetFreeMarkerDataByDoc(List<GentableEntity> tableList, ProjectInfoEntity projectInfo) {
        Map data = new HashMap();
        data.put("tableList", tableList);
        data.put("projectInfo", projectInfo);
        return data;
    }


    public static void setTreeFreeMarkerData(Map data, GentableEntity genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeCode = getTreecode(paramsObj);
        String treeParentCode = getTreeParentCode(paramsObj);
        String treeName = getTreeName(paramsObj);

        data.put("treeCode", treeCode);
        data.put("treeParentCode", treeParentCode);
        data.put("treeName", treeName);
        data.put("expandColumn", getExpandColumn(genTable));
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            data.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            data.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
        }
    }

    /**
     * 获取树编码
     *
     * @param paramsObj 生成其他选项
     * @return 树编码
     */
    public static String getTreecode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树名称
     *
     * @param paramsObj 生成其他选项
     * @return 树名称
     */
    public static String getTreeName(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树父编码
     *
     * @param paramsObj 生成其他选项
     * @return 树父编码
     */
    public static String getTreeParentCode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取需要在哪一列上面显示展开按钮
     *
     * @param genTable 业务表对象
     * @return 展开按钮列序号
     */
    public static int getExpandColumn(GentableEntity genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int num = 0;
        for (GentableColumnEntity column : genTable.getColumns()) {
            if (column.getIsList() == YesNoEnum.YES.getValue()) {
                num++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName)) {
                    break;
                }
            }
        }
        return num;
    }

    public static void setSubFreeMarkerData(Map data, GentableEntity genTable) {
        GentableEntity subTable = genTable.getSubTable();
        String subTableName = genTable.getSubTableName();
        String subTableFkName = genTable.getSubTableFkName();
        String subClassName = genTable.getSubTable().getClassName();
        String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);
        String businessName = subTable.getBusinessName().replace("\\.", "");
        String functionName = subTable.getFunctionName();
        String subPackageName = genTable.getPackageName() + "." + genTable.getModuleName() + "." + businessName;

        data.put("subTable", subTable);
        data.put("subPackageName", subPackageName);
        data.put("subTableName", subTableName);
        data.put("subTableFkName", subTableFkName);
        data.put("subFunctionName", StringUtils.isNotEmpty(functionName) ? functionName : subTable.getTableComment());
        //外键java类型
        data.put("subTableFkType", getFkJavaType(subTable, subTableFkName));
        data.put("subTableFkClassName", subTableFkClassName);
        data.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        data.put("subClassName", subClassName);
        data.put("subBusinessName", businessName);
        data.put("subclassName", StringUtils.uncapitalize(subClassName));
        data.put("subImportList", getImportList(subTable));
        data.put("subColumns", subTable.getColumns());
        data.put("subPkColumn", subTable.getPkColumn());
    }

    private static String getFkJavaType(GentableEntity subTable, String subTableFkName) {
        String subTableFkType = "";
        GentableColumnEntity gentableColumnEntity = subTable.getColumns().stream().filter(f -> subTableFkName.equals(f.getColumnName())).findFirst().orElseGet(() -> null);
        if (!ObjectUtils.isEmpty(gentableColumnEntity)) {
            subTableFkType = gentableColumnEntity.getJavaType();
        }

        return subTableFkType;
    }


    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(".");
        String basePackage = StringUtils.substring(packageName, 0, lastIndex);
        return basePackage;
    }

    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GentableEntity genTable) {
        List<GentableColumnEntity> columns = genTable.getColumns();
        GentableEntity subGenTable = genTable.getSubTable();
        HashSet<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subGenTable)) {
            importList.add("java.util.List");
        }
        for (GentableColumnEntity column : columns) {
            if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.util.Date");
                //importList.add("com.fasterxml.jackson.annotation.JsonFormat");
            } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GentableEntity genTable) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = StringUtils.replace(genTable.getBusinessName(), ".", "/");
        // main/java+ packageName(com.mortals.xhx.modules)
        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/") + "/" + moduleName;

        String mybatisPath = MYBATIS_PATH + "/" + moduleName;
        String vuePath = "vue";
        String dbPath = "db";

        //实体类输出路径
        if (template.contains("entity.java.ftl")) {
            fileName = StringUtils.format("{}/{}/model/{}Entity.java", javaPath, businessName, className);
        } else if (template.contains("vo.java.ftl")) {
            fileName = StringUtils.format("{}/{}/model/vo/{}Vo.java", javaPath, businessName, className);
        } else if (template.contains("entityQuery.java.ftl")) {
            fileName = StringUtils.format("{}/{}/model/{}Query.java", javaPath, businessName, className);
        } else if (template.contains("dao.java.ftl")) {
            fileName = StringUtils.format("{}/{}/dao/{}Dao.java", javaPath, businessName, className);
        } else if (template.contains("daoImpl.java.ftl")) {
            fileName = StringUtils.format("{}/{}/dao/ibatis/{}DaoImpl.java", javaPath, businessName, className);
        } else if (template.contains("service.java.ftl")) {
            fileName = StringUtils.format("{}/{}/service/{}Service.java", javaPath, businessName, className);
        } else if (template.contains("serviceImpl.java.ftl")) {
            fileName = StringUtils.format("{}/{}/service/impl/{}ServiceImpl.java", javaPath, businessName, className);
        } else if (template.contains("web.java.ftl")) {
            fileName = StringUtils.format("{}/{}/web/{}Controller.java", javaPath, businessName, className);
        } else if (template.contains("webForm.java.ftl")) {
            fileName = StringUtils.format("{}/{}/web/{}Form.java", javaPath, businessName, className);
        } else if (template.contains("sqlMap.xml.ftl")) {
            fileName = StringUtils.format("{}/{}/{}Mapper.xml", mybatisPath, businessName, className);
        } else if (template.contains("webVueList.vue.ftl")) {
            fileName = StringUtils.format("{}/views/{}/list.vue", vuePath, businessName);
        } else if (template.contains("webVueShow.vue.ftl")) {
            fileName = StringUtils.format("{}/views/{}/show.vue", vuePath, businessName);
        } else if (template.contains("db.doc.ftl")) {
            fileName = StringUtils.format("{}/views/{}/show.vue", vuePath, businessName);
        }
        return fileName;
    }


    /**
     * 提供模板文件，输出到控制台
     *
     * @param templateName 模板对象
     * @param dataModel    数据模型
     */
    public static void printConsole(String templateName, Map dataModel) {
        Template template = getTemplate(templateName);
        try {
            template.process(dataModel, new PrintWriter(System.out));
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 提供模板文件名称，输出到文件中
     *
     * @param templateName 模板对象
     * @param dataModel    数据模型
     * @param destFile     目标文件地址
     */
    public static String printFile(String templateName, Map dataModel, String destFile) {
        System.out.println(destFile);
        Template template = getTemplate(templateName);
        try {
            template.process(dataModel, new FileWriter(new File(destFile)));

        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return destFile;
    }

    public static String printFile(String templateName, List<Map> dataModel, String destFile) {
        Template template = getTemplate(templateName);
        try {
            template.process(dataModel, new FileWriter(new File(destFile)));

        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return destFile;
    }

    public static void main(String[] args) {

        String templatePath="E:\\pic\\template\\";

        FreeMarkerUtils.initFreeMarkerPath(templatePath);

        Template template = FreeMarkerUtils.getTemplate("634745647093772288.xml");

        //System.out.println(template);


//        FreeMarkerUtils.initFreeMarker("java");
//
//        Template template = FreeMarkerUtils.getTemplate("sqlMap.ftl");
//        System.out.println(template.getName());
//
//
//        GentableEntity gentableEntity = new GentableEntity();
//        gentableEntity.setPackageName("com.mortals.xhx.module");
//        gentableEntity.setBusinessName("matter");
//        gentableEntity.setClassName("MortalsXhxMatter");
//        gentableEntity.setModuleName("moduleName");
//
//        String fileName = FreeMarkerUtils.getFileName("entity.ftl", gentableEntity);
//
//        System.out.println("fileName:" + fileName);

    }

}
