import dayjs from 'dayjs';
import { stringify } from 'qs';
import { request } from 'umi';

// 能耗标牌
export async function query() {
  const res = await request(
    `/api/energy/v1/energy-card/list?project_id=${projectId}`,
  );
  return res;
}

// 全场概况 查询能耗配置相关
export async function queryEnergyConfig(projectId) {
  const res = await request(
    `/api/energy/v1/energy-config?project_id=${projectId}`,
  );
  return res;
}

// 当日累计能耗、吨水电耗、环比
export async function queryAccumulativeEnergy(projectId) {
  const res = await request(
    `/api/energy/v1/accumulative-energy?project_id=${projectId}`,
  );
  return res;
}

// 工艺段下总电耗曲线
export async function querySectionEnergy(params) {
  const res = await request(
    `/api/energy/v1/section-energy?${stringify(params)}`,
  );
  return res;
}

// 工艺段下各设备的用电情况
export async function querySectionDevice(params) {
  const res = await request(
    `/api/energy/v1/section-device?${stringify(params)}`,
  );
  return res;
}

// 吨水电耗折线图
export async function queryEnergyWaterChart(params) {
  const res = await request(
    `/api/energy/v1/energy-water-chart?${stringify(params)}`,
  );
  return res;
}

/**
 * 根据工艺段id查询code
 * @param {*} processId 工艺段id
 * @param {*} type 0 能耗 1 药耗 2 水质 3 水量
 * @param project_id
 * @returns
 */
export async function querySectionCode(processId, type, project_id) {
  const res = await request(
    `/api/energy/v1/section-code?process_section_id=${processId}&type=${type}&project_id=${project_id}`,
  );
  return res.data;
}

/**
 *
 * @param {*} data
 * @param {*} data.project_id
 * @param {*} data.metric_code
 * @param {*} data.start_time
 * @param {*} data.end_time
 * @returns
 */
export async function queryChartList(data) {
  if (!data.order) data.order = 2;
  const res = await request(`/api/energy/v1/chart/list`, {
    method: 'POST',
    data,
  });
  return res.data;
}

// 水检测折线图 参数同上
export async function queryWaterCheckChartList(data) {
  if (!data.order) data.order = 2;
  const res = await request(`/api/energy/v1/mon-chart/list`, {
    method: 'POST',
    data,
  });
  return res.data;
}

/**
 *  根据metric_code返回数据
 * @param {*} data 同queryChartList的data
 * @param {Array|string} codes metric_code
 * @param {Boolean} isCheck 是否为水检测数据
 * @returns [{ time:string, [code]:number}]
 */
export async function queryChartListByCode(data, codes, isCheck = false) {
  let dataSource = [];
  if (codes instanceof Array) {
    const res = {};
    let time = [];
    for (let i = 0; i < codes.length; i++) {
      const metric_code = codes[i];
      let chartRes;
      if (isCheck) {
        chartRes = await queryWaterCheckChartList({ ...data, metric_code });
      } else {
        chartRes = await queryChartList({ ...data, metric_code });
      }

      if (i == 0) {
        time = chartRes.data?.map((item) => item.data_time);
      }
      res[metric_code] = chartRes.data?.map((item) => item.value.toFixed(2));
    }
    console.log(res, codes);
    dataSource = time.map((time, index) => {
      const data = { time };
      codes.forEach((code) => {
        data[code] = res[code]?.[index];
      });
      return data;
    });
  } else if (typeof codes === 'string') {
    const res = await queryChartList({ ...data, metric_code: codes });
    dataSource = res.data.map((item) => ({
      time: item.data_time,
      [metric_code]: item.value,
    }));
  }
  return { data: dataSource };
}

/**
 *
 *
 * @param {*} metric_code //药耗code数组
 * @param {*} water_code  //水质单个code
 * @param {*} params.start_time
 * @param {*} params.end_time
 *  @param {*} params.projectId
 * @returns
 */
export async function queryChartMedicineAndWater(
  metric_code,
  water_code,
  params,
) {
  const data = {};
  let time = [];
  const waterRes = await queryChartList({
    project_id: params.projectId,
    start_time: params.start_time,
    end_time: params.end_time,
    metric_code: water_code?.metric_code,
    order: 1,
  });
  data[water_code.metric_code] = {
    data: waterRes.map((item) => item.value),
    type: 2,
    name: water_code?.metric,
    yIndex: 0,
  };
  if (metric_code instanceof Array) {
    for (let index = 0; index < metric_code.length; index++) {
      const element = metric_code[index];
      const res = await queryChartList({
        project_id: params.projectId,
        start_time: params.start_time,
        end_time: params.end_time,
        metric_code: element?.metric_code,
        order: 1,
      });
      if (index == 0) {
        time = res.map((item) => item.data_time);
      }
      // type	是	0 能耗 1 药耗 2 水质 3 水量
      data[element.metric_code] = {
        data: res.map((item) => item.value),
        type: 0,
        name: element?.metric,
        yIndex: 1,
      };
    }
  }
  return { data: { data, time } };
}

export async function queryProcessSection(projectId) {
  const res = await request(
    `/api/v1/process-section/${projectId}?page_size=999`,
  );
  return { data: res?.data?.list };
}

export async function queryAnalysisDict() {
  const res = await request(
    `/api/analysis/v1/analysis-dict/list?page_size=9999`,
    {
      method: 'POST',
    },
  );
  return { data: res?.data?.list };
}

export async function queryAnalysisDictByParams(params) {
  const res = await request(
    `/api/analysis/v1/analysis-dict/list?${stringify(params)}`,
    {
      method: 'POST',
    },
  );
  return { data: res?.data?.list };
}

// 成本分析-能耗监测
export async function queryEnergyChartList(data) {
  if (!data.order) data.order = 2;
  const res = await request(`/api/energy/v1/energy-chart/list`, {
    method: 'POST',
    data,
  });
  return res;
}

// 能耗管理导入列表
export async function queryEnergyUpload(data) {
  const res = await request(`/api/energy/v1/statday/list`, {
    method: 'POST',
    headers: { ContentType: 'application/json' },
    data,
  });
  return res;
}

export async function deleteEnergyUpload(data) {
  const res = await request(`/api/energy/v1/statday/del`, {
    method: 'POST',
    headers: { ContentType: 'application/json' },
    data,
  });
  return res;
}

export async function createStat(data) {
  await request(`/api/energy/v1/statday/create`, {
    method: 'POST',
    headers: { ContentType: 'application/json' },
    data,
  });
}

export async function modifySampleMetric(data) {
  const res = await request(`/api/energy/v1/sample-metric`, {
    method: 'POST',
    data,
  });
  return res;
}

export async function deleteBreakerExp(data) {
  const res = await request(`/api/energy/v1/beaker/del`, {
    method: 'POST',
    data,
  });
  return res;
}

export async function saveBreakerExp(data) {
  const res = await request(`/api/energy/v1/beaker/save`, {
    method: 'POST',
    data,
  });
  return res;
}

export async function editBreakerExp(data) {
  const res = await request(`/api/energy/v1/beaker/edit`, {
    method: 'POST',
    data,
  });
}

export async function queryBreakerExpList(data) {
  const res = await request(`/api/energy/v1/beaker/list`, {
    method: 'POST',
    data,
  });
  return res;
}

export async function querySampleMetric(params) {
  const res = await request(
    `/api/energy/v1/sample-metric-list?${stringify(params)}`,
  );
  return res;
}

// 水质异常
export async function queryQualityAbnormal(params) {
  const res = await request(`/api/task/v1/water-monitor/list`, {
    method: 'POST',
    headers: { ContentType: 'application/json' },
    data: params,
  });
  return res;
}

export async function dealQualityAbnormal(params) {
  await request(`/api/task/v1/set/water-monitor`, {
    method: 'POST',
    headers: { ContentType: 'application/json' },
    data: params,
  });
}

export async function getStatisticsChart(data_type) {
  let s_time;
  const e_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
  switch (data_type) {
    case '1':
      s_time = dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '2':
      s_time = dayjs().subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '3':
      s_time = dayjs().subtract(1, 'years').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '4':
      s_time = dayjs().subtract(5, 'years').format('YYYY-MM-DD HH:mm:ss');
      break;
  }
  const baseParams = {
    start_time: s_time,
    end_time: e_time,
    data_type,
    project_id: 65,
  };
  const params = [
    {
      ...baseParams,
      name: '北侧流量计',
      metric_code: '172_168_184_200.FIT111_TOT',
    },
    {
      ...baseParams,
      name: '南侧流量计',
      metric_code: '172_168_184_200.FIT112_TOT',
    },
  ];
  const dataList = [];
  let xData = [];
  for (let i = 0; i < params.length; i++) {
    const item = params[i];
    const res = await request(
      `/api/energy/v1/statistics/chart?${stringify(item)}`,
    );
    if (i == 0) {
      xData = res.data.data.map((item) =>
        dayjs(item.data_time).format('YYYY-MM-DD HH:mm:ss'),
      );
    }
    dataList.push({
      name: item.name,
      data: res.data.data.map((item) => item.value),
    });
  }
  return { data: { xData, dataList } };
}

/**
 * @param  {*} params
 * @returns {Promise<null>}
 */
export async function getComparisonData(params) {
  const res = await request(`/api/energy/v1/month/chart?${stringify(params)}`);
  return res?.data?.list;
}

export async function getChemicalAgents(projectID) {
  const res = await request(
    `/api/energy/v1/chemical_agents?project_id=${projectID}`,
  );
  return res?.data?.list;
}

export async function getScadaPage(params = {}) {
  const res = await request(`/api/v1/scada/page?${stringify(params)}`);
  return res?.data;
}
