import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { request } from '@/plugins/http-fetch';
import { parseObjLineToHump } from '@/utils/parse-utils';
import { parseDateToStr } from '@/utils/date-utils';
import useUserStore from '@/store/modules/user';

/**
 * 获取活动告警数
 * @returns object
 */
export async function getActiveAlarmTotal() {
  let totalSQL = `select count(*)  as total from alarm where alarm_status='1'`;

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/alarm`,
    method: 'get',
    params: {
      SQL: totalSQL,
    },
  });

  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS) {
    const itemData = result.data.data;
    if (Array.isArray(itemData)) {
      const v = itemData[0]['alarm'];
      if (Array.isArray(v)) {
        result.data = v[0]['total'];
      }
    }
  }
  return result;
}

/**
 * 查询列表
 * @param query 查询参数
 * @returns object
 */
export async function listAct(query: Record<string, any>, filterSQl: string) {
  let totalSQL = `select count(*)  as total from alarm where alarm_status='1' ${filterSQl} `;
  let rowsSQL = `select * from alarm where alarm_status='1' ${filterSQl}`;
  // 查询
  let querySQL = '';
  debugger;
  if (query.alarmCode) {
    querySQL += ` and alarm_code = '${query.alarmCode}' `;
  }

  if (query.alarmType) {
    querySQL += ` and alarm_type = '${query.alarmType}' `;
  }

  if (query.pvFlag) {
    querySQL += ` and pv_flag = '${query.pvFlag}' `;
  }

  if (query.origSeverity) {
    querySQL += ` and orig_severity in('${query.origSeverity}' )`;
  }

  if (query.neId) {
    querySQL += ` and ne_id like '%${query.neId}%' `;
  }

  if (query.neName) {
    querySQL += ` and ne_name like '%${query.neName}%' `;
  }

  if (query.neType) {
    querySQL += ` and ne_type like '%${query.neType}%' `;
  }

  if (query.beginTime && query.endTime) {
    querySQL += ` and event_time BETWEEN '${query.beginTime}' and ' ${query.endTime}'`;
  }

  // 分页
  const pageNum = (query.pageNum - 1) * query.pageSize;
  const limtSql = ` order by event_time desc limit ${pageNum},${query.pageSize} `;

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/alarm`,
    method: 'get',
    params: {
      SQL: totalSQL + querySQL,
      rowsSQL: rowsSQL + querySQL + limtSql,
    },
  });

  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS) {
    const data: DataList = {
      total: 0,
      rows: [],
      code: result.code,
      msg: result.msg,
    };
    result.data.data.forEach((item: any) => {
      const itemData = item['alarm'];
      if (Array.isArray(itemData)) {
        if (itemData.length === 1 && itemData[0]['total'] >= 0) {
          data.total = itemData[0]['total'];
        } else {
          data.rows = itemData.map(v => parseObjLineToHump(v));
        }
      }
    });
    return data;
  }
  return result;
}

/**
 * 确认告警信息
 * @param data 鉴权对象
 * @returns object
 */
export function updateConfirm(data: Record<string, any>) {
  var time = new Date();
  const userName = useUserStore().userName;
  let finalData = {
    alarm: {
      ack_time: parseDateToStr(time),
      ack_user: userName,
      ack_state: '1',
    },
  };

  return request({
    url: `/api/rest/databaseManagement/v1/update/omc_db/alarm?WHERE=id='${data.id}'`,
    method: 'put',
    data: finalData,
  });
}

/**
 * 取消确认告警
 * @param data 鉴权对象
 * @returns object
 */
export function cancelConfirm(data: (string | number)[]) {
  var time = new Date();
  const userName = useUserStore().userName;
  let finalData = {
    alarm: {
      ack_time: parseDateToStr(time),
      ack_user: '',
      ack_state: '0',
    },
  };

  return request({
    url: `/api/rest/databaseManagement/v1/update/omc_db/alarm?WHERE=id in(${data.join(
      ','
    )})`,
    method: 'put',
    data: finalData,
  });
}

/**
 * 设置告警显示过滤
 * @param data 鉴权对象
 * @returns object
 */
export function showPass(data: Record<string, any>) {
  let querySQL = '';
  querySQL += data.alarm_code ? ` and alarm_code != ${data.alarm_code} ` : '';
  querySQL += data.alarm_type
    ? ` and alarm_type !=\\' ${data.alarm_type} \\'`
    : '';
  querySQL += data.pv_flag ? ` and pv_flag !=\\'${data.pv_flag} \\'` : '';
  querySQL += data.orig_severity
    ? ` and orig_severity !=\\'${data.orig_severity}\\'`
    : '';
  querySQL += data.ne_id ? ` and ne_id !=\\'${data.ne_id}\\' ` : '';
  querySQL += data.ne_type ? ` and ne_type !=\\'${data.ne_type}\\' ` : '';

  let toBackJson = {
    data: {
      value: querySQL,
      value_json: JSON.stringify(data),
    },
  };

  return request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='displayFilter'`,
    method: 'put',
    data: toBackJson,
  });
}
/**
 * 获取告警显示过滤条件
 * @param data 鉴权对象
 * @returns object
 */
export function getPass() {
  return request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/config`,
    method: 'get',
    params: {
      SQL: "SELECT value_json,value FROM config WHERE config_tag ='displayFilter'",
    },
  });
}

/**
 * 清除告警信息
 * @param data 鉴权对象
 * @returns object
 */
export function clearAlarm(data: Record<string, any>) {
  var time = new Date();
  const userName = useUserStore().userName;
  let finalData = {
    data: {
      clear_time: parseDateToStr(time),
      clear_type: '2',
      alarm_status: '0',
      clear_user: userName,
    },
  };

  return request({
    url: `/api/rest/databaseManagement/v1/update/omc_db/alarm?WHERE=id in(${data.join(
      ','
    )})`,
    method: 'put',
    data: finalData,
  });
}

/**
 * 手工同步
 * @param data 鉴权对象
 * @returns object
 */
export function listSync() {
  return request({
    url: `/api/rest/faultManagement/v1/elementType/all/objectType/alarms`,
    method: 'get',
  });
}

/**
 * 活动告警导出
 * @param query 查询参数
 * @returns bolb
 */
export async function exportAll(query: Record<string, any>) {
  let rowsSQL = `select * from alarm where alarm_status='1'`;
  // 查询
  let querySQL = '';
  querySQL += query.alarm_code
    ? ` and alarm_code = '${query.alarm_code}' `
    : '';
  querySQL += query.alarm_type
    ? ` and alarm_type = '${query.alarm_type}' `
    : '';
  querySQL += query.pv_flag ? ` and pv_flag = '${query.pv_flag}' ` : '';
  querySQL += query.orig_severity
    ? ` and orig_severity in('${query.orig_severity}' )`
    : '';
  querySQL += query.ne_id ? ` and ne_id like '%${query.ne_id}%' ` : '';
  querySQL += query.ne_name ? ` and ne_name like '%${query.ne_name}%' ` : '';
  querySQL += query.ne_type ? ` and ne_type like '%${query.ne_type}%' ` : '';
  querySQL +=
    query.beginTime && query.endTime
      ? ` and event_time BETWEEN '${query.beginTime}' and ' ${query.endTime}'`
      : '';

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/alarm`,
    method: 'get',
    params: {
      rowsSQL: rowsSQL + querySQL,
    },
  });

  if (result.code === RESULT_CODE_SUCCESS) {
    let v = result.data.data[0];
    const vArr = parseObjLineToHump(v['alarm']);
    result.data = vArr == null ? [] : vArr;
  }
  return result;
}
