<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; margin-right: 10px;">
            <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>
          <el-select
            v-model="product"
            placeholder="货品"
            size="small"
            style="width: 120px;"
            :loading="productLoading"
          >
            <el-option label="全部" value="all"/>
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </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'
import _ from 'lodash'
import resize from './mixins/resize'
// import { getProductList } from '@/api/production' // 后续需要添加此API

export default {
  name: 'MonthlyChart',
  mixins: [resize],
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      month: '1',
      product: 'all',
      productLoading: false,
      productOptions: [],
      chart: null,
      // 示例数据
      defaultProductOptions: [
        { label: '智能膜环', value: '智能膜环' },
        { label: '智能喷淋', value: '智能喷淋' },
        { label: '佳沃评分', value: '佳沃评分' },
        { label: '大屏', value: '大屏' },
        { label: '耳标', value: '耳标' },
        { label: '智能称重', value: '智能称重' }
      ],
      // 图表示例数据
      localChartData: {
        xAxis: ['智能喷淋', '智能膜环', '提拉器', '精准喷喷', '奶台识别', '体况评分', '车载控制器', '大屏'],
        series: {
          plan: [2000, 600, 700, 970, 680, 840, 500, 1600],
          actual: [1600, 550, 500, 800, 430, 800, 500, 1600],
          rate: [80, 92, 71, 82, 63, 95, 100, 100]
        }
      },
      lastData: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      this.initProductOptions()
    })
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  watch: {
    month() {
      this.$emit('filter-change', { month: this.month, product: this.product })
    },
    product() {
      this.$emit('filter-change', { month: this.month, product: this.product })
    },
    chartData: {
      deep: true,
      handler(val) {
        this.updateChart(val)
      }
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartRef)
      this.setChartOption(this.localChartData)
    },
    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
            }
          },
          {
            type: 'value',
            name: '完成率(%)',
            position: 'right',
            max: 100,
            interval: 10,
            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: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgb(0, 127, 255)'
                    }, {
                      offset: 1,
                      color: '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',
                    x: location[0],
                    y: location[1] - 10
                  }
                }]
              };
            },
            data: data.series.plan || [],
            label: {
              show: true,
              position: 'top',
              distance: 10,
              fontSize: 12,
              color: 'rgb(0, 127, 255)',
              formatter: function(params) {
                return params.value
              }
            }
          },
          {
            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: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgb(255, 134, 42)'
                    }, {
                      offset: 1,
                      color: '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',
                    x: location[0] + 20,  // 向右偏移20个像素
                    y: location[1] - 10
                  }
                }]
              };
            },
            data: data.series.actual || [],
            label: {
              show: true,
              position: 'top',
              distance: 10,
              fontSize: 12,
              color: 'rgb(255, 134, 42)',
              formatter: function(params) {
                return params.value
              }
            }
          },
          {
            name: '完成率',
            type: 'line',
            yAxisIndex: 1,
            data: data.series.rate || [],
            symbolSize: 5,
            showSymbol: true,
            legendSymbol: 'circle',
            lineStyle: {
              width: 1,
              type: 'solid',
              color: 'rgb(68, 165, 60)'
            },
            itemStyle: {
              color: 'rgb(68, 165, 60)',
              borderColor: 'rgb(68, 165, 60)',
              borderWidth: 1
            },
            // label: {
            //   show: true,
            //   formatter: '{c}%',
            //   position: 'top',
            //   distance: 10,
            //   fontSize: 12,
            //   color: 'rgb(68, 165, 60)'
            // }
          }
        ]
      }

      // 使用 notMerge 参数为 false，只更新数据
      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)
      }
    },
    async initProductOptions() {
      try {
        this.productLoading = true
        await this.fetchProductList()
      } catch (error) {
        console.error('初始化产品列表失败:', error)
      } finally {
        this.productLoading = false
      }
    },
    async fetchProductList() {
      try {
        this.productLoading = true
        // 使用 Promise.race 添加超时处理
        const result = await Promise.race([
          this.getProductList(),
          new Promise((_, reject) =>
            setTimeout(() => reject(new Error('请求超时')), 5000)
          )
        ])

        this.productOptions = result || this.defaultProductOptions
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.$message.error(error.message || '获取产品列表失败')
        // 加载失败时使用默认选项
        this.productOptions = this.defaultProductOptions
      } finally {
        this.productLoading = false
      }
    },
    async getProductList() {
      try {
        // TODO: 后端接口完成后替换此处
        // const { data } = await getProductList()
        // this.productOptions = data.map(item => ({
        //   label: item.name,
        //   value: item.code
        // }))

        // 模拟接口调用
        await new Promise(resolve => setTimeout(resolve, 500))
        return this.defaultProductOptions
      } catch (error) {
        console.error('获取产品列表失败:', error)
        return null
      }
    }
  }
}
</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>