import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
  RESULT_MSG_ERROR,
  RESULT_MSG_SUCCESS,
} from '@/constants/result-constants';
import { request } from '@/plugins/http-fetch';
import { parseFirstLower, parseObjLineToHump } from '@/utils/parse-utils';

/**
 * 查询配置参数标签栏
 * @param neType 网元类型
 * @returns object
 */
export async function getParamConfigTopTab(neType: string) {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/elementType/omc_db/objectType/param_config`,
    method: 'get',
    params: {
      SQL: `SELECT top_display,top_tag FROM param_config WHERE ne_type = '${neType}'`,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    let data = result.data.data[0];
    data = data['param_config'];
    if (Array.isArray(data)) {
      return Object.assign(result, {
        data: parseObjLineToHump(data),
      });
    }
    return Object.assign(result, {
      data: [],
    });
  }
  return result;
}

/**
 * 查询配置参数标签栏对应JSON信息
 * @param neType 网元类型
 * @returns object
 */
export async function getParamConfigTopTabJson(neType: string, topTag: string) {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/elementType/omc_db/objectType/param_config`,
    method: 'get',
    params: {
      SQL: `SELECT param_json FROM param_config WHERE ne_type = '${neType}' AND top_tag='${topTag}'`,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    let data = result.data.data[0];
    data = data['param_config'];
    if (Array.isArray(data)) {
      const v = data[0]['param_json'];
      try {
        result.data = JSON.parse(v);
      } catch (error) {
        console.error(error);
        result.data = {};
      }
    }
    return result;
  }
  return result;
}

/**
 * 查询配置参数标签栏对应信息
 * @param neType 网元类型
 * @returns object
 */
export async function getParamConfigInfo(
  neType: string,
  topTag: string,
  neId: string
) {
  const { wrRule, dataArr } = await Promise.allSettled([
    // 获取参数规则
    request({
      url: `/api/rest/databaseManagement/v1/elementType/omc_db/objectType/param_config`,
      method: 'get',
      params: {
        SQL: `SELECT param_json FROM param_config WHERE ne_type = '${neType}' AND top_tag='${topTag}'`,
      },
    }),
    // 获取对应信息
    request({
      url: `/api/rest/systemManagement/v1/elementType/${neType.toLowerCase()}/objectType/config/${topTag}`,
      method: 'get',
      params: {
        ne_id: neId,
      },
    }),
  ]).then(resArr => {
    let wrRule: Record<string, any> = {};
    // 规则数据
    if (resArr[0].status === 'fulfilled') {
      const itemV = resArr[0].value;
      // 解析数据
      if (
        itemV.code === RESULT_CODE_SUCCESS &&
        Array.isArray(itemV.data?.data)
      ) {
        let itemData = itemV.data.data;
        const data = itemData[0]['param_config'];
        if (Array.isArray(data)) {
          const v = data[0]['param_json'];
          try {
            itemData = parseObjLineToHump(JSON.parse(v));
            wrRule = itemData;
          } catch (error) {
            console.error(error);
          }
        }
      }
    }
    let dataArr: Record<string, any>[] = [];
    // 对应信息
    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;
        dataArr = parseObjLineToHump(itemData);
      }
    }
    return { wrRule, dataArr };
  });

  // UPF参数不统一
  if (neType === 'UPF') {
    if (Reflect.has(wrRule, 'list')) {
      for (const arr of wrRule['list']) {
        arr['name'] = parseFirstLower(arr['name']);
      }
      for (const item of dataArr) {
        for (const k in item) {
          item[parseFirstLower(k)] = item[k];
          Reflect.deleteProperty(item, k);
        }
      }
    }
    if (Reflect.has(wrRule, 'array')) {
      for (const arr of wrRule['array']) {
        if (Array.isArray(arr['array'])) {
          for (const child of arr['array']) {
            child['name'] = parseFirstLower(child['name']);
          }
        }
        arr['name'] = parseFirstLower(arr['name']);
      }
      for (const item of dataArr) {
        for (const k in item) {
          // 处理子列表
          if (Array.isArray(item[k])) {
            for (const child of item[k]) {
              for (const childKey in child) {
                child[parseFirstLower(childKey)] = child[childKey];
                Reflect.deleteProperty(child, childKey);
              }
            }
          }
          item[parseFirstLower(k)] = item[k];
          Reflect.deleteProperty(item, k);
        }
      }
    }
  }

  // 拼装数据
  const result = {
    code: RESULT_CODE_SUCCESS,
    msg: RESULT_MSG_SUCCESS,
    data: {
      type: 'list' as 'list' | 'array',
      data: [] as any[],
      dataRule: {},
      columns: [] as any[],
    },
  };

  // kv单列表
  if (Reflect.has(wrRule, 'list')) {
    result.data.type = 'list';
    const ruleArr = Object.freeze(wrRule['list']);

    // 列表项数据
    let dataList = [];
    for (const item of dataArr) {
      for (const key of Object.keys(item)) {
        // 规则为准
        for (const rule of ruleArr) {
          if (rule['name'] === key) {
            const ruleItem = Object.assign({}, rule, { value: item[key] });
            dataList.push(ruleItem);
            break;
          }
        }
      }
    }
    result.data.data = dataList;

    // 列表字段
    result.data.columns = [
      {
        title: 'Key',
        dataIndex: 'display',
        align: 'left',
        width: '30%',
      },
      {
        title: 'Value',
        dataIndex: 'value',
        align: 'left',
        width: '70%',
      },
    ];
  }
  // 多列表
  if (Reflect.has(wrRule, 'array')) {
    result.data.type = 'array';
    const ruleArr = Object.freeze(wrRule['array']);

    // 列表项数据
    const dataArray = [];
    for (const item of dataArr) {
      let record: Record<string, any> = {};
      for (const key of Object.keys(item)) {
        // 规则为准
        for (const rule of ruleArr) {
          if (rule['name'] === key) {
            const ruleItem = Object.assign({}, rule, { value: item[key] });
            record[ruleItem.name] = ruleItem;
            break;
          }
        }
      }
      dataArray.push(record);
    }
    result.data.data = dataArray;

    // 无数据时，用于新增
    let dataRule: Record<string, any> = {};
    for (const rule of ruleArr) {
      dataRule[rule.name] = rule;
    }
    result.data.dataRule = dataRule;

    // 列表字段
    const columns: Record<string, any>[] = [];
    for (const rule of ruleArr) {
      columns.push({
        title: rule.display,
        dataIndex: rule.name,
        align: 'left',
      });
    }
    result.data.columns = columns;
  }
  return result;
}

/**
 * 查询配置参数标签栏对应信息子节点
 * @param neType 网元类型
 * @param topTag
 * @param neId
 * @param loc 子节点（index/字段） 1/dnnList
 * @returns
 */
export async function getParamConfigInfoChild(
  neType: string,
  topTag: string,
  neId: string,
  loc: string
) {
  // 发起请求
  const result = await request({
    url: `/api/rest/systemManagement/v1/elementType/${neType.toLowerCase()}/objectType/config/${topTag}`,
    method: 'get',
    params: {
      ne_id: neId,
      loc: loc,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    return Object.assign(result, {
      data: parseObjLineToHump(result.data.data),
    });
  }
  return result;
}

/**
 * 修改配置参数标签栏对应信息
 * @param args 对象 {neType,neId,topTag,loc}
 * @param data 对象 {修改的数据kv}
 * @returns object
 */
export function updateParamConfigInfo(
  type: 'list' | 'array',
  args: Record<string, any>,
  data: Record<string, any>
) {
  let url = `/api/rest/systemManagement/v1/elementType/${args.neType.toLowerCase()}/objectType/config/${
    args.topTag
  }?ne_id=${args.neId}`;

  // 多列表需要loc
  if (type === 'array') {
    url += `&loc=${args.loc}`;
  }

  return request({
    url,
    method: 'put',
    data: data,
  });
}

/**
 * 新增配置参数标签栏对应信息
 * @param args 对象 {neType,neId,topTag,loc}
 * @param data 行记录对象
 * @returns object
 */
export function addParamConfigInfo(
  args: Record<string, any>,
  data: Record<string, any>
) {
  return request({
    url: `/api/rest/systemManagement/v1/elementType/${args.neType.toLowerCase()}/objectType/config/${
      args.topTag
    }?ne_id=${args.neId}&loc=${args.loc}`,
    method: 'post',
    data: data,
  });
}

/**
 * 删除配置参数标签栏对应信息
 * @param args 对象 {neType,neId,topTag,loc}
 * loc 多层表的定位信息{index0}/{paraName1}/{index1}
 * @param data 行记录对象
 * @returns object
 */
export function delParamConfigInfo(args: Record<string, any>) {
  return request({
    url: `/api/rest/systemManagement/v1/elementType/${args.neType.toLowerCase()}/objectType/config/${
      args.topTag
    }?ne_id=${args.neId}&loc=${args.loc}`,
    method: 'delete',
  });
}

/**
 * 更新网元配置重新载入
 * @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'] },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    const v = result.data.data[0];
    if (v && v.toLowerCase().includes('ok')) {
      delete result.data;
    } else {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR };
    }
  }
  return result;
}
