import { EChartsOption } from 'echarts';
import moment from 'moment';
import { computed, ref, unref } from 'vue';
import { eChartOptions } from '../../localtion/config.data';
import { HistoryData } from '/@/api/alarm/position/model';
import { getDeviceAttributes } from '/@/api/dataBoard';
import { DeviceAttributeRecord } from '/@/api/dataBoard/model';
import { dateUtil } from '/@/utils/dateUtil';
import { isArray } from '/@/utils/is';
import { QueryWay } from '/@/views/report/config/config.data';
import { SchemaFiled } from '/@/views/visual/board/detail/config/historyTrend.config';
import { DEFAULT_DATE_FORMAT } from '/@/views/visual/board/detail/config/util';

interface DeviceOption {
  deviceProfileId: string;
}

export function useHistoryData() {
  const deviceAttrs = ref<DeviceAttributeRecord[]>([]);

  const getDeviceKeys = computed(() => {
    return unref(deviceAttrs).map((item) => item.identifier);
  });

  const getDeviceAttribute = async (record: DeviceOption) => {
    try {
      const { deviceProfileId } = record;
      const list = (await getDeviceAttributes({ deviceProfileId })) || [];
      deviceAttrs.value = isArray(list) ? list : [];
    } catch (error) {
      throw error;
    }
  };

  function getSearchParams(value: Partial<Record<SchemaFiled, string>>) {
    const { startTs, endTs, interval, agg, limit, keys, way, deviceId } = value;
    const basicRecord = {
      entityId: deviceId,
      keys: keys ? keys : unref(getDeviceKeys).join(),
      interval,
      agg,
      limit,
    };
    if (way === QueryWay.LATEST) {
      return Object.assign(basicRecord, {
        startTs: moment().subtract(startTs, 'ms').valueOf(),
        endTs: Date.now(),
      });
    } else {
      return Object.assign(basicRecord, {
        startTs: moment(startTs).valueOf(),
        endTs: moment(endTs).valueOf(),
      });
    }
  }

  function setChartOptions(
    data: HistoryData,
    keys?: DeviceAttributeRecord | DeviceAttributeRecord[]
  ) {
    const dataArray: [string, string, string][] = [];
    for (const key in data) {
      for (const item of data[key]) {
        let { value } = item;
        const { ts } = item;
        const time = dateUtil(ts).format(DEFAULT_DATE_FORMAT);
        value = Number(value).toFixed(2);
        dataArray.push([time, value, key as string]);
      }
    }

    keys = keys ? [keys as DeviceAttributeRecord] : unref(deviceAttrs);
    const legend = keys.map((item) => item.name);

    const series: EChartsOption['series'] = (keys as DeviceAttributeRecord[]).map((item) => {
      return {
        name: item.name,
        type: 'line',
        data: dataArray.filter((temp) => temp[2] === item.identifier),
      };
    });

    return eChartOptions(series, legend);
  }

  return {
    deviceAttrs,
    getDeviceKeys,
    getDeviceAttribute,
    getSearchParams,
    setChartOptions,
  };
}
