// 修改数据
function sqlGenUpdate() {
    const commitData = payload.get().body?.toObject();
    let filter = payload.get().query[COLUMN_KEY];
    if (filter == undefined) {
        filter = payload.get().path.split("/").pop();
    }
    if (!filter) {
        return errMsg(507, "缺少主键参数");
    }
    var oldData = SQL.query(
        DB_NAME,
        `SELECT * FROM ${TABLE_NAME} WHERE ${COLUMN_KEY} = ?`,
        filter
    );
    if (!oldData || !oldData[0]) {
        return errMsg(507, "未找到原始数据");
    }

    oldData = oldData[0];

    const syncList = {};
    const cols = [];
    var linkBindColumn = {};
    TABLE_STRUCT.forEach((item) => {
        if (item.is_edit == 1) {
            if (
                item?.link_sync_type > 1 &&
                item?.link_db_name &&
                item?.link_table_name &&
                item?.link_column_name
            ) {
                linkBindColumn = TABLE_STRUCT.find(
                    (linkColumn) => linkColumn.column_name == item.link_bind_field
                );
                syncList[item.field_name] = {
                    db_name: item.link_db_name,
                    table_name: item.link_table_name,
                    self_field: item.link_bind_field,
                    link_field: item.link_column_name,
                    bind_field: linkBindColumn.link_column_name,
                };
            }
            cols.push(item.column_name);
        }
    });

    const updateArr = [];
    const dataArr = [];
    Object.keys(commitData).forEach((key) => {
        const colName = camelToUnderscore(key);
        if (cols.includes(colName)) {
            if (commitData[key] === "null" || commitData[key] === null) {
                updateArr.push(`${colName} = null`);
            } else if (commitData[key] != oldData[key]) {
                updateArr.push(`${colName} = ?`);
                dataArr.push(commitData[key]);
            }
        }
    });

    // 处理同步更新
    const syncData = handleSyncUpdate(syncList, commitData, oldData);
    Object.keys(syncData).forEach((dbName) => {
        payload.add.header("sql_exec", stmt);
        SQL.transaction(dbName, syncData[dbName].join(";"))
        // if (SQL.exec(dbName, syncData[dbName].join(";"))) {
        //     return errMsg(507, "同步更新失败");
        // }
    });

    if (updateArr.length > 0) {
        const stmt = `UPDATE ${TABLE_NAME} SET ${updateArr.join(",")} WHERE ${COLUMN_KEY} = ?`;
        if (TABLE_INFO.before_hook) {
            runtime.call(TABLE_INFO.before_hook);
        }
        payload.add.header("sql_exec", stmt);
        const result = SQL.exec(DB_NAME, stmt, ...dataArr, filter);
        if (TABLE_INFO.after_hook) {
            runtime.call(TABLE_INFO.after_hook);
        }
        if (result) {
            return okMsg(result);
        }
    }
    return errMsg(507, "参数错误或无可更新字段");
}

// 同步关联修改数据
function handleSyncUpdate(syncList, commitData, oldData) {
    const syncData = {};
    Object.keys(syncList).forEach((key) => {
        if (!syncData[syncList[key].db_name]) {
            syncData[syncList[key].db_name] = [];
        }
        if (commitData[key] == "null" || commitData[key] == null) {
            syncData[syncList[key].db_name].push(
                `UPDATE ${syncList[key].table_name} SET ${syncList[key].link_field} = null WHERE ${syncList[key].bind_field} = '${oldData[syncList[key].self_field]}'`
            );
        } else if (commitData[key] != oldData[key]) {
            syncData[syncList[key].db_name].push(
                `UPDATE ${syncList[key].table_name} SET ${syncList[key].link_field} = '${commitData[key]}' WHERE ${syncList[key].bind_field} = '${oldData[syncList[key].self_field]}'`
            );
        }
    });
    return syncData;
}