package com.starry.generator.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.starry.common.utils.StringUtils;
import com.starry.generator.constant.GenConstants;
import com.starry.generator.entity.GenTableColumnEntity;
import com.starry.generator.entity.GenTableEntity;
import java.util.*;
import org.apache.velocity.VelocityContext;

/**
 * @author admin 模板处理工具类
 * @since 2022/7/19
 */
public class VelocityUtils {

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

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

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTableEntity genTableEntity) {
        String moduleName = genTableEntity.getModuleName();
        String businessName = genTableEntity.getBusinessName();
        String packageName = genTableEntity.getPackageName();
        String tplCategory = genTableEntity.getTplCategory();
        String functionName = genTableEntity.getFunctionName();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tplCategory", genTableEntity.getTplCategory());
        velocityContext.put("tableName", genTableEntity.getTableName());
        velocityContext.put("functionName", StrUtil.isNotBlank(functionName) ? functionName : "【请填写功能名称】");
        velocityContext.put("ClassName", genTableEntity.getClassName());
        // 首字母小写
        velocityContext.put("className", StringUtils.uncapitalize(genTableEntity.getClassName()));
        velocityContext.put("moduleName", genTableEntity.getModuleName());
        // 首字母大写
        velocityContext.put("BusinessName", StringUtils.capitalize(genTableEntity.getBusinessName()));
        velocityContext.put("businessName", genTableEntity.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", genTableEntity.getFunctionAuthor());
        velocityContext.put("datetime", DateUtil.format(new Date(), "yyyy-MM-dd"));
        velocityContext.put("pkColumn", genTableEntity.getPkColumn());
        velocityContext.put("importList", getImportList(genTableEntity));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", genTableEntity.getColumns());
        velocityContext.put("table", genTableEntity);
        velocityContext.put("dicts", getDicts(genTableEntity));
        setMenuVelocityContext(velocityContext, genTableEntity);
        if (GenConstants.TPL_TREE.equals(tplCategory)) {
            setTreeVelocityContext(velocityContext, genTableEntity);
        }
        if (GenConstants.TPL_SUB.equals(tplCategory)) {
            setSubVelocityContext(velocityContext, genTableEntity);
        }
        return velocityContext;
    }

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

    /**
     * 根据列类型获取导入包
     *
     * @param genTableEntity
     *            业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTableEntity genTableEntity) {
        List<GenTableColumnEntity> columns = genTableEntity.getColumns();
        GenTableEntity subGenTableEntity = genTableEntity.getSubTable();
        HashSet<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subGenTableEntity)) {
            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;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName
     *            模块名称
     * @param businessName
     *            业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName) {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

    /**
     * 根据列类型获取字典组
     *
     * @param genTableEntity
     *            业务表对象
     * @return 返回字典组
     */
    public static String getDicts(GenTableEntity genTableEntity) {
        List<GenTableColumnEntity> columns = genTableEntity.getColumns();
        Set<String> dicts = new HashSet<>();
        addDicts(dicts, columns);
        if (StringUtils.isNotNull(genTableEntity.getSubTable())) {
            List<GenTableColumnEntity> subColumns = genTableEntity.getSubTable().getColumns();
            addDicts(dicts, subColumns);
        }
        return StringUtils.join(dicts, ", ");
    }

    /**
     * 添加字典列表
     *
     * @param dicts
     *            字典列表
     * @param columns
     *            列集合
     */
    public static void addDicts(Set<String> dicts, List<GenTableColumnEntity> columns) {
        for (GenTableColumnEntity column : columns) {
            if (!column.isSuperColumn() && StrUtil.isNotBlank(column.getDictType()) && StringUtils.equalsAny(
                    column.getHtmlType(),
                    new String[]{GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX})) {
                dicts.add("'" + column.getDictType() + "'");
            }
        }
    }

    public static void setMenuVelocityContext(VelocityContext context, GenTableEntity genTableEntity) {
        String options = genTableEntity.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String parentMenuId = getParentMenuId(paramsObj);
        context.put("parentMenuId", parentMenuId);
    }

    public static void setTreeVelocityContext(VelocityContext context, GenTableEntity genTableEntity) {
        String options = genTableEntity.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String treeCode = getTreeCode(paramsObj);
        String treeParentCode = getTreeParentCode(paramsObj);
        String treeName = getTreeName(paramsObj);

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

    public static void setSubVelocityContext(VelocityContext context, GenTableEntity genTableEntity) {
        GenTableEntity subTable = genTableEntity.getSubTable();
        String subTableName = genTableEntity.getSubTableName();
        String subTableFkName = genTableEntity.getSubTableFkName();
        String subClassName = genTableEntity.getSubTable().getClassName();
        String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);

        context.put("subTable", subTable);
        context.put("subTableName", subTableName);
        context.put("subTableFkName", subTableFkName);
        context.put("subTableFkClassName", subTableFkClassName);
        context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        context.put("subClassName", subClassName);
        context.put("subclassName", StringUtils.uncapitalize(subClassName));
        context.put("subImportList", getImportList(genTableEntity.getSubTable()));
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj
     *            生成其他选项
     * @return 上级菜单ID字段
     */
    public static String getParentMenuId(JSONObject paramsObj) {
        if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
                && StrUtil.isNotBlank(paramsObj.getString(GenConstants.PARENT_MENU_ID))) {
            return paramsObj.getString(GenConstants.PARENT_MENU_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

    /**
     * 获取树编码
     *
     * @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 getTreeParentCode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_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;
    }

    public static int getExpandColumn(GenTableEntity genTableEntity) {
        String options = genTableEntity.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int num = 0;
        for (GenTableColumnEntity column : genTableEntity.getColumns()) {
            if ("1".equals(column.getIsList())) {
                num++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName)) {
                    break;
                }
            }
        }
        return num;
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory) {
        List<String> templates = new ArrayList<>();
        templates.add("vm/java/entity.java.vm");
        templates.add("vm/java/mapper.java.vm");
        templates.add("vm/java/service.java.vm");
        templates.add("vm/java/serviceImpl.java.vm");
        templates.add("vm/java/controller.java.vm");
        templates.add("vm/java/queryVo.java.vm");
        templates.add("vm/java/addVo.java.vm");
        templates.add("vm/xml/mapper.xml.vm");
        templates.add("vm/sql/sql.vm");
        templates.add("vm/js/api.js.vm");
        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;
    }

    /**
     * 获取文件名
     *
     * @return 文件名称
     */
    public static String getFileName(String template, GenTableEntity genTableEntity) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTableEntity.getPackageName();
        // 模块名
        String moduleName = genTableEntity.getModuleName();
        // 大写类名
        String className = genTableEntity.getClassName();
        // 业务名称
        String businessName = genTableEntity.getBusinessName();

        // 相关生成文件目录
        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + moduleName;
        String vuePath = "vue";

        if (template.contains("entity.java.vm")) {
            fileName = StringUtils.format("{}/module/entity/{}Entity.java", javaPath, className);
        } else if (template.contains("sub-domain.java.vm")
                && StringUtils.equals(GenConstants.TPL_SUB, genTableEntity.getTplCategory())) {
            fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTableEntity.getSubTable().getClassName());
        } else if (template.contains("mapper.java.vm")) {
            fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
        } else if (template.contains("service.java.vm")) {
            fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
        } else if (template.contains("serviceImpl.java.vm")) {
            fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
        } else if (template.contains("controller.java.vm")) {
            fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
        } else if (template.contains("queryVo.java.vm")) {
            fileName = StringUtils.format("{}/vo/{}QueryVo.java", javaPath, className);
        } else if (template.contains("addVo.java.vm")) {
            fileName = StringUtils.format("{}/vo/{}AddVo.java", javaPath, className);
        } else if (template.contains("mapper.xml.vm")) {
            fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
        } else if (template.contains("sql.vm")) {
            fileName = businessName + "Menu.sql";
        } else if (template.contains("api.js.vm")) {
            fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName);
        } else if (template.contains("index.vue.vm")) {
            fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
        } else if (template.contains("index-tree.vue.vm")) {
            fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
        }
        return fileName;
    }
}
