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 listMML(query: Record<string, any>) {
  let totalSQL = 'select count(*) as total from mml_log where 1=1 ';
  let rowsSQL = 'select * from mml_log where 1=1 ';

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

  // 排序
  let sortSql = ' order by log_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/mml_log`,
    method: 'GET',
    params: {
      totalSQL: totalSQL + querySQL,
      rowsSQL: rowsSQL + querySQL + sortSql + limtSql,
    },
  });

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