package com.izouma.codegenerator;


import com.izouma.awesomeadmin.model.GenCode;
import com.izouma.awesomeadmin.model.TableField;
import org.apache.commons.text.CaseUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.ToolManager;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

public class GenList {
    public static void main(String[] args) {
        try {
            Set<String> imports = new HashSet<>();

            TableField field1 = new TableField();
            field1.setName("aaaBbbb");
            field1.setJdbcType("int");
            field1.setJavaType("Integer");
            field1.setPrimaryKey(true);
            field1.setShowInList(true);
            field1.setShowInForm(true);


            TableField field2 = new TableField();
            field2.setName("cccDdd");
            field2.setJdbcType("varchar");
            field2.setJavaType("String");
            field2.setShowInList(true);
            field2.setShowInForm(true);

            GenCode model = new GenCode();
            model.setTableName("test_gen");
            model.setClassName(CaseUtils.toCamelCase(model.getTableName(), true, '_'));
            List<TableField> fields = new ArrayList<>();
            fields.add(field1);
            fields.add(field2);
            model.setFields(fields);

            model.setPrimaryField(field1);

            Properties pro = new Properties();
            pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "/Users/xiongzhu/Projects/Java/awesomeAdmin/src/main/java/com/izouma/ModelGenerator/templates");
            Velocity.init(pro);
            ToolManager manager = new ToolManager(true, true);
            VelocityContext context = new VelocityContext(manager.createContext());
            context.put("imports", imports);
            context.put("model", model);
            Template t = Velocity.getTemplate("listTemplate.vm");

            String targetFile = "TestGenList.vue";
            File file = new File("src/main/vue/src/pages", targetFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            if (!file.exists())
                file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            t.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
            System.out.println("成功生成vue文件:");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
