// 添加数据
function sqlGenInsert() {
    var data = payload.get().body?.toObject()

    if (!data || (data && !Object.keys(data).length)) {
        return errMsg(404, '未传入参数')
    }

    let userAccess
    // 判断用户表权限
    if (TABLE_INFO.is_acl && !ALLOW_PUBLIC_ACCESS) {
        let udr = []
        udr.push(`'${USER_INFO.user_id}'`)
        udr.push(`'${USER_INFO.role_id}'`)
        udr.push(`'${USER_INFO.organization_id}'`)

        let columnIds = []
        TABLE_STRUCT.forEach(item => {
            if (item.is_acl == 1) {
                columnIds.push(`'${item.column_id}'`)
            }
        })

        userAccess = SQL.query(
            DB_NAME,
            `SELECT DISTINCT column_name FROM dm_table_columns_acl WHERE column_id IN (${columnIds.split(',')}) AND access_id IN (${udr.split(',')}) AND level = 2 AND delete_time IS NULL;`,
            TABLE_INFO.table_id
        )
    }

    var insertCols = []
    for (var i = 0; i < TABLE_STRUCT.length; i++) {
        if (TABLE_STRUCT[i].is_insert == 1) {
            if (TABLE_STRUCT[i].is_acl == 1 && !userAccess.includes(TABLE_STRUCT[i].column_name)) {
                continue
            }
            insertCols.push(TABLE_STRUCT[i].column_name)
        }
    }

    var dataArr = []
    var dataKeyArr = Object.keys(data)

    var dataId = ex.suid().base58()

    var cols = []
    var values = []
    // var cols = [COLUMN_KEY]
    // var cols = [COLUMN_KEY, 'proprietor_id', 'proprietor_name']
    // var values = [`'${dataId}'`]
    // var values = [`'${dataId}'`, `'${USER_INFO.user_id}'`, `'${USER_INFO.nickname}'`]
    let newItem

    // 如果table_struct 有proprietor_id字段，则自动添加
    if (TABLE_STRUCT.find(item => item.column_name === 'proprietor_id')) {
        cols.push('proprietor_id')
        values.push(`'${USER_INFO.user_id}'`)
        cols.push('proprietor_name')
        values.push(`'${USER_INFO.nickname}'`)
    }

    for (let i = 0; i < dataKeyArr.length; i++) {
        newItem = TABLE_STRUCT.find(itemT => itemT.field_name === dataKeyArr[i])
        if (!newItem) {
            console.error('未找到字段:', dataKeyArr[i])
            return errMsg(404, '未找到字段')
        }
        if (insertCols.includes(newItem.column_name)) {
            cols.push(newItem.column_name)
            values.push('?')

            if (newItem.column_name == COLUMN_KEY) {
                if (data[dataKeyArr[i]]) {
                    dataId = data[dataKeyArr[i]]
                } else {
                    data[dataKeyArr[i]] = dataId
                }
            }

            if (!data[dataKeyArr[i]] && newItem?.default_value) {
                data[dataKeyArr[i]] = newItem.default_value
            }

            if (data[dataKeyArr[i]] == "suid") {
                dataArr.push(ex.suid().base58())
            }

            dataArr.push(data[dataKeyArr[i]])
        }
    }

    if (!cols.includes(COLUMN_KEY)) {
        cols.push(COLUMN_KEY)
        values.push('?')
        dataArr.push(dataId)
    }

    for (var i = 0; i < TABLE_STRUCT.length; i++) {
        if (TABLE_STRUCT[i].is_required == 1 && !cols.includes(TABLE_STRUCT[i].column_name)) {
            return errMsg(507, `未填写必选项:${TABLE_STRUCT[i].column_name}`)
        }
    }

    stmt = `INSERT INTO ${TABLE_NAME}(${cols.join(',')}) VALUES (${values.join(',')})`
    if (TABLE_INFO.before_hook) {
        result = runtime.call(TABLE_INFO.before_hook)
    }
    payload.add.header("sql_exec", stmt)
    result = SQL.exec(DB_NAME, stmt, ...dataArr)
    if (TABLE_INFO.after_hook) {
        runtime.call(TABLE_INFO.after_hook)
    }
    if (!result) {
        console.error('添加失败')
        return errMsg(507, '添加失败')
    }

    stmt = `SELECT access_id,level FROM dm_tables_acl WHERE table_id =? AND delete_time IS NULL`
    if (TABLE_INFO.before_hook) {
        result = runtime.call(TABLE_INFO.before_hook)
    }
    SQL_STMTS.push(stmt)
    result = SQL.query('system_sql', stmt, TABLE_INFO.table_id)
    if (TABLE_INFO.after_hook) {
        runtime.call(TABLE_INFO.after_hook)
    }

    if (result) {
        result.forEach(item => {
            switch (item.access_id) {
                case 'self':
                    item.access_id = USER_INFO.user_id
                    break
                case 'role':
                    item.access_id = USER_INFO.role_id
                    break
                case 'dept':
                    item.access_id = USER_INFO.organization_id
                    break
            }
            if (TABLE_INFO.before_hook) {
                runtime.call(TABLE_INFO.before_hook)
            }
            SQL.push('system_sql', `INSERT INTO sys_data_acl (data_id,access_id,level,proprietor_id,proprietor_name) VALUES (?,?,?,?,?)`, dataId, item.access_id, item.level, USER_INFO.user_id, USER_INFO.nickname)
        })
    } else {
        if (TABLE_INFO.before_hook) {
            runtime.call(TABLE_INFO.before_hook)
        }
        SQL.push('system_sql', `INSERT INTO sys_data_acl (data_id,access_id,level,proprietor_id,proprietor_name) VALUES (?,?,?,?,?)`, dataId, item.user_id, 3, USER_INFO.user_id, USER_INFO.nickname)
    }
    return okMsg(dataId)
}