// ==========================================================================
// 所属模块：DevGenTableColumns
// 生成日期：2024-02-20 20:43:57 +0800 CST
// 生成路径: /dm/cols/function.js
// 生成人：xScript_Engine
// 数据表：dm_table_columns - 代码生成字段
// ==========================================================================

response.headers.add('X-Script-Version', 'core-gen-cols-gen-147')

// ===== 获取dm_table_columns表所有数据
TABLE_NAME = 'dm_table_columns';
COLUMN_KEY = 'table_id';
TABLE_FIELDS = '*';

'use api/lib/sql.js';

function getPlaceholders(condition) {
    const columnsArr = Object.keys(condition);
    const placeholders = [];
    const tempParams = [];
    columnsArr.forEach((item) => {
        if (item == 'tableId') {
            placeholders.push(`tableId = ?`);
            tempParams.push(condition[item]);
        } else if (item == 'tableName') {
            placeholders.push(`table_name LIKE ?`);
            tempParams.push('%' + condition[item] + '%');
        } else if (item == 'columnComment') {
            placeholders.push(`column_comment LIKE ?`);
            tempParams.push('%' + condition[item] + '%');
        }
    });

    return {
        placeholders: placeholders.join(' AND '),
        tempParams: tempParams,
    };
}

function update() {
    const data = payload.get().body?.toObject();
    delete data.createTime;
    delete data.updateTime;
    const newData = {};
    let field
    Object.keys(data).forEach((name) => {
        field = Object(TABLE_STRUCT).find(data => data.field_name === data).column_name
        newData[field] = data[name];
    });
    let filter = payload.get().path.split('/').pop();
    const columnsArr = Object.keys(newData);
    let dataArr = [];
    const placeholders = [];
    columnsArr.forEach((item) => {
        if (newData[item]) {
            placeholders.push(`${item} =?`);
            dataArr.push(newData[item]);
        } else {
            placeholders.push(`${item} = NULL`);
        }
    })

    const newPlaceholders = placeholders.join(',');
    const query = `UPDATE ${TABLE_NAME} SET ${newPlaceholders} WHERE ${COLUMN_KEY} = ?`;

    const res = SQL.exec(DB_NAME, query, ...[...dataArr, filter]);
    if (res) {
        return okMsg(res);
    }
    return errMsg(507, '更新失败');
}

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

    switch (payload.get().method) {
        case 'GET':
            return sql_select();
        case 'PUT':
            return update();
        case 'DELETE':
            return sql_delete();
        default:
            response.status.notFound();
            return `404 page not found`;
    }
}
