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

/**
 * 查询告警设置
 * @param tag 配置ID
 * @returns object
 */
export async function getAlarmSet() {
  let arr = [];

  // 历史告警保存时间
  const logDurationResult = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'historyDuration'`,
    },
  });
  arr.push(logDurationResult);
  // 同步设置
  const logCapacityResult = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'syncTaskPeriod'`,
    },
  });
  arr.push(logCapacityResult);

  // 发起请求
  const result = await Promise.allSettled(arr).then(resArr => {
    let resultData: any = {};
    for (const item of resArr) {
      if (item.status === 'rejected') {
        continue;
      }
      const itemV = item.value;
      // 解析数据
      if (
        itemV.code === RESULT_CODE_SUCCESS &&
        Array.isArray(itemV.data.data)
      ) {
        let itemData = itemV.data.data[0];
        const v = parseObjLineToHump(itemData['config'][0]);
        let vJSON: any = {};
        if (v.configTag == 'syncTaskPeriod') {
          try {
            vJSON = JSON.parse(v.valueJson);
          } catch (error) {
            console.error(error);
          }
          resultData = { ...resultData, ...vJSON };
        } else {
          resultData[v.configTag] = parseInt(v.value);
        }
      }
    }
    if (Object.keys(resultData).length === 0) {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR, data: {} };
    }
    return {
      code: RESULT_CODE_SUCCESS,
      msg: RESULT_MSG_SUCCESS,
      data: resultData,
    };
  });
  return result;
}

/**
 * 修改告警设置
 * @param data 配置对象
 * @returns object
 */
export async function updateAlarmSet(data: Record<string, any>) {
  let { historyDuration, ...syncTaskPeriodJson } = data;
  let arr = [];

  // 历史告警保存时间
  const historyDurationResult = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='historyDuration'`,
    method: 'put',
    data: { data: { value: data.historyDuration.toString() } },
  });
  arr.push(historyDurationResult);
  // 同步设置
  const syncTaskPeriodResult = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='syncTaskPeriod'`,
    method: 'put',
    data: { data: { value_json: JSON.stringify(syncTaskPeriodJson) } },
  });
  arr.push(syncTaskPeriodResult);

  // 发起请求
  const result = await Promise.allSettled(arr).then(resArr => {
    let resultNum = 0;
    for (const item of resArr) {
      if (item.status === 'rejected') {
        continue;
      }
      const itemV = item.value;
      // 解析数据
      let itemData = itemV.data.data;
      if (itemV.code === RESULT_CODE_SUCCESS && itemData) {
        let rows = itemData.affectedRows;
        if (rows) {
          resultNum += rows;
        }
      }
    }
    // 无变更时
    if (resultNum === 0) {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR, data: 0 };
    }
    return {
      code: RESULT_CODE_SUCCESS,
      msg: RESULT_MSG_SUCCESS,
      data: resultNum,
    };
  });
  return result;
}

/**
 * 查询告警前转接口设置
 * @param tag 配置ID
 * @returns object
 */
export async function getForwardSet() {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'forwardAlarm'`,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    let data = result.data.data[0];
    const v = parseObjLineToHump(data['config'][0]);
    let vJSON: any = {};
    try {
      vJSON = JSON.parse(v.valueJson);
    } catch (error) {
      console.error(error);
    }
    return Object.assign(result, {
      data: vJSON,
    });
  }
  return result;
}

/**
 * 修改告警前转接口配置
 * @param data 配置对象
 * @returns object
 */
export async function updateForwardSet(data: Record<string, any>) {
  // return false;
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='forwardAlarm'`,
    method: 'put',
    data: { data: { value_json: JSON.stringify(data) } },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && result.data.data) {
    let rows = result.data.data.affectedRows;
    if (rows) {
      delete result.data;
      return result;
    } else {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR };
    }
  }
  return result;
}
