package com.izouma.codegenerator;

import com.izouma.awesomeadmin.model.DataSourceInfo;
import com.izouma.awesomeadmin.model.GenCode;
import com.izouma.awesomeadmin.model.TableField;
import com.izouma.awesomeadmin.util.Const;
import com.izouma.awesomeadmin.util.JDBC;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class TableGenerator {
    public static void main(String[] args) throws Exception {
        //测试数据
        GenCode genCode = new GenCode();
        genCode.setTableName("ddddd");
        List<TableField> tableFields = new ArrayList<>();
        TableField tableFields1 = new TableField();
        tableFields1.setName("id");
        tableFields1.setJdbcType("int");
        tableFields1.setLength(11);
        tableFields1.setRemark("编号");
        tableFields1.setPrimaryKey(true);
        tableFields1.setAutoIncrease(true);
        tableFields1.setNotNull(true);

        TableField tableFields2 = new TableField();
        tableFields2.setName("username");
        tableFields2.setJdbcType("varchar");
        tableFields2.setLength(50);
        tableFields2.setRemark("用户名");
        tableFields2.setDefaultValue("s");
        tableFields2.setPrimaryKey(false);
        tableFields2.setAutoIncrease(false);
        tableFields2.setNotNull(true);

        tableFields.add(tableFields1);
        tableFields.add(tableFields2);
        genCode.setFields(tableFields);
        GenTable(genCode);
    }

    /**
     * 生成表，数据库建表
     *
     * @param model
     * @throws Exception
     */
    public static void GenTable(GenCode model) throws Exception {
        Connection conn = null;
        try {

            String DRIVER = "com.mysql.jdbc.Driver";

            PropertiesFileLoader propertiesFileLoader = PropertiesFileLoader.getInstance();

            //基础数据库
            String url = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.url");
            String user = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.username");
            String password = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.password");


            if (!"dataSource".equals(model.getDataSourceCode())) {//如果不是基础数据库

                //获取数据源配置信息
                DataSourceInfo dataSourceInfo = Const.DataSourceInfoMap.get(model.getDataSourceCode());

                if ("Mysql".equals(dataSourceInfo.getDatabaseType())) {
                    url = "jdbc:mysql://" + dataSourceInfo.getUrl() + "/" + dataSourceInfo.getDatabaseName();
                    user = dataSourceInfo.getUsername();
                    password = dataSourceInfo.getPassword();
                } else if ("SqlServer".equals(dataSourceInfo.getDatabaseType())) {
                    DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                    url = "jdbc:sqlserver://" + dataSourceInfo.getUrl() + ";DatabaseName=" + dataSourceInfo.getDatabaseName();
                    user = dataSourceInfo.getUsername();
                    password = dataSourceInfo.getPassword();
                }

            }


            conn = JDBC.connectDB(DRIVER, url, user, password);

            Statement stmt = conn.createStatement();

            String sql = "DROP TABLE IF EXISTS " + model.getTableName() + "; create table " + model.getTableName() + "(";

            if ("SqlServer".equals(model.getDataBaseType())) {
                sql = "IF EXISTS (SELECT * FROM sys.objects where name = '" + model.getTableName() + "')DROP TABLE " + model.getTableName()
                        + "; create table " + model.getTableName() + "(";
            }


            for (TableField tableField : model.getFields()) {
                if (tableField.getLength() == null) {
                    switch (tableField.getJdbcType()) {
                        case "int":
                            tableField.setLength(10);
                            break;
                        case "char":
                            tableField.setLength(1);
                            break;
                        case "varchar":
                            tableField.setLength(255);
                            break;
                        default:
                            tableField.setJavaType("String");
                    }
                }
                if (tableField.getJdbcType().equals("decimal")) {
                    if (tableField.getLength() == null) {
                        tableField.setLength(10);
                    }
                    if (tableField.getDecimalPlaces() == null) {
                        tableField.setDecimalPlaces(0);
                    }
                }

                if (tableField.getLength() == null) {
                    tableField.setLength(0);
                }


                if ("Mysql".equals(model.getDataBaseType())) {

                    sql += " " + tableField.getName() + " " + tableField.getJdbcType() + "(" + tableField.getLength() + ")";

                } else if ("SqlServer".equals(model.getDataBaseType())) {
                    if ("int".equals(tableField.getJdbcType())) {

                        sql += " " + tableField.getName() + " " + tableField.getJdbcType();
                    } else {
                        sql += " " + tableField.getName() + " " + tableField.getJdbcType() + "(" + tableField.getLength() + ")";
                    }

                }


                if (tableField.getNotNull()) {
                    sql += " not null ";
                }
                if (tableField.getPrimaryKey()) {
                    sql += " primary key ";
                }
                if (tableField.getAutoIncrease()) {
                    if ("Mysql".equals(model.getDataBaseType())) {

                        sql += " auto_increment ";

                    } else if ("SqlServer".equals(model.getDataBaseType())) {
                        sql += " identity(1,1) ";
                    }

                }
                if (tableField.getDefaultValue() != null) {
                    sql += " default " + "'" + tableField.getDefaultValue() + "'";
                }

                if (StringUtils.isNotEmpty(tableField.getRemark())) {
                    if ("Mysql".equals(model.getDataBaseType())) {
                        sql += " comment " + "'" + tableField.getRemark() + "'";
                    }
                }

                sql += ",";
            }
            String str = sql.substring(0, sql.lastIndexOf(","));
            String sql1 = str + " )";

            if (StringUtils.isNotEmpty(model.getRemark())) {
                if ("Mysql".equals(model.getDataBaseType())) {
                    sql1 += " comment = " + "'" + model.getRemark() + "'";
                }
            }

            System.out.println(sql1);
            int result = stmt.executeUpdate(sql1);
            if (result != -1) {
                System.out.println("创建数据表成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
        }

    }

}

