package com.tofly.codegen.util;

import com.tofly.codegen.entity.ColumnEntity;
import com.tofly.codegen.entity.GenConfig;
import com.tofly.codegen.entity.TableEntity;
import lombok.experimental.UtilityClass;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Administrator
 * @date 2019/9/26  14:32
 */
@UtilityClass
public class GenUtils {
    private static final String ENTITY_JAVA_VM = "Entity.java.vm";
    private static final String MAPPER_JAVA_VM = "Mapper.java.vm";
    private static final String SERVICE_JAVA_VM = "Service.java.vm";
    private static final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
    private static final String CONTROLLER_JAVA_VM = "Controller.java.vm";
    private static final String MAPPER_XML_VM = "Mapper.xml.vm";

    private List<String> getTemplates() {
        List<String> templates = new ArrayList<>();
        templates.add("templates/Entity.java.vm");
        templates.add("templates/Mapper.java.vm");
        templates.add("templates/Mapper.xml.vm");
        templates.add("templates/Service.java.vm");
        templates.add("templates/ServiceImpl.java.vm");
        templates.add("templates/Controller.java.vm");
        return templates;
    }

    /**
     * 生成代码
     */
    public void generatorCode(GenConfig genConfig, Map<String, String> table,
                              List<Map<String, String>> columns, ZipOutputStream zip) throws Exception {
        //配置信息
        Configuration config = getConfig();
        //如果存在大数据
        boolean hasBigDecimal = false;
        //如果存在日期类型，需要转换格式
        boolean hasDate = false;

        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("TABLENAME"));

        if (StringUtils.isNotBlank(genConfig.getComments())) {
            tableEntity.setComments(genConfig.getComments());
        } else {
            tableEntity.setComments(table.get("COMMENTS"));
        }

        String tablePrefix;
        if (StringUtils.isNotBlank(genConfig.getTablePrefix())) {
            tablePrefix = genConfig.getTablePrefix();
        } else {
            tablePrefix = config.getString("tablePrefix");
        }

        String tableSuffix;
        if (StringUtils.isNotBlank(genConfig.getTablePrefix())) {
            tableSuffix = genConfig.getTableSuffix();
        } else {
            tableSuffix = config.getString("tableSuffix");
        }

        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), tablePrefix,tableSuffix);
        tableEntity.setCaseClassName(className);
        tableEntity.setLowerClassName(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columnList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("COLUMNNAME"));
            columnEntity.setDataType(column.get("DATATYPE"));
            columnEntity.setComments(column.get("COMMENTS"));
            columnEntity.setExtra(column.get("extra"));

            columnEntity.setType(column.get("TYPE"));
            columnEntity.setDefaultValue(column.get("DEFAULTVALUE"));
            columnEntity.setQueryLike(column.get("QUERYLIKE"));
            columnEntity.setCodeKey(column.get("CODEKEY"));



            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setCaseAttrName(attrName);
            columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));

            columnEntity.setSetFunName(setFunName(columnEntity.getLowerAttrName()));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
                hasBigDecimal = true;
            }
            if (!hasDate && "Date".equals(attrType)) {
                hasDate = true;
            }

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("ISKEY")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            //自定义增加的字段名
            String customSql=column.get("CUSTOMSQL");
            if(customSql!=null && customSql!=""){
                customSql=customSql.replace("?","#{"+columnEntity.getLowerAttrName()+"}");
                columnEntity.setCustomSql(customSql);
            }
            handlerCustomName(columnEntity);

            columnList.add(columnEntity);
        }
        tableEntity.setColumns(columnList);

        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", tableEntity.getTableName());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getCaseClassName());
        map.put("classname", tableEntity.getLowerClassName());
        map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasDate", hasDate);
        map.put("datetime", DateUtil.getNowDate());

        if (StringUtils.isNotBlank(genConfig.getComments())) {
            map.put("comments", genConfig.getComments());
        } else {
            map.put("comments", tableEntity.getComments());
        }

        if (StringUtils.isNotBlank(genConfig.getAuthor())) {
            map.put("author", genConfig.getAuthor());
        } else {
            map.put("author", config.getString("author"));
        }

        if (StringUtils.isNotBlank(genConfig.getModuleName())) {
            map.put("moduleName", genConfig.getModuleName());
        } else {
            map.put("moduleName", config.getString("moduleName"));
        }

        if (StringUtils.isNotBlank(genConfig.getPackageName())) {
            map.put("package", genConfig.getPackageName());
            map.put("mainPath", genConfig.getPackageName());
        } else {
            map.put("package", config.getString("package"));
            map.put("mainPath", config.getString("mainPath"));
        }
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(Objects
                        .requireNonNull(getFileName(template, tableEntity.getCaseClassName()
                                , map.get("package").toString(), map.get("moduleName").toString()))));
                IOUtil.write(zip, "UTF-8", false, sw.toString());
                IOUtil.close(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new Exception("渲染模板失败，表名：" + tableEntity.getTableName());
            }
        }
    }


    private void handlerCustomName(ColumnEntity columnEntity){
        String type=columnEntity.getType();
        if(type!=null && type!=""){
            switch (type){
                case "1":
                    columnEntity.setCustomName("list"+fristCase(columnEntity.getLowerAttrName()));
                    break;
                case "5":
                    columnEntity.setCustomName("list"+fristCase(columnEntity.getLowerAttrName()));
                    break;
                case "6":
                    columnEntity.setCustomName(getFormName(columnEntity.getCustomSql()));
                    break;
                default: return;
            }
        }
    }

    private String getFormName(String sql){
        String[] a=sql.split(" from");
        String[] b=a[0].split(" ");
        List<String> collect = Arrays.stream(b).filter(k -> k != " ").collect(Collectors.toList());
        return collect.get(collect.size()-1);
    }


    /**
     * 列名转换成Java属性名
     */
    private String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }


    private String setFunName(String columnName){
        return "set"+fristCase(columnName)+"Name";
    }

    private String fristCase(String str){
        char[] cs=str.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }



    /**
     * 表名转换成Java类名
     */
    private String tableToJava(String tableName, String tablePrefix,String tableSuffix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }

        if (StringUtils.isNotBlank(tableSuffix)) {
            tableName = tableName.replace(tableSuffix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    private Configuration getConfig() throws ConfigurationException{
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new ConfigurationException("获取配置文件失败");
        }
    }

    /**
     * 获取文件名
     */
    private String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "tofly" + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }

        if (template.contains(ENTITY_JAVA_VM)) {
            return packagePath + "entity" + File.separator + className + ".java";
        }

        if (template.contains(MAPPER_JAVA_VM)) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }

        if (template.contains(SERVICE_JAVA_VM)) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains(SERVICE_IMPL_JAVA_VM)) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains(CONTROLLER_JAVA_VM)) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains(MAPPER_XML_VM)) {
            return "tofly" + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
        }
        return null;
    }
}
