import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { request } from '@/plugins/http-fetch';
import { parseObjLineToHump } from '@/utils/parse-utils';

/**
 * 查询日志列表
 * @param query 查询参数
 * @returns object
 */
export async function listSecurityLog(query: Record<string, any>) {
  let totalSQL = 'select count(*) as total from security_log where 1=1 ';
  let rowsSQL = 'select * from security_log where 1=1 ';

  // 查询
  let querySQL = '';
  if (query.accountName) {
    querySQL += ` and account_name like '%${query.accountName}%' `;
  }
  if (query.opType) {
    querySQL += ` and op_type = '${query.opType}' `;
  }
  if (query.beginTime) {
    querySQL += ` and op_time >= '${query.beginTime}' `;
  }
  if (query.endTime) {
    querySQL += ` and op_time <= '${query.endTime}' `;
  }

  // 排序
  let sortSql = ' order by op_time ';
  if (query.sortOrder === 'asc') {
    sortSql += ' asc ';
  } else {
    sortSql += ' desc ';
  }

  // 分页
  const pageNum = (query.pageNum - 1) * query.pageSize;
  const limtSql = ` limit ${pageNum},${query.pageSize} `;

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/security_log`,
    method: 'get',
    params: {
      totalSQL: totalSQL + querySQL,
      rowsSQL: rowsSQL + querySQL + sortSql + limtSql,
    },
  });

  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS) {
    const data: DataList = {
      total: 0,
      rows: [],
      code: result.code,
      msg: result.msg,
    };
    result.data.data.forEach((item: any) => {
      const itemData = item['security_log'];
      if (Array.isArray(itemData)) {
        if (itemData.length === 1 && itemData[0]['total'] >= 0) {
          data.total = itemData[0]['total'];
        } else {
          data.rows = itemData.map(v => parseObjLineToHump(v));
        }
      }
    });
    return data;
  }
  return result;
}
