package cn.stylefeng.team.meta.sdk.util;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.rule.enums.YesOrNotEnum;
import cn.stylefeng.team.meta.api.entity.MetaField;
import cn.stylefeng.team.meta.sdk.parser.MysqlTypeToMetaFieldType;

public class TableSchemaCreateUtil {

    public static String fieldTypeMetaCreate(MetaField metaField) {

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append("`").append(metaField.getFieldCode()).append("` ");

        String mysqlType = MysqlTypeToMetaFieldType.getSqlType(metaField.getFieldType());

        String lengthResult = MysqlTypeToMetaFieldType.getLengthResult(metaField.getFieldType(), metaField.getFieldLength(), metaField.getDecimalLength());
        stringBuilder.append(mysqlType).append(lengthResult).append(" ");

        if (MysqlTypeToMetaFieldType.VARCHAR.getMysqlType().equals(mysqlType) || MysqlTypeToMetaFieldType.ONE_CHAR.getMysqlType().equals(mysqlType)) {
            stringBuilder.append("CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ");
        }

        if (YesOrNotEnum.Y.getCode().equals(metaField.getNotEmptyFlag())) {
            stringBuilder.append("NOT NULL ");
        } else {
            stringBuilder.append("NULL ");
        }

        if (metaField.getDefaultValue() != null) {
            if (MysqlTypeToMetaFieldType.VARCHAR.getMysqlType().equals(mysqlType) || MysqlTypeToMetaFieldType.ONE_CHAR.getMysqlType().equals(mysqlType)) {
                stringBuilder.append("DEFAULT '").append(metaField.getDefaultValue()).append("' ");
            } else {
                stringBuilder.append("DEFAULT ").append(metaField.getDefaultValue()).append(" ");
            }
        }

        if (ObjectUtil.isNotEmpty(metaField.getDescription())) {
            stringBuilder.append("COMMENT '").append(metaField.getDescription()).append("'");
        }

        return stringBuilder.toString();
    }

}
