<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
import resize from '../mixins/resize'
import axios from 'axios'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '700px'
    },
    chartData: {
      type: Array,
      default: () => []
    },
    theme: {
      type: String,
      default: 'dark'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    theme() {
      this.setOptions(this.chartData)
    },
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(this.$el, 'macarons')
      
      // Check if map is already registered
      if (echarts.getMap('china')) {
        this.setOptions(this.chartData)
      } else {
        // Fetch China Map GeoJSON from local static assets
        // This ensures the map loads even without internet access or on non-local environments
        axios.get(process.env.BASE_URL + 'china.json')
          .then(response => {
            echarts.registerMap('china', response.data)
            this.setOptions(this.chartData)
          })
          .catch(error => {
            console.error('Failed to load China map data:', error)
          })
      }
    },
    setOptions(data) {
      if (!this.chart) return

      const isDark = this.theme === 'dark';
      const textColor = isDark ? '#fff' : '#333';
      
      let areaColor, borderColor, visualMapColor;

      switch (this.theme) {
        case 'orange':
          areaColor = '#fdf6ec';
          borderColor = '#faecd8';
          visualMapColor = ['#fdf6ec', '#e6a23c'];
          break;
        case 'light':
          areaColor = '#f0f9eb';
          borderColor = '#fff';
          visualMapColor = ['#f0f9eb', '#67c23a'];
          break;
        default: // dark
          areaColor = 'rgba(20, 41, 87, 0.6)';
          borderColor = '#4facfe';
          visualMapColor = ['#e0ffff', '#006edd'];
          break;
      }

      this.chart.setOption({
        backgroundColor: 'transparent',
        title: {
          text: '学员城市分布',
          left: 'center',
          top: 20,
          textStyle: {
            color: textColor,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
              if (params.value) {
                  return params.name + ': ' + params.value + '人';
              }
              return params.name;
          }
        },
        visualMap: {
          min: 0,
          max: data.length > 0 ? Math.max(...data.map(d => d.value)) : 100,
          left: '50',
          bottom: '50',
          text: ['高', '低'],
          textStyle: {
            color: textColor
          },
          calculable: true,
          inRange: {
            color: visualMapColor
          }
        },
        series: [
          {
            name: '学员分布',
            type: 'map',
            mapType: 'china',
            roam: true, // Allow zooming and panning
            zoom: 1.2,
            label: {
              show: true,
              color: textColor,
              fontSize: 10,
              formatter: function(params) {
                  if (params.value > 0) {
                      return params.name + '\n' + params.value;
                  }
                  return '';
              }
            },
            emphasis: {
                label: {
                    show: true,
                    color: textColor
                },
                itemStyle: {
                    areaColor: '#fbc2eb',
                    borderColor: '#fff',
                    borderWidth: 1
                }
            },
            itemStyle: {
                areaColor: areaColor,
                borderColor: borderColor,
                borderWidth: 1
            },
            data: data
          }
        ]
      })
    }
  }
}
</script>
