<template>
  <view class="pest-echart">
    <view class="pest-echart__header">
      <view class="tab-list">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeTab === index }"
          @click="switchTab(index)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <view class="pest-echart__content">
      <!-- 三个关键时期 -->
      <view class="period-section">
        <view class="period-item">
          <view class="period-label">始见期</view>
          <view class="period-value">{{ periodData.firstDate }}</view>
        </view>
        <view class="period-item">
          <view class="period-label">高峰期</view>
          <view class="period-value">{{ periodData.peakDate }}</view>
        </view>
        <view class="period-item">
          <view class="period-label">终见期</view>
          <view class="period-value">{{ periodData.lastDate }}</view>
        </view>
      </view>

      <!-- 图表区域 -->
      <view class="chart-container">
        <div id="pestChart" class="chart-canvas"></div>
      </view>
    </view>
  </view>
</template>

<script>
import * as echarts from 'echarts';

let chartInstance = null;

export default {
  name: 'PestEchart',
  props:{
    pest_order:{
      type: Object,
      default: () => ({})
    },
    endDate: {
      type: String,
      default: ''
    },
    d_id: {
      type: String | Number,
      default: ''
    },
    day:{
      type: Array,
      default: () => []
    },
    pest:{
      type: Array,
      default: () => []
    },
  },
  watch:{
    pest_order:{
      handler(val){
        this.tabs = [];
        for(let key in val){
          this.tabs.push({
            name: key,
          })
        }
        const name = this.tabs[0]?.name;
        this.currentPest = name;
        if(this.currentPest){
          this.getPestNameDetail(name);
          this.setChartData();
        }
      },
      deep: true
    },
    d_id:{
      handler(val){
        val && this.setChartData();
      },
      deep: true
    },
    endDate:{
      handler(val){
        val && this.setChartData();
      },
      deep: true
    },
    day:{
      handler(){
        this.initChart();
      },
      deep: true
    },
  },
  data() {
    return {
      tabs: [],
      currentPest:'',
      activeTab: 0,
      // 三个关键时期数据
      periodData: {
        firstDate: '-',
        peakDate: '-',
        lastDate: '-'
      },
      chartData: {},
      // 每个标签对应的数据
      tabData: []
    };
  },
  methods: {
    async getPestNameDetail(name){
      const res = await this.$myRequest({
        url: '/api/pest_name_detail',
        method: 'POST',
        data: {
          name
        },
      });
      this.deviceInfo = res
      this.$emit('getInfo',res)
    },
    async setChartData(){
      if(!this.currentPest){
        return;
      }
      if(!this.d_id || !this.endDate){
        return;
      }
     const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.cbd_analysis.pest_predict_time',
        method: 'POST',
        data: {
          model:'B',
          d_id: this.d_id,
          year: this.endDate.split('-')[0],
          pest: this.currentPest,
        },
      });
      this.periodData = {
        firstDate: res[0][0],
        peakDate: res[1][0],
        lastDate: res[2][0],
      }
    },
    initChart() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.drawChart();
        }, 100);
      });
    },
    drawChart() {
      // 销毁已有的图表实例
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }

      // 初始化图表
      const chartDom = document.getElementById('pestChart');
      if (!chartDom) return;

      // 确保 pest 数据是数字类型
      const dayData = this.day || [];
      const pestData = (this.pest || []).map(item => Number(item) || 0);

      chartInstance = echarts.init(chartDom);
      const option = {
        backgroundColor: '#FFFFFF',
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          show: false
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dayData,
          axisLine: {
            lineStyle: {
              color: '#CCCCCC'
            }
          },
          axisLabel: {
            fontSize: 11,
            color: '#999999'
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          minInterval: 1,
          splitNumber: 4,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#CCCCCC'
            }
          },
          axisLabel: {
            fontSize: 11,
            color: '#999999',
            formatter: (value) => Math.floor(value)
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#E5E5E5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '虫量',
            type: 'line',
            smooth: true,
            data: pestData,
            lineStyle: {
              color: '#0085FF',
              width: 2
            },
            itemStyle: {
              color: '#0085FF',
              borderColor: '#0085FF',
              borderWidth: 2
            },
            symbol: 'circle',
            symbolSize: 6,
          }
        ]
      };
      
      chartInstance.setOption(option, true);
      
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        chartInstance.resize();
      });
    },
    switchTab(index) {
      this.activeTab = index;
      // 更新数据
      const name = this.tabs[index]?.name;
      this.currentPest = name
      this.getPestNameDetail(name);
      this.setChartData();
      // this.periodData = this.tabData[index].periodData;
      // this.chartData = this.tabData[index].chartData;
      // 重新绘制图表
      this.$nextTick(() => {
        this.drawChart();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.pest-echart {
  overflow: hidden;
  margin-top: 24rpx;
}

.pest-echart__header {
  padding-top: 24rpx;
}

.tab-list {
  width: 100%;
  padding-bottom: 24rpx;
  overflow-x: scroll;
  white-space: nowrap;
  overflow-y: hidden;
  box-sizing: border-box;
  // 去掉滚动条
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.tab-item {
  margin-right: 16rpx;
  font-size: 28rpx;
  font-family: 'Source Han Sans CN VF', sans-serif;
  font-weight: 500;
  color: #999999;
  display: inline-block;
  box-sizing: border-box;
  background: #ffffff;
  font-family: "Source Han Sans CN VF";
  font-size: 28rpx;
  padding: 10rpx 32rpx;
  border-radius: 8rpx;
  &:last-child {
    margin-right: 0;
  }
  &.active {
    color: #0BBC58;
    font-weight: 700;
  }
  &:first-child.active {
    color: #0BBC58;
  }
}

.pest-echart__content {
  background: #FFFFFF;
  border-radius: 16rpx;
  padding: 0 32rpx 32rpx;
}

.period-section {
  display: flex;
  justify-content: space-between;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 12rpx;
}

.period-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.period-label {
  font-size: 28rpx;
  color: #303133;
  font-family: 'Source Han Sans CN VF', sans-serif;
  font-weight: 700;
  margin-bottom: 8rpx;
}

.period-value {
  font-size: 24rpx;
  color: #999999;
  font-family: 'Source Han Sans CN VF', sans-serif;
  font-weight: 400;
}

.chart-container {
  position: relative;
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.chart-canvas {
  width: 100%;
  height: 100%;
}
</style>