// 分页数据
function genSelectData(chooseData, placeholdersObj) {
    const newPlaceholders = placeholdersObj.placeholders;
    if (newPlaceholders != '') {
        const tempParams = placeholdersObj.tempParams;
        return {
            query: `SELECT ${chooseData} FROM ${TABLE_NAME} WHERE ${newPlaceholders}`,
            params: [...tempParams],
        };
    } else {
        return {
            query: `SELECT ${chooseData} FROM ${TABLE_NAME} WHERE 1`,
            params: [],
        };
    }
}

// 列表查询总数居
function genCountTotal(placeholdersObj) {
    const newPlaceholders = placeholdersObj.placeholders;
    if (newPlaceholders != '') {
        const tempParams = placeholdersObj.tempParams;
        return {
            query: `SELECT COUNT(*) AS count FROM ${TABLE_NAME} WHERE ${newPlaceholders}`,
            params: [...tempParams],
        };
    } else {
        return {
            query: `SELECT COUNT(*) AS count FROM ${TABLE_NAME} WHERE 1`,
            params: [],
        };
    }
}

// 分页列表查询
function genListPage(chooseData, placeholdersObj) {
    // 总数据
    const ROWS_COUNT = genCountTotal(placeholdersObj);
    ROWS_COUNT.query += searchStr
    stmt = ROWS_COUNT.query

    if (TABLE_INFO.before_hook) {
        runtime.call(TABLE_INFO.before_hook)
    }

    SQL_STMTS.push(stmt)
    result = SQL.query(DB_NAME, stmt, ...ROWS_COUNT.params);

    if (TABLE_INFO.after_hook) {
        runtime.call(TABLE_INFO.after_hook)
    }

    // 总数据
    const count = result
    // 分页数据
    const LIST_DATA = genSelectData(chooseData, placeholdersObj);
    if (parseInt(params.pageSize) > 1000) {
        response.status.code(413)
        return false
    }

    if (params.pageNum && params.pageSize) {
        searchStr += ` LIMIT ${(params.pageNum - 1) * parseInt(params.pageSize)}, ${parseInt(params.pageSize)}`
    }
    LIST_DATA.query += searchStr

    stmt = LIST_DATA.query

    // console.log(LIST_DATA.query)

    if (TABLE_INFO.before_hook) {
        runtime.call(TABLE_INFO.before_hook)
    }

    SQL_STMTS.push(stmt)
    result = SQL.query(DB_NAME, stmt, ...LIST_DATA.params);

    if (!result) return;

    const coverRes = result.sort(compareSorts)
    result = { result: coverRes, count: count[0].count, pageNum: params.pageNum, pageSize: params.pageSize }

    if (TABLE_INFO.after_hook) {
        runtime.call(TABLE_INFO.after_hook)
    }

    return result;
}

// 获取sql查询列表
function sqlGenList() {
    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}'`)
            }
            if (item.search_value) {
                searchStr += ` AND ${item.column_name} ${sql_operator[item.query_type]} '${item.search_value}'`
            }
            if (item.query_type == "NAN" || item.query_type == "VAL") {
                searchStr += ` AND ${item.column_name} ${sql_operator[item.query_type]}`
            }
        })

        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 > 0 AND delete_time IS NULL;`,
            TABLE_INFO.table_id
        )
    } else {
        TABLE_STRUCT.forEach(item => {
            if (item.search_value) {
                searchStr += ` AND ${item.column_name} ${sql_operator[item.query_type]} '${item.search_value}'`
            }
            if (item.query_type == "NAN" || item.query_type == "VAL") {
                searchStr += ` AND ${item.column_name} ${sql_operator[item.query_type]}`
            }
        })
    }

    var cols = []
    var groups = []
    var orders = []
    var distincts = []
    for (var i = 0; i < TABLE_STRUCT.length; i++) {
        if (TABLE_STRUCT[i].is_list == 1) {
            if (TABLE_STRUCT[i].is_acl == 1 && !userAccess.includes(TABLE_STRUCT[i].column_name)) {
                continue
            }

            // 运算规则 0 SUM 1 COUNT 2 AVG 3 MAX 4 MIN 5 VARIANCE 6 STDDEV 7 GROUP_CONCAT
            switch (TABLE_STRUCT[i].calc_type) {
                case 0:
                    cols.push(`SUM(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 1:
                    cols.push(`COUNT(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 2:
                    cols.push(`AVG(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 3:
                    cols.push(`MAX(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 4:
                    cols.push(`MIN(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 5:
                    cols.push(`VARIANCE(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 6:
                    cols.push(`STDDEV(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                case 7:
                    cols.push(`GROUP_CONCAT(${TABLE_STRUCT[i].column_name}) as ${TABLE_STRUCT[i].field_name}`)
                    break
                default:
                    cols.push(TABLE_STRUCT[i].column_name + ' as ' + TABLE_STRUCT[i].field_name)
                    break
            }

            if (TABLE_STRUCT[i].is_distinct == 1) {
                distincts.push(`${TABLE_STRUCT[i].field_name}`)
            }

            if (TABLE_STRUCT[i].is_group == 1) {
                groups.push(`${TABLE_STRUCT[i].field_name}`)
            }

            if (TABLE_STRUCT[i].is_order == 1) {
                orders.push(`${TABLE_STRUCT[i].field_name}`)
            }
        }
    }

    const chooseData = cols.join(',');
    if (chooseData == '') {
        return errMsg(507, '未设置列表字段')
    }

    if (TABLE_INFO.is_distinct == 1) {
        chooseData = `DISTINCT ${chooseData}`
    }

    distincts = distincts.join(',')
    if (distincts != '') {
        chooseData = `DISTINCT ${distincts}`
    }

    groups = groups.join(',')
    if (groups != '') {
        searchStr += ` GROUP BY ${groups}`
    }

    orders = orders.join(',')
    if (orders != '') {
        searchStr += ` ORDER BY ${orders} ${TABLE_INFO.order_type == 1 ? 'DESC' : 'ASC'}`
    }

    const placeholdersObj = formatCondition();
    const res = genListPage(chooseData, placeholdersObj);
    return okMsg(res);
}