<script setup lang="ts">
import type { ReportIndicatorModel } from '@/model';

import type { LineSeriesOption } from 'echarts/charts';
import { LineChart }             from 'echarts/charts';

import type {
  GridComponentOption,
  LegendComponentOption,
  MarkLineComponentOption,
  TitleComponentOption,
  TooltipComponentOption,
} from 'echarts/components';
import {
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  TitleComponent,
  TooltipComponent,
  VisualMapComponent,
} from 'echarts/components';


import { use }            from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import VChart             from 'vue-echarts';


use([
  CanvasRenderer,
  LineChart, MarkLineComponent,
  GridComponent, VisualMapComponent,
  TitleComponent, TooltipComponent, LegendComponent,
]);


const props = defineProps<{
  dataset: ReportIndicatorModel;
  loading?: boolean;
}>();
const emits = defineEmits<{
  destroy: []
}>();

const option = ref({
  title: { text: '', top: 12, left: 'center' } as TitleComponentOption,
  tooltip: { trigger: 'axis' } as TooltipComponentOption,
  legend: { show: false, top: 12, right: 24 } as LegendComponentOption,
  grid: { top: 60, bottom: 24, left: 40, right: 60, containLabel: true } as GridComponentOption,
  xAxis: { type: 'category' } as any,
  yAxis: { type: 'value', scale: true, splitNumber: 10 } as any,
  visualMap: {
    pieces: [],
    show: false,
    type: 'piecewise',
  } as any,
  series: [] as ( LineSeriesOption & MarkLineComponentOption )[],

});
watchEffect(() => update(props.dataset));

function update(data: ReportIndicatorModel) {
  const range = data.range.map(t => +t);
  let min = range[ 0 ], max = range[ 1 ], source = [];
  const records = [ ...data.records ].reverse();
  for ( const { time, value } of records ) {
    source.push(time.format('YYYY/MM/DD'), value);
    min = Math.min(min, value);
    max = Math.max(max, value);
  }
  option.value.title.text = data.name;
  option.value.yAxis.name = data.unit;
  option.value.yAxis.min = Math.max(data.editor.min, Math.floor(min * 0.75));
  option.value.yAxis.max = Math.min(data.editor.max, Math.floor(max * 1.25));
  option.value.yAxis.minInterval = data.editor.step ?? 1;
  option.value.visualMap.pieces = [
    { gt: range[ 1 ], color: '#fc97af' },
    { gte: range[ 0 ], lte: range[ 1 ], color: '#72ccff' },
    { lt: range[ 0 ], color: '#fc97af' },
  ];
  option.value.series = [
    {
      name: data.name, smooth: true, type: 'line',
      data: records.map((record) => [ record.time.format('YYYY/MM/DD'), record.value ]),
      markLine: {
        data: data.range.map(value => (
          { yAxis: value }
        )),
      },
    },
  ];
}
</script>
<template>
  <v-chart class="chart-container" :option="option" :autoresize="true" />
</template>
<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
