/** 页面管理基础接口   **/

TABLE_NAME = 'sys_pages';
COLUMN_KEY = 'page_id';
TABLE_FIELDS = '*';
'use api/lib/sql.js';

function main() {
    // 验证用户权限
    'use api/user/acl/excerpt.js';
    switch (payload.get().method) {
        case "GET":
            return list();
        case "POST":
            return insert();
        case "PUT":
            return sql_update();
        case 'DELETE':
            return sql_delete();
        default:
            response.status.notFound();
            return `404 page not found`;
    }
}


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

    return {
        placeholders: placeholders.join(' AND '),
        tempParams: tempParams,
    };
}
function list() {
    const queryPa = payload.get().query;
    if (!Object.keys(queryPa).length) {
        // 根据id查询详情
        var useParent = scriptPath != payload.get().path.substring(1);
        if (useParent) {
            let value = payload.get().path.split('/').pop();
            const result = SQL.query(
                'system_sql',
                `SELECT * FROM ${TABLE_NAME} WHERE delete_time IS NULL AND ${COLUMN_KEY} = ?`,
                value
            );
            if (result.length) {
                return okMsg(result);
            }
            return errMsg('获取失败');
        }
    }
    // 格式化这个query参数
    let newData = {};
    Object.keys(queryPa).forEach((item) => {
        newData[item] = queryPa[item][0];
    });

    // 总数据
    const COUNT_TOTAL = countTotal(newData);
    const total = SQL.query('system_sql', COUNT_TOTAL.query, ...COUNT_TOTAL.params);
    // 分页数据
    const LIST_DATA = selectData(newData);
    const result = SQL.query('system_sql', LIST_DATA.query, ...LIST_DATA.params);

    return okMsg({ result, count: total[0].count, pageNum: Number(newData.pageNum), pageSize: Number(newData.pageSize) });
}

function insert() {
    const data = payload.get().body?.toObject();
    const newData = { ...data };
    const columnsArr = Object.keys(newData);
    let dataArr = Object.values(newData);
    const placeholders = [];

    columnsArr.push(COLUMN_KEY)
    columnsArr.push('proprietor_id')
    columnsArr.push('proprietor_name')


    const suid = ex.suid().base58()
    dataArr.push(suid)
    dataArr.push(USER_INFO.user_id)
    dataArr.push(USER_INFO.nickname)

    dataArr.forEach(() => {
        placeholders.push('?');
    });
    placeholders.join(',');

    const columnsStr = columnsArr.join(',');
    const query = `INSERT INTO ${TABLE_NAME} (${columnsStr}) VALUES (${placeholders})`;
    const res = SQL.exec('system_sql', query, ...dataArr);
    if (res) {
        return okMsg(suid);
    }
    return errMsg(507, '添加失败');
}