package com.ruoyi.generator.service.front;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.front.dto.DatabaseColumnDesign;
import com.ruoyi.generator.domain.front.dto.DatabaseTableDesign;

@Component
public class MysqlDdlBuilder
{
    public String build(DatabaseTableDesign table)
    {
        List<String> lines = new ArrayList<String>();
        String primaryKey = null;
        for (DatabaseColumnDesign column : table.getColumns())
        {
            lines.add("  " + buildColumn(column));
            if ("1".equals(column.getIsPk()))
            {
                primaryKey = column.getColumnName();
            }
        }
        if (primaryKey != null)
        {
            lines.add("  PRIMARY KEY (`" + primaryKey + "`)");
        }
        return "CREATE TABLE `" + table.getTableName() + "` (\n"
                + StringUtils.join(lines, ",\n")
                + "\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='" + escapeComment(table.getTableComment()) + "';";
    }

    private String buildColumn(DatabaseColumnDesign column)
    {
        StringBuilder sql = new StringBuilder();
        sql.append("`").append(column.getColumnName()).append("` ").append(column.getColumnType());
        if ("1".equals(column.getIsRequired()) || "1".equals(column.getIsPk()))
        {
            sql.append(" NOT NULL");
        }
        else
        {
            sql.append(" DEFAULT NULL");
        }
        if ("1".equals(column.getIsIncrement()))
        {
            sql.append(" AUTO_INCREMENT");
        }
        sql.append(" COMMENT '").append(escapeComment(column.getColumnComment())).append("'");
        return sql.toString();
    }

    private String escapeComment(String comment)
    {
        return StringUtils.defaultString(comment)
                .replaceAll("[\\p{Cntrl}]", " ")
                .replace("\\", "\\\\")
                .replace("'", "''");
    }
}
