package com.mortals.xhx.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.code.YesNo;
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.key.GenConstants;
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.getBusinessNameExt;

public class FreeMarkerUtils {
    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";
    private static final String TEST_PATH = "test/java/com/mortals/httpclient";

    private static final String FEIGN_PATH = "feign/main/java/com/mortals/xhx/feign";
    private static final String PDU_PATH = "feign/main/java/com/mortals/xhx/common/pdu";

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


    public static Configuration cfg = null;

    public static StringBuilder apimd = new StringBuilder();
    public static StringBuilder apitwomd = 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.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("enum.java.ftl");
        templates.add("entity.java.ftl");
        templates.add("entityQuery.java.ftl");
       // templates.add("entityAndQuery.java.ftl");
        templates.add("dao.java.ftl");
        templates.add("daoImpl.java.ftl");
        templates.add("web.java.ftl");
        templates.add("feign.java.ftl");
        templates.add("pdu.java.ftl");
        templates.add("webBody.java.ftl");
        templates.add("webForm.java.ftl");
        templates.add("sqlMap.xml.ftl");
        templates.add("db.sql.ftl");
        templates.add("dm_db.sql.ftl");
        templates.add("menu.sql.ftl");
        templates.add("api.md.ftl");

        if (GenConstants.TPL_CRUD.equals(tplCategory)) {
            templates.add("service.java.ftl");
            templates.add("serviceImpl.java.ftl");
            templates.add("webVueList.vue.ftl");
            templates.add("VueDialogShow.vue.ftl");
            templates.add("VueDrawerShow.vue.ftl");
            templates.add("webVueShow.vue.ftl");
        } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
            templates.add("entity-tree.java.ftl");
            templates.add("service-tree.java.ftl");
            templates.add("serviceImpl-tree.java.ftl");
            templates.add("VueTreeDialogShow.vue.ftl");
            templates.add("webVueTreeList.vue.ftl");
        } else if (GenConstants.TPL_SUB.equals(tplCategory) || GenConstants.TPL_SUB_ONE.equals(tplCategory)) {
            templates.add("service.java.ftl");
            templates.add("serviceImpl.java.ftl");
            templates.add("webVueList.vue.ftl");
            templates.add("webVueShow.vue.ftl");
            templates.add("VueDrawerShow.vue.ftl");
            templates.add("VueDialogShow.vue.ftl");
        }
        templates.add("webVueView.vue.ftl");
        templates.add("httpclient.test.ftl");
        return templates;
    }


    /**
     * 获取model模板信息
     *
     * @return 模板列表
     */
    public static Set<String> getModelTemplateSet() {
        Set<String> templates = new HashSet<String>();
        templates.add("vo.java.ftl");
        templates.add("entity.java.ftl");
        templates.add("entityQuery.java.ftl");
        templates.add("sqlMap.xml.ftl");
        templates.add("entity-tree.java.ftl");
        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("\\.", "");
        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);
        data.put("code", genTable.getCode()==null?"":genTable.getCode());
        data.put("path", genTable.getPath()==null?"":genTable.getPath());
        //com.mortals.xhx.feign.area
        data.put("packageFeignName", "com.mortals.xhx.feign."+businessName);

        String RequestMapping = Arrays.stream(getBusinessNameExt(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;
    }


    /**
     * 设置枚举模板变量信息
     *
     * @return 模板列表
     */
    public static Map prepareSetFreeMarkerDataByEnum(List<Map<String, String>> enums, String enumName, String enumClassName, String javaType) {
        Map data = new HashMap();
        data.put("enums", enums);
        data.put("EnumName", enumName);
        data.put("JavaType", javaType);
        data.put("EnumClassName", StringUtils.capitalize(enumClassName));
        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));

    }

    /**
     * 获取树编码
     *
     * @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() == YesNo.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 feignPath = FEIGN_PATH + "/" + businessName;
        String pduPath = PDU_PATH + "/" + businessName;
        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("entity-tree.java.ftl")) {
            fileName = StringUtils.format("{}/{}/model/{}TreeSelect.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("entityAndQuery.java.ftl")) {
//            fileName = StringUtils.format("{}/{}/model/{}Entity.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("service-tree.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("serviceImpl-tree.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("webBody.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")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/list.vue", vuePath, businessNameExt);
        }

        else if (template.contains("webVueShow.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/show.vue", vuePath, businessNameExt);
        }
        else if (template.contains("webVueView.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/view.vue", vuePath, businessNameExt);
        }
        else if (template.contains("webVueTreeList.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/list.vue", vuePath, businessNameExt);
        } else if (template.contains("VueTreeDialogShow.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/dialogshow.vue", vuePath, businessNameExt);
        } else if (template.contains("VueDialogShow.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/dialogshow.vue", vuePath, businessNameExt);
        } else if (template.contains("VueDrawerShow.vue.ftl")) {
            String businessNameExt = getBusinessNameExt(genTable.getTableName());
            businessNameExt = StringUtils.replace(businessNameExt, ".", "/");
            fileName = StringUtils.format("{}/views/{}/drawershow.vue", vuePath, businessNameExt);
        }
        else if (template.contains("db.doc.ftl")) {
            fileName = StringUtils.format("doc/alldoc.docx");
        } else if (template.contains("api.doc.ftl")) {
            fileName = StringUtils.format("doc/api.md");
        } else if (template.contains("httpclient.test.ftl")) {
            fileName = StringUtils.format("{}/{}/{}Controller.http", TEST_PATH, businessName, className);
        } else if (template.contains("feign.java.ftl")) {
            fileName = StringUtils.format("{}/I{}Feign.java", feignPath, className);
        } else if (template.contains("pdu.java.ftl")) {
            fileName = StringUtils.format("{}/{}Pdu.java", pduPath, className);
        }
        return fileName;
    }


    /**
     * 获取枚举文件名
     */
    public static String getEnumFileName(String enumClassName) {
        // 文件名称
        String fileName = "";
        String javaPath = PROJECT_PATH + "/com/mortals/xhx/common/code";
        fileName = StringUtils.format("{}/{}Enum.java", javaPath, StringUtils.capitalize(enumClassName));
        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);

    }

}
