<template>
  <div class="unsafe-items-chart">
    <div class="chart-container" ref="itemsChart"></div>
    <div class="items-list">
      <div v-for="(item, index) in chartsData.items" :key="index" class="list-item">
        <div class="item-name">{{ item.name }}</div>
        <div class="item-value">{{ item.value }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'UnsafeItemsChart',
  props: {
    chartsData: {
      type: Object,
      default: () => ({
        items: [
          { name: '打火机', value: 57 },
          { name: '固体酒精', value: 55 },
          { name: '手机', value: 56 },
          { name: '不合格充电宝', value: 56 },
          { name: '登山杖', value: 55 }
        ]
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  watch: {
    chartsData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          if (this.chart) this.chart.dispose()
          this.initChart()
        })
      }
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.itemsChart) return
      this.chart = echarts.init(this.$refs.itemsChart)
      const option = {
        responsive: true,
        maintainAspectRatio: false,
        series: [{
          type: 'pie',
          radius: ['50%', '70%'],
          data: this.chartsData.items.map(item => ({
            name: item.name,
            value: item.value
          })),
          itemStyle: {
            color: function(params) {
              const colors = ['#60A5FA', '#A78BFA', '#34D399', '#FBBF24', '#F472B6']
              return colors[params.dataIndex]
            }
          },
          label: {
            show: true,
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            formatter: '{b}\n{d}%'
          }
        }]
      }
      this.chart.setOption(option)
    }
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose()
  }
}
</script>

<style lang="scss" scoped>
.unsafe-items-chart {
  .chart-container {
    height: 220rpx;
  }
  
  .items-list {
    margin-top: 16rpx;
  }
  
  .list-item {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;
    padding: 8rpx 0;
    
    .item-name {
      color: rgba(255, 255, 255, 0.7);
    }
    
    .item-value {
      color: rgba(255, 255, 255, 0.9);
    }
  }
}
</style>
