<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 x = (this.items as Array<Item>).map((it) => it.name)
      const y = (this.items as Array<Item>).map((it) => {
        const n = Number(it.value)
        return isFinite(n) ? n : 0
      })
      this.chartOption = {
        grid: { left: 80, right: 24, top: 18, bottom: 18 },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: { type: 'value', axisLabel: { color: 'rgba(0,0,0,0.55)' }, splitLine: { lineStyle: { color: 'rgba(0,0,0,0.06)' } } },
        yAxis: { type: 'category', data: x, axisTick: { show: false }, axisLabel: { color: 'rgba(0,0,0,0.65)' } },
        series: [{ type: 'bar', data: y, barWidth: 14, itemStyle: { borderRadius: 6 } }]
      }
    }
  }
}
</script>

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