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 getLogSet() {
  let arr = [];

  // 日志保存时间
  const logDurationResult = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'logDuration'`,
    },
  });
  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 = 'logCapacity'`,
    },
  });
  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]);
        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 updateLogSet(data: Record<string, any>) {
  let arr = [];
  for (const key in data) {
    const value = `${data[key]}`;
    const result = request({
      url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='${key}'`,
      method: 'put',
      data: { data: { value } },
    });
    arr.push(result);
  }

  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;
}

/**
 * 查询FTP日志设置
 * @param tag 配置ID
 * @returns object
 */
export async function getFtpLogSet() {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'ftpLogSet'`,
    },
  });
  // 解析数据
  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);
      vJSON['ftpLog'] = parseInt(vJSON['ftpLog']) || 12;
    } catch (error) {
      console.error(error);
    }
    return Object.assign(result, {
      data: vJSON,
    });
  }
  return result;
}

/**
 * 修改FTP日志配置
 * @param data 配置对象
 * @returns object
 */
export async function updateFtpLogSet(data: Record<string, any>) {
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='ftpLogSet'`,
    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;
}

/**
 * 查询日志远程输出设置
 * @param tag 配置ID
 * @returns object
 */
export async function getRemoteOut() {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config`,
    method: 'get',
    params: {
      SQL: `SELECT * FROM config WHERE config_tag = 'remoteLogSet'`,
    },
  });
  // 解析数据
  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 = {};
    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 updateRemoteOut(data: Record<string, any>) {
  const result = await request({
    url: `/api/rest/databaseManagement/v1/omc_db/config?WHERE=config_tag='remoteLogSet'`,
    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;
}

/**
 * 日志查询导出
 * @param query 查询参数
 * @returns bolb
 */
export async function exportLog(query: Record<string, any>) {
  // 查询
  let querySQL = '';
  if (query.logType === 'security_log') {
    querySQL = `SELECT account_name,account_type,op_ip,op_type,op_content,op_result,op_time
    FROM security_log 
    WHERE op_time >= '${query.beginTime}' AND op_time <= '${query.endTime}' 
    order by op_time`;
  }
  if (query.logType === 'alarm_log') {
    querySQL = `SELECT ne_type,ne_id,alarm_id,alarm_seq,alarm_code,alarm_status,event_time,log_time
    FROM security_log 
    WHERE log_time >= '${query.beginTime}' AND log_time <= '${query.endTime}' 
    order event_time,log_time`;
  }
  if (query.logType === 'operation_log') {
    querySQL = `SELECT account_name,account_type,op_ip,subsys_tag,op_type,op_content,op_result,begin_time,end_time,vnf_flag
    FROM operation_log 
    WHERE begin_time >= '${query.beginTime}' AND end_time <= '${query.endTime}' AND op_type ='${query.opType}' 
    order begin_time,end_time`;
  }
  if (!querySQL) {
    return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR };
  }
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/${query.logType}`,
    method: 'get',
    params: {
      SQL: querySQL,
    },
  });

  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS) {
    let v = result.data.data[0];
    const vArr = parseObjLineToHump(v[query.logType]);
    result.data = vArr == null ? [] : vArr;
  }
  return result;
}

/**
 * 日志手动备份
 * @param data 配置对象
 * @returns object
 */
export async function backupLog(logType: string) {
  const result = await request({
    url: `/api/rest/dataManagement/v1/omc_db/${logType}/backup`,
    method: 'post',
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && result.data.data) {
    let v = result.data.data[logType].affectedRows || 0;
    if (v) {
      result.data = v;
      return result;
    } else {
      return { code: RESULT_CODE_ERROR, msg: RESULT_MSG_ERROR };
    }
  }
  return result;
}

/**
 * 日志手动备份文件下载
 * @param data 配置对象
 * @returns object
 */
export async function backupDownload(path: string) {
  return request({
    url: `/api/rest/fileManagement/v1/path/file?path=${path}`,
    method: 'get',
    responseType: 'blob',
  });
}

/**
 * 日志手动备份文件列表
 * @param data 配置对象
 * @returns object
 */
export function backupFileList() {
  return request({
    url: `/api/rest/fileManagement/v1/files/listFiles`,
    method: 'post',
    data: {
      path: '/usr/local/omc/database',
      expand: true,
      showHidden: false,
      page: 1,
      pageSize: 100,
      search: '',
      containSub: false,
    },
  });
}
