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

/**
 * 查询任务列表
 * @param query 查询参数
 * @returns object
 */
export async function listPerfTask(query: Record<string, any>) {
  let totalSQL = "select count(*) as total from measure_task where status!='DELETED' ";
  let rowsSQL = "select * from measure_task where status!='DELETED' ";

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

    // 排序
    let sortSql = ' order by create_time ';
    if (query.sortOrder === 'asc') {
      sortSql += ' asc ';
    } else {
      sortSql += ' desc ';
    }
  // 分页
  const pageNum = (query.pageNum - 1) * query.pageSize;
  const limtSql = ` limit ${pageNum},${query.pageSize} `;

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

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

/**
 * 查询任务详细
 * @param id 网元ID
 * @returns object
 */
export async function getPerfTask(id: string | number) {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/select/omc_db/measure_task`,
    method: 'GET',
    params: {
      SQL: `select * from measure_task where id = ${id}`,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    let data = result.data.data[0];
    return Object.assign(result, {
      data: parseObjLineToHump(data['measure_task'][0]),
    });
  }
  return result;
}

/**
 * 新增性能测量任务
 * @param data 网元对象
 * @returns object
 */
export function addPerfTask(data: Record<string, any>) {
  var time = new Date();
  var periods: any = [];
  var scheduule: any = [];
  //如果没选测量计划 则选择了测量时段也要置为空。因为二者是绑定关系
  if (data.smPlan.length && data.bigPlan.length) {
    data.periods.forEach((item: any) => {
      periods.push({ Start: item.split(',')[0], End: item.split(',')[1] });
    });
    scheduule.push({ Type: data.bigPlan, Days: data.smPlan });
  }

  let obj: any = {
    ne_type: data.neType,
    ne_ids: JSON.stringify([data.neId]),
    kpi_set: data.kpiSet,
    schedule: JSON.stringify(scheduule),
    start_time: data.startTime,
    end_time: data.endTime,
    granul_option: data.granulOption,
    status: 'Inactive',
    account_id: data.accountId,
    create_time: parseDateToStr(time),
    periods: JSON.stringify(periods),
    comment: data.comment,
  };

  return request({
    url: `/api/rest/databaseManagement/v1/omc_db/measure_task`,
    method: 'POST',
    data: { measure_task: [obj] },
  });
}

/**
 * 修改性能测量任务
 * @param data 网元对象
 * @returns object
 */
export function updatePerfTask(data: Record<string, any>) {
  var time = new Date();
  var periods: any = [];
  var scheduule: any = [];
  //如果没选测量计划 则选择了测量时段也要置为空。因为二者是绑定关系
  if (data.smPlan.length && data.bigPlan.length) {
    data.periods.forEach((item: any) => {
      periods.push({ Start: item.split(',')[0], End: item.split(',')[1] });
    });
    scheduule.push({ Type: data.bigPlan, Days: data.smPlan });
  }

  let obj: any = {
    ne_type: data.neType,
    ne_ids: JSON.stringify([data.neId]),
    kpi_set: data.kpiSet,
    schedule: JSON.stringify(scheduule),
    start_time: data.startTime,
    end_time: data.endTime,
    granul_option: data.granulOption,
    status: 'Inactive',
    account_id: data.accountId,
    create_time: parseDateToStr(time),
    periods: JSON.stringify(periods),
    comment: data.comment,
  };
  return request({
    url: `/api/rest/databaseManagement/v1/omc_db/measure_task?WHERE=id=${data.id}`,
    method: 'PUT',
    data: { measure_task: obj },
  });
}

/**
 * 删除任务
 * @param noticeId 网元ID
 * @returns object
 */
export async function delPerfTask(data: Record<string, any>) {
  return request({
    url: `/api/rest/performanceManagement/v1/elementType/${data.neType.toLowerCase()}/objectType/measureTask?id=${
      data.id
    }`,
    method: 'DELETE',
  });
}

/**
 * 获取性能测量指标列表
 * @returns object
 */
export async function getNePerformanceList() {
  // 发起请求
  const result = await request({
    url: `/api/rest/databaseManagement/v1/elementType/omc_db/objectType/measure_title`,
    method: 'GET',
    params: {
      SQL: `SELECT * FROM measure_title`,
    },
  });
  // 解析数据
  if (result.code === RESULT_CODE_SUCCESS && Array.isArray(result.data.data)) {
    let data = result.data.data[0];
    return Object.assign(result, {
      data: parseObjLineToHump(data['measure_title']),
    });
  }
  return result;
}


/**
 * 激活任务
 * @param
 * @returns bolb
 */
export function taskRun(data: Record<string, any>) {
  return request({
    url: `/api/rest/performanceManagement/v1/elementType/${data.neType.toLowerCase()}/objectType/measureTask?id=${data.id}`,
    method: 'POST',
  });
}

/**
 * 挂起任务
 * @param
 * @returns bolb
 */
export function taskStop(data: Record<string, any>) {
  return request({
    url: `/api/rest/performanceManagement/v1/elementType/${data.neType.toLowerCase()}/objectType/measureTask?id=${data.id}`,
    method: 'PUT',
  });
}