<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <div class="chart-header">
        <span>货品安装情况</span>
        <div class="chart-filters">
          <el-select v-model="month" placeholder="月" size="small" style="width: 100px;">
            <el-option label="本周" value="1"/>
            <el-option label="当月" value="2"/>
            <el-option label="近三月" value="3"/>
            <el-option label="近半年" value="4"/>
            <el-option label="全年" value="5"/>
          </el-select>
        </div>
      </div>
    </div>
    <div class="chart-wrapper">
      <div ref="chartRef" style="width: 100%; height: 100%;"></div>
    </div>
  </el-card>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'InstallationStatusChart',
  data() {
    return {
      chart: null,
      month: '2',
      lastData: null,
      localChartData: {
        xAxis: ['智能膜环', '精准阉割', '佳沃评分', '智能喷淋', '智能称重', '显示大屏'],
        series: {
          plan: [5000, 3500, 2800, 1500, 2000, 1000],
          finished: [4200, 2800, 2100, 1200, 1600, 800],
          rate: [84, 80, 75, 80, 80, 80]
        }
      }
    }
  },
  watch: {
    month() {
      this.$emit('filter-change', { month: this.month })
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartRef)
      this.updateChart(this.localChartData)
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    setChartOption(data) {
      if (!this.chart) return

      const option = {
        animation: true,
        animationDuration: 300,
        animationEasing: 'cubicOut',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let html = params[0].axisValue + '<br/>'
            params.forEach(item => {
              let color = item.color
              if (item.seriesName === '计划量') {
                color = 'rgb(0, 127, 255)'
              } else if (item.seriesName === '完成量') {
                color = 'rgb(255, 134, 42)'
              } else if (item.seriesName === '完成率') {
                color = 'rgb(68, 165, 60)'
              }
              const marker = '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:' + color + '"></span>'
              const value = item.seriesName === '完成率' ? item.value + '%' : item.value
              html += marker + item.seriesName + ': ' + value + '<br/>'
            })
            return html
          }
        },
        legend: {
          data: ['计划量', '完成量'],
          top: '0',
          left: 'center',
          orient: 'horizontal',
          itemGap: 30,
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.xAxis || [],
          axisLabel: {
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '单位/个',
          position: 'left',
          interval: 200,
          axisLine: {
            show: true
          },
          splitLine: {
            show: false
          }
        },
        series: [
          {
            name: '计划量',
            type: 'custom',
            barGap: '30%',
            itemStyle: {
              color: 'rgb(0, 127, 255)'
            },
            renderItem: (params, api) => {
              const location = api.coord([api.value(0), api.value(1)]);
              const start = api.coord([api.value(0), 0]);
              const size = api.size([0, api.value(1)]);
              const style = api.style();
              const radius = 7.5;
              const value = api.value(1);

              return {
                type: 'group',
                children: [{
                  type: 'rect',
                  shape: {
                    x: location[0] - radius,
                    y: location[1],
                    width: radius * 2,
                    height: Math.max(0, start[1] - location[1])
                  },
                  style: {
                    fill: 'rgb(0, 127, 255)'
                  }
                }, {
                  type: 'circle',
                  shape: {
                    cx: location[0],
                    cy: location[1],
                    r: radius
                  },
                  style: {
                    fill: 'rgb(0, 127, 255)'
                  }
                }, {
                  type: 'text',
                  style: {
                    text: value,
                    textFont: api.font({fontSize: 12}),
                    textFill: 'rgb(0, 127, 255)',
                    textAlign: 'center',
                    textVerticalAlign: 'bottom'
                  },
                  position: [location[0], location[1] - 10]
                }]
              }
            },
            data: data.series.plan || [],
            z: 2
          },
          {
            name: '完成量',
            type: 'custom',
            barGap: '30%',
            itemStyle: {
              color: 'rgb(255, 134, 42)'
            },
            renderItem: (params, api) => {
              const location = api.coord([api.value(0), api.value(1)]);
              const start = api.coord([api.value(0), 0]);
              const size = api.size([0, api.value(1)]);
              const style = api.style();
              const radius = 7.5;
              const value = api.value(1);

              return {
                type: 'group',
                children: [{
                  type: 'rect',
                  shape: {
                    x: location[0] - radius + 20,  // 向右偏移20个像素
                    y: location[1],
                    width: radius * 2,
                    height: Math.max(0, start[1] - location[1])
                  },
                  style: {
                    fill: 'rgb(255, 134, 42)'
                  }
                }, {
                  type: 'circle',
                  shape: {
                    cx: location[0] + 20,  // 向右偏移20个像素
                    cy: location[1],
                    r: radius
                  },
                  style: {
                    fill: 'rgb(255, 134, 42)'
                  }
                }, {
                  type: 'text',
                  style: {
                    text: value,
                    textFont: api.font({fontSize: 12}),
                    textFill: 'rgb(255, 134, 42)',
                    textAlign: 'center',
                    textVerticalAlign: 'bottom'
                  },
                  position: [location[0] + 20, location[1] - 10]
                }]
              }
            },
            data: data.series.finished || [],
            z: 2
          }
        ]
      }

      this.chart.setOption(option, false)
    },
    updateChart(data) {
      if (!this.chart) return

      const chartData = data || this.localChartData
      if (JSON.stringify(this.lastData) !== JSON.stringify(chartData)) {
        this.lastData = chartData
        this.setChartOption(chartData)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}

.chart-wrapper {
  background: #fff;
  padding: 24px;
  height: 500px;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .chart-filters {
    display: flex;
    align-items: center;
  }
}
</style>