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 listgoldData(query: Record<string, any>) {
  let totalSQL = 'select count(*) as total from gold_kpi where 1=1 ';
  let rowsSQL =
    'SELECT gold_kpi.*,kpi_title.en_title FROM gold_kpi LEFT JOIN kpi_title on gold_kpi.kpi_id=kpi_title.kpi_id where 1=1 ';

  // 查询
  let querySQL = '';
  if (query.neType) {
    querySQL += ` and gold_kpi.ne_type like '%${query.neType}%' `;
  }
  if (query.beginTime) {
    querySQL += ` and start_time >= '${query.beginTime}' `;
  }
  if (query.endTime) {
    querySQL += ` and end_time <= '${query.endTime}' `;
  }

  // 排序
  let sortSql = ' order by  ';
  if (query.sortField) {
    sortSql += ` ${query.sortField} `;
  } else {
    sortSql += ` start_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/gold_kpi`,
    method: 'get',
    params: {
      totalSQL: totalSQL + querySQL,
      rowsSQL: rowsSQL + querySQL + sortSql + limtSql,
    },
    timeout: 60_000,
  });

  // 解析数据
  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['gold_kpi'];
      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;
}

/**
 * 查询黄金指标数据
 * @param query 查询参数
 * @returns object
 */
export async function goldData(query: Record<string, any>) {
  const result = await request({
    url: `/ne/kpi/data`,
    method: 'get',
    params: {
      neType: query.neType[0],
      neId: query.neType[1],
      startTime: query.beginTime,
      endTime: query.endTime,
      interval: query.particle,
      sortField:query.sortField,
      sortOrder:query.sortOrder
    },
    timeout: 60_000,
  });

  return result;
}

/**
 * 查询网元可用黄金指标
 * @param neType 网元类型
 * @returns object
 */
export async function getGoldTitleByNE(neType: string) {
  // 发起请求
  const result = await request({
    url: `/ne/kpi/title`,
    method: 'get',
    params: { neType },
  });
  // 解析数据
  return result;
}
