<script setup lang="ts">
import { provide, ref }                      from 'vue';
import VChart, { type EChartsOption, theme } from './echart';


const { dataset = [] } = defineProps<{ dataset?: any[][] }>();

const snapshot = defineModel('snapshot', { default: '' });

provide(...theme);

const option = ref<EChartsOption>({
  backgroundColor: 'transparent',
  dataset: {
    dimensions: [ '体质', '得分', '类别' ],
    source: [],
  },
  grid: {
    containLabel: true,
    top: 50,
    bottom: 10,
    left: 10,
    right: 10,
  },
  xAxis: {
    type: 'category',
    splitLine: { show: false },
    axisTick: { show: false },
  },
  yAxis: {
    type: 'value', min: 0, max: 100, splitNumber: 5,
    axisLine: { show: false },
    axisLabel: { show: false },
  },
  visualMap: {
    type: 'piecewise',
    inRange: {},
    categories: [],
    dimension: 2,
    orient: 'horizontal',
    top: 10,
    right: 10,
  },
  series: [
    {
      type: 'bar',
      barMaxWidth: 30,
    },
  ],
});


const defaultSetting = [
  { label: '平和体质(正常体质)', color: '#38ff6e' },
  { label: '所属体质', color: '#ff8917' },
  { label: '倾向体质', color: '#ffbc5b' },
  { label: '推断体质', color: '#34a76b' },
  { label: '体质', color: '#b2b4ab' },
];

watchEffect(() => {
  const ref = new Set<number>(dataset.map(item => item[ 2 ]));
  const categories = [];
  const colors = [];
  for ( const key of ref ) {
    const { label, color } = defaultSetting[ key ] ?? {};
    if ( label ) categories.push(label);
    if ( color ) colors.push(color);
  }

  option.value.dataset = {
    ...option.value.dataset,
    source: dataset.map(item => [ item[ 0 ], item[ 1 ], defaultSetting[ item[ 2 ] ]?.label ]),
  };
  option.value.visualMap = {
    ...option.value.visualMap,
    categories,
    inRange: { color: colors },
  };
});

const chart = useTemplateRef<InstanceType<typeof VChart>>('chart');

function onFinished() {
  snapshot.value = chart.value?.getDataURL() ?? '';
}
</script>
<template>
  <div class="mx-auto">
    <div class="chart-container">
      <v-chart ref="chart" class="chart" :option="option" @finished="onFinished" />
    </div>
  </div>
</template>
<style scoped lang="scss">
.chart-container {
  position: relative;
  padding-bottom: 50%;

  > .chart {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
</style>
