<template>
  <div v-loading="loading">
    <!--<MetricsCards v-model="metrics" :metric-items="metricsItems" @change="changeMetric"></MetricsCards>-->
    <!--<el-radio-group v-model="statDim" class="chart-button-group" @change="changeStatDim">-->
    <!--  <el-radio-button label="day">日</el-radio-button>-->
    <!--  <el-radio-button label="week" :disabled="!props.fetchLineWeek">周</el-radio按钮>-->
    <!--  <el-radio-button label="month" :disabled="!props.fetchLineWeek">月</el-radio按钮>-->
    <!--</el-radio-group>-->
    <div ref="chartRef" style="height: 350px"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { monthCompareMetricsEnum } from '/src/views/reportManage/dataCenter/utils/enum';
// import MetricsCards from '/@/components/MetricsCards/index.vue'
import XEUtils from 'xe-utils';
import { monthlyQueryParams } from '/src/views/reportManage/dataCenter/utils/tools';

defineOptions({
  name: 'DataTendencyChart',
});

interface Props {
  fetchLine: Function;
  query: { [key: string]: any };
  initMetric?: ShowMetric[];
  metricEnum?: { [key: string]: string }[];
}

const props = withDefaults(defineProps<Props>(), {
  initMetric: () => [
    {metric: 'sales', color: '#0085ff', label: '销售额'},
    {metric: 'planSales', color: '#3fd4cf', label: '计划销售额'},
    {metric: 'planSales', color: '#3fd4cf', label: '计划销售额'},
  ],
  metricEnum: () => monthCompareMetricsEnum,
});

const metrics = ref(props.initMetric);
const dataSet = ref([]);
let chartObj: any;
const chartRef = ref();
const option: any = {
  dataset: {
    source: [],
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      label: {
        backgroundColor: '#6a7985',
      },
    },
  },
  legend: {
    selected: {}, // 控制显隐
    show: false,
  },
  grid: {
    top: 50,
    right: 150,
    bottom: 30,
    left: 65,
  },
  xAxis: {
    type: 'category',
  },
  yAxis: [
    {
      id: 0,
      type: 'value',
      name: '',
      splitLine: {
        show: true, // 设置显示分割线
      },
      axisLine: {
        show: true,
        lineStyle: {color: ''},
      },
      show: true,
    },
    {
      id: 1,
      type: 'value',
      name: '',
      position: 'right',
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '',
        },
      },
      show: true,
    },
  ],
  series: [
    {
      id: 0,
      name: '',
      type: 'bar',
      encode: {
        x: 'data_datetime',
        y: '',
      },
      barMaxWidth: '18px',
      yAxisIndex: 0,
      itemStyle: {
        color: '',
        borderRadius: 4,
      },
    },
    {
      id: 1,
      name: '',
      type: 'bar',
      encode: {
        x: 'data_datetime',
        y: '',
      },
      barMaxWidth: '18px',
      yAxisIndex: 0,
      itemStyle: {
        color: '',
        borderRadius: 4,
      },
    },
  ],
};
const loading = ref(true);
const queryParams = computed(() => monthlyQueryParams(props.query));

onMounted(() => {
  addResize();
  setTimeout(() => {
    initLine();
  }, 0);
});
onBeforeUnmount(() => {
  if (chartObj) {
    chartObj.dispose();
    chartObj = null;
  }
  removeResize();
});

const initLine = async () => {
  chartObj = echarts.init(chartRef.value);
  option.dataset.source = dataSet.value;

  XEUtils.arrayEach(option.series, (info: any, index) => {
    const color = metrics.value[index].color;
    info.name = metrics.value[index].label;
    info.encode.y = metrics.value[index].metric;
    if (info.type === 'bar') {
      info.itemStyle.color = color;
    }
  });
  XEUtils.arrayEach(option.yAxis, (info: any, index) => {
    info.name = metrics.value[index].label;
    info.axisLine.lineStyle.color = metrics.value[index].color;
  });

  XEUtils.arrayEach(props.metricEnum, (info) => {
    option.legend.selected[info.label] = false;
  });
  for (const info of metrics.value) {
    option.legend.selected[info.label] = true;
  }

  chartObj.setOption(option);
  loading.value = false;
};

const getDataset = async () => {
  const resp = await props.fetchLine(queryParams.value);
  dataSet.value = resp.data;
};

const emit = defineEmits(['changeStatDim']);

let initialized = false;
watch(props.query, async () => {
  if (!initialized) {
    initialized = true;
    return;
  }
  loading.value = true;
  //const items = await getDataset();
  //const opt = {dataset: {source: items}};
  //chartObj.setOption(opt);
  chartObj.setOption(option, true);
  await getDataset()
  await initLine();
  loading.value = false;
});

const resizeChart = () => {
  chartObj.resize();
};
const addResize = () => {
  window.addEventListener('resize', resizeChart);
};
const removeResize = () => {
  window.removeEventListener('resize', resizeChart);
};
</script>

<style scoped>
.metrics-cards {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  width: 100%;
}

.chart-button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}
</style>