<template>
  <view class="chart-wrap" :style="{ height: heightPx }">
    <EChartsView :option="chartOption" class="chart" />
  </view>
</template>

<script lang="uts">
import EChartsView from '@/uni_modules/charts/EChartsView.vue'

type Item = { name: string; value: number }

export default {
  components: {
    EChartsView
  },
  props: {
    items: { type: Array, default: () => [] },
    height: { type: Number, default: 300 }
  },
  data() {
    return { 
      heightPx: '300px',
      chartOption: {} as any
    }
  },
  watch: {
    items: { handler() { this.updateOption() }, deep: true },
    height: { 
      handler() { 
        this.heightPx = `${this.height}px`
      } 
    }
  },
  mounted() {
    this.heightPx = `${this.height}px`
    this.updateOption()
  },
  methods: {
    updateOption() {
      const data = (this.items as Array<Item>).map((it) => ({
        name: it.name,
        value: (() => {
          const n = Number(it.value)
          return isFinite(n) ? n : 0
        })()
      }))
      this.chartOption = {
        tooltip: { trigger: 'item' },
        legend: { left: 0, bottom: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 12 } },
        series: [
          {
            type: 'pie',
            radius: ['55%', '75%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: true,
            label: { show: true, formatter: '{b}\n{d}%' },
            labelLine: { length: 10, length2: 10 },
            data
          }
        ]
      }
    }
  }
}
</script>

<style>
.chart-wrap { width: 100%; }
.chart { width: 100%; height: 100%; }
</style>
