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

/**
 * Todo 废弃
 * 查询黄金指标数据
 * @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 = {
      data: { total: 0, rows: [] as any },
      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.data.total = itemData[0]['total'];
        } else {
          data.data.rows = itemData.map(v => parseObjLineToHump(v));
        }
      }
    });
    return data;
  }
  return result;
}

/**
 * 查询黄金指标数据
 * @param query 查询参数
 * @returns object
 */
export async function listKPIData(query: Record<string, any>) {
  const result = await request({
    url: `/neData/kpi/data`,
    method: 'GET',
    params: query,
    timeout: 60_000,
  });

  return result;
}

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

/**
 * Todo 废弃
 * 查询UPF上下行速率数据
 * @param query 查询参数
 * @returns object
 */
export async function listUPFData(timeArr: any) {
  const initTime: Date = new Date();
  const twentyFourHoursAgo: Date = new Date(
    initTime.getTime() - 10 * 60 * 1000
  );

  return await Promise.allSettled([
    // 获取参数规则
    request({
      url: `/api/rest/databaseManagement/v1/select/omc_db/gold_kpi`,
      method: 'GET',
      params: {
        SQL: `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 and gold_kpi.kpi_id ='UPF.03' AND timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND NOW()`,
      },
      timeout: 60_000,
    }),
    // 获取对应信息
    request({
      url: `/api/rest/databaseManagement/v1/select/omc_db/gold_kpi`,
      method: 'GET',
      params: {
        SQL: `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 and gold_kpi.kpi_id ='UPF.06' AND timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND NOW()`,
      },
      timeout: 60_000,
    }),
  ]).then(resArr => {
    let upData: any = [];
    let downData: any = [];

    // 规则数据
    if (resArr[0].status === 'fulfilled') {
      const itemV: any = resArr[0].value;
      // 解析数据
      if (
        itemV.code === RESULT_CODE_SUCCESS &&
        Array.isArray(itemV.data?.data)
      ) {
        let itemData = itemV.data.data;
        let data = itemData[0]['gold_kpi'];
        if (Array.isArray(data)) {
          try {
            upData = data.map(v => parseObjLineToHump(v));
          } catch (error) {
            console.error(error);
          }
        }
      }
    }

    if (resArr[1].status === 'fulfilled') {
      const itemV = resArr[1].value;
      // 解析数据
      if (
        itemV.code === RESULT_CODE_SUCCESS &&
        Array.isArray(itemV.data?.data)
      ) {
        let itemData = itemV.data.data;
        const data = itemData[0]['gold_kpi'];
        if (Array.isArray(data)) {
          try {
            downData = data.map(v => parseObjLineToHump(v));
          } catch (error) {
            console.error(error);
          }
        }
      }
    }
    return { upData, downData };
  });
}
