<template>
  <view class="chart-container">
    <view
      :id="chartId"
      class="echart-container"
      :change:prop="echartModule.updateChart"
      :prop="chartOption"
    ></view>
  </view>
</template>

<script>
export default {
  props: {
    budget: {
      type: Number,
      default: 0
    },
    used: {
      type: Number,
      default: 0
    },
    chartId: {
      type: String,
      default: 'budgetPieChart'
    }
  },
  computed: {
    chartOption() {
      const total = this.budget || 1
      const used = Math.min(this.used, total)
      const remaining = Math.max(total - used, 0)

      return {
        chartId: this.chartId,
        used: used,
        remaining: remaining
      }
    }
  }
}
</script>

<script module="echartModule" lang="renderjs">
const chartInstances = {}

export default {
  mounted() {
    // renderjs mounted时初始化
    if (typeof window !== 'undefined') {
      // 动态加载 echarts
      this.loadEcharts()
    }
  },
  methods: {
    loadEcharts() {
      // 检查是否已加载
      if (window.echarts) {
        return
      }

      // 动态加载 echarts 脚本
      const script = document.createElement('script')
      script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js'
      script.onload = () => {
        console.log('ECharts loaded successfully')
      }
      script.onerror = () => {
        console.error('Failed to load ECharts')
      }
      document.head.appendChild(script)
    },
    updateChart(newValue, oldValue, ownerInstance, instance) {
      // 等待 echarts 加载完成
      const checkEcharts = () => {
        if (!window.echarts) {
          setTimeout(checkEcharts, 100)
          return
        }
        this.renderChart(newValue)
      }
      checkEcharts()
    },
    renderChart(option) {
      if (!window.echarts || !option) return

      const chartDom = document.getElementById(option.chartId)
      if (!chartDom) {
        console.error('Chart container not found:', option.chartId)
        return
      }

      // 为每个图表ID创建独立的实例
      if (!chartInstances[option.chartId]) {
        chartInstances[option.chartId] = window.echarts.init(chartDom)
      }

      const chartInstance = chartInstances[option.chartId]

      // 设置图表配置
      const chartOption = {
        backgroundColor: 'transparent',
        series: [
          {
            type: 'pie',
            radius: ['60%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 20,
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'center',
              formatter: function() {
                return `{a|剩余预算}\n{b|¥${option.remaining.toFixed(2)}}`
              },
              rich: {
                a: {
                  fontSize: 13,
                  color: '#8D6E63',
                  lineHeight: 20,
                  fontWeight: 'normal'
                },
                b: {
                  fontSize: 17,
                  color: '#5D4037',
                  fontWeight: 'bold',
                  lineHeight: 32
                }
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: option.used,
                name: '已用',
                itemStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      { offset: 0, color: '#FA3534' },
                      { offset: 1, color: '#FF6B6B' }
                    ]
                  },
                  shadowBlur: 10,
                  shadowColor: 'rgba(250, 53, 52, 0.3)'
                }
              },
              {
                value: option.remaining,
                name: '剩余',
                itemStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      { offset: 0, color: '#FFD700' },
                      { offset: 1, color: '#F5D59E' }
                    ]
                  },
                  shadowBlur: 10,
                  shadowColor: 'rgba(255, 215, 0, 0.3)'
                }
              }
            ],
            emphasis: {
              scale: true,
              scaleSize: 5,
              itemStyle: {
                shadowBlur: 15,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.4)'
              }
            },
            animationType: 'scale',
            animationEasing: 'cubicOut',
            animationDelay: 0
          }
        ]
      }

      chartInstance.setOption(chartOption, true)

      // 调整图表尺寸
      setTimeout(() => {
        chartInstance.resize()
      }, 100)
    }
  },
  beforeDestroy() {
    // 清理所有图表实例
    Object.keys(chartInstances).forEach(key => {
      if (chartInstances[key]) {
        chartInstances[key].dispose()
        delete chartInstances[key]
      }
    })
  }
}
</script>

<style scoped>
.chart-container {
  width: 280rpx;
  height: 280rpx;
  margin: 0 auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.echart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
  min-width: 200px;
}
</style>
