// 创建数据表的信息
//
'use api/core/runtime/database/sql/tables.js';
'use api/lib/camelAndUnderscore.js';

// 根据sql列类型获取html类型
function getHtmlTypeFromColumnType(columnType) {
    // const ColumnTypeStr = ['char', 'varchar', 'narchar', 'varchar2', 'tinytext', 'text', 'mediumtext', 'longtext']; // to "input";
    const ColumnTypeTime = ['datetime', 'time', 'date', 'timestamp', 'timestamptz']; // to "datetime";
    // const ColumnTypeNumber = [
    // 	'smallint',
    // 	'mediumint',
    // 	'int',
    // 	'int2',
    // 	'int4',
    // 	'int8',
    // 	'number',
    // 	'integer',
    // 	'numeric',
    // 	'bigint',
    // 	'float',
    // 	'float4',
    // 	'float8',
    // 	'double',
    // 	'decimal',
    // ]; // to "input";
    const ColumnTypeBool = ['tinyint', 'bool', 'boolean']; // to "switch";
    const dataType = columnType.toLowerCase();
    if (ColumnTypeTime.includes(dataType)) {
        return 'datetime';
    } else if (ColumnTypeBool.includes(dataType)) {
        return 'switch';
    } else {
        return 'input';
    }
}

function main() {
    // 验证用户权限
    'use api/user/acl/excerpt.js'

    let tableId = payload.get().path.split('/').pop();

    TABLE_STRUCT = SQL.query('system_sql', 'SELECT * FROM dm_table_columns WHERE table_id = ?', tableId);
    if (TABLE_STRUCT.length == 0) {
        return errMsg(507, '表结构为空');
    }

    DB_NAME = SQL.query('system_sql', 'SELECT db_name FROM dm_tables WHERE table_id = ?', tableId)[0].db_name;
    TABLE_NAME = TABLE_STRUCT[0].table_name;
    
    let tableCollums = getTableCollums();

    // let fieldName = underscoreToCamel(col.Field);
    const temp = [];
    for (let i = 0; i < tableCollums.length; i++) {
        let col = tableCollums[i];

        // 如果TABLE_STRUCT有元素的column_name和col.Field相同则跳过
        if (TABLE_STRUCT.find((item) => item.column_name == col.Field)) {
            continue;
        }

        let stmt =
            'INSERT INTO dm_table_columns (column_id, table_id, sort, table_name, column_name, column_comment, column_type, column_key, field_name, is_pk, is_required, is_increment, html_type, proprietor_id, proprietor_name) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
        //           							         tid, 	sort,  tname    , cname,       ccomment,	      ctype,      ckey,    	  jfield,   ispk,   isrequired,      isinc,     htype      oid,     own
        let params = [
            ex.suid().base58(),
            tableId,
            i + 1,
            TABLE_NAME,
            col.Field,
            col.Comment,
            col.Type,
            col.Key,
            underscoreToCamel(col.Field),
            col.Key == 'PKI' ? 1 : 0,
            col.Null == 'NO' ? 1 : 0,
            col.Extra.includes('auto_increment') ? 1 : 0,
            getHtmlTypeFromColumnType(col.Type),
            USER_INFO.user_id,
            USER_INFO.nickname,
        ];
        SQL.push('system_sql', stmt, ...params);
        temp.push(params);
    }

    return okMsg('创建表信息成功');
}
