import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { request } from '@/plugins/http-fetch';
import { parseDateToStr } from '@/utils/date-utils';
import { NE_TYPE_LIST } from '@/constants/ne-constants';

/**
 * 查询公告列表
 * @param query 查询参数
 * @returns object
 */
export async function listMain() {
  const result = await request({
    url: '/api/rest/systemManagement/v1/elementType/all/objectType/systemState',
    method: 'get',
    timeout: 60_000,
  });
  // console.log(result);
  let realData = result.data.data;
  const mergedData = realData.map((obj: any) => {
    // console.log(obj);
    const [key, value] = Object.entries(obj)[0];
    const ipAddress = (value as any).ipAddress;
    const systemState = (value as any).systemState;
    const serialNum = (value as any).serialNum;
    const version = (value as any).version;

    const errCode = systemState && systemState['errorCode'];
    var time = new Date();
    // console.log(key, value);
    let mergedObj;
    if (errCode === undefined && systemState) {
      mergedObj = {
        ...systemState,
        refresh: parseDateToStr(time),
        ipAddress: ipAddress,
        name: key.split('/').join('_'),
        status: 'Normal',
      };
    } else {
      mergedObj = {
        version,
        refresh: parseDateToStr(time),
        ipAddress,
        serialNum,
        name: key.split('/').join('_'),
        expiryDate: '-',
        status: 'Abnormal',
      };
    }
    return mergedObj;
  });
  //通过sort进行冒泡排序
  mergedData.sort((a: any, b: any) => {
    const typeA = NE_TYPE_LIST.indexOf(a.name.split('_')[0]);
    const typeB = NE_TYPE_LIST.indexOf(b.name.split('_')[0]);
    if (typeA === -1) return 1; // 如果不在特定顺序中，排到后面
    if (typeB === -1) return -1; // 如果不在特定顺序中，排到后面
    return typeA - typeB;
  });

  return mergedData;
}

/**
 * 获取服务器时间
 * @returns object
 */
export async function getServerTime() {
  // 发起请求
  const result = await request({
    url: `/api/rest/systemManagement/v1/elementType/OMC/objectType/time`,
    method: 'get',
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && result.data) {
    return Object.assign(result, {
      data: result.data.data,
    });
  }
  return result;
}

/**
 * 获取系统暴露的配置信息
 * @returns object
 */
export function getSysConf() {
  return request({
    url: `/sys-conf`,
    method: 'get',
    whithToken: false,
  });
}
