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

/**
 * 查询备份列表
 * @param query 查询参数
 * @returns object
 */
export async function listNeBackup(query: Record<string, any>) {
  let totalSQL = 'select count(id) as total from ne_backup ';
  let rowsSQL = ' select * from ne_backup ';

  // 查询
  let querySQL = 'where 1=1';
  if (query.neType) {
    querySQL += ` and ne_type like '%${query.neType}%' `;
  }

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

  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/ne_backup`,
    method: 'get',
    params: {
      totalSQL: 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['ne_backup'];
      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 noticeId 网元ID
 * @returns object
 */
export async function delNeBackup(data: Record<string, any>) {
  return request({
    url: `/api/rest/systemManagement/v1/${data.neType}/neBackup/${data.fileName}`,
    method: 'delete',
  });
}

/**
 * 获取备份信息文件
 * @param menuId 网元ID
 * @returns object
 */
export async function downloadNeBackup(data: Record<string, any>) {
  return await request({
    url: `/api/rest/systemManagement/v1/${data.neType}/neBackup/${data.fileName}`,
    method: 'get',
    responseType: 'blob',
  });
}
