import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
  RESULT_MSG_ERROR,
} from '@/constants/result-constants';
import { language, request } from '@/plugins/http-fetch';

/**
 * 更新网元配置重新载入
 * @param neType 网元类型
 * @param neId 网元ID
 * @returns
 */
export async function updateNeConfigReload(neType: string, neId: string) {
  // 发起请求
  const result = await request({
    url: `/api/rest/operationManagement/v1/elementType/${neType}/objectType/mml?ne_id=${neId}`,
    method: 'post',
    data: { mml: ['reload'] },
    timeout: 180_000,
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    const v = result.data.data[0];
    const str = v.toLowerCase();
    if (str.indexOf('ok') !== -1) {
      delete result.data;
    } else if (str.indexOf('success') !== -1) {
      delete result.data;
    } else {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR[language] };
    }
  }
  return result;
}

/**
 * 从参数配置PCF中获取对应信息提供给PCC用户策略输入框
 * @param neId
 * @returns object {pccRules,sessionRules,qosTemplate,headerEnrichTemplate,serviceAreaRestriction}
 */
export async function getPCCRule(neId: any) {
  const paramNameArr = [
    'pccRules',
    'sessionRules',
    'qosTemplate',
    'headerEnrichTemplate',
    'serviceAreaRestriction',
  ];
  const reqArr = [];
  for (const paramName of paramNameArr) {
    reqArr.push(
      request({
        url: `/ne/config/data`,
        params: { neType: 'PCF', neId, paramName },
        method: 'get',
      })
    );
  }
  return await Promise.allSettled(reqArr).then(resArr => {
    // 规则数据
    const obj: any = {};
    resArr.forEach((item, i: number) => {
      if (item.status === 'fulfilled') {
        const res = item.value;
        if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
          const key = paramNameArr[i];
          obj[key] = res.data.map((item: any) => {
            if ('qosTemplate' === key) {
              return { value: item.qosId, label: item.qosId };
            }
            if ('headerEnrichTemplate' === key) {
              return { value: item.templateName, label: item.templateName };
            }
            if ('serviceAreaRestriction' === key) {
              return { value: item.name, label: item.name };
            }
            return { value: item.ruleId, label: item.ruleId };
          });
        }
      }
    });
    return obj;
  });
}
