// ==========================================================================
// 所属模块：core - gen - sql
// 生成日期：2024-02-19 00:24:00 +0800 CST
// 生成路径: dm/sql/sql.js
// 生成人：Cato
// 功能描述：定义全局通用的SQL的CURD功能封装，包含分页列表和模版查询、数据增删等等。（注册于global.js内)
// ==========================================================================

// 系统的sql数据库连接名为 system_sql

// 连接测试数据库
// var test_sql = SQL.new(
//     'mydb',
//     'mysql',
//     'root:123456@tcp(127.0.0.1:3306)/test_db'
// )

var stmt
var result
let searchStr = ''

'use api/dm/struct/table.js'

'use api/dm/sql/utils.js'

'use api/dm/sql/data.js'
'use api/dm/sql/list.js'
'use api/dm/sql/delete.js'
'use api/dm/sql/insert.js'
'use api/dm/sql/update.js'

'use api/dm/sql/formatCondition.js'
'use api/lib/requestQueryFormatSingle.js'
'use api/lib/camelAndUnderscore.js'

// 基本的CURD功能
function base_curd() {
  payload.set.header("Databus-Time", new Date().getTime())

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

    userAccess = SQL.query(
      'system_sql',
      `SELECT MAX(level) as level FROM dm_tables_acl WHERE table_id =? AND access_id IN (${udr.split(',')}) AND delete_time IS NULL;`,
      TABLE_INFO.table_id
    )

    if (userAccess) {
      userAccess = userAccess[0].level
    } else {
      return errMsg(403, '无权限')
    }
  }

  switch (payload.get().method) {
    case 'GET':
      if (TABLE_INFO.is_acl && userAccess < 1) {
        return errMsg(403, '无权限')
      }
      if (TABLE_INFO.is_acl && !getAclData(payload.get().query[COLUMN_KEY], 1)) {
        return errMsg(403, '无权限')
      }
      return sqlGenSelect()
    case 'PUT':
      if (TABLE_INFO.is_acl && userAccess < 2) {
        return errMsg(403, '无权限')
      }
      if (TABLE_INFO.is_acl && !getAclData(tableId, 1)) {
        return errMsg(403, '无权限')
      }
      return sqlGenUpdate()
    case 'POST':
      if (TABLE_INFO.is_acl && userAccess < 2) {
        return errMsg(403, '无权限')
      }
      return sqlGenInsert()
    case 'DELETE':
      if (TABLE_INFO.is_acl && userAccess < 3) {
        return errMsg(403, '无权限')
      }
      if (TABLE_INFO.is_acl && !getAclData(tableId, 3)) {
        return errMsg(403, '无权限')
      }
      return sqlGenDelete()
    default:
      response.status.notFound()
      return `404 page not found`
  }
}
