<template>
  <view class="pest-echart" v-show="tabs.length">
    <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" v-show="dayData.length">
      <!-- 三个关键时期 -->
      <!-- <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">
        <!-- <canvas
          canvas-id="pestChart"
          id="pestChart"
          class="charts"
          :style="{'width':cWidth*pixelRatio+'px','height':cHeight*pixelRatio+'px', 'transform': 'scale('+(1/pixelRatio)+')','margin-left':-cWidth*(pixelRatio-1)/2+'px','margin-top':-cHeight*(pixelRatio-1)/2+'px'}"
          @touchstart="touchChart($event)"
          @touchmove="moveChart($event)"
          @touchend="touchEndChart($event)"
          disable-scroll=true
        ></canvas> -->
        <qiun-data-charts type="line" :chartData="chartData" :opts="opts" :canvas2d="true" :inScrollView="true" :ontouch="true" />
      </view>
    </view>
  </view>
</template>

<script>
import uCharts from '../../../components/js_sdk/u-charts/u-charts/u-charts.js';

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: () => []
    },
  },
  data() {
    return {
      tabs: [],
      currentPest:'',
      activeTab: 0,
      dayData:[],
      // 三个关键时期数据
      periodData: {
        firstDate: '-',
        peakDate: '-',
        lastDate: '-'
      },
      chartData: {},
      // canvas 尺寸配置
      cWidth: 650,
      cHeight: 400,
      pixelRatio: 1,
      opts: {
        type: 'line',
        xAxis: {
          disableGrid: true,
          itemCount: 3,
          scrollShow: true
        },
        yAxis: {
          disableGrid: true,
          gridType: 'dash',
          splitNumber: 5,
          min: 0,
          format: (val) => {
            return Math.round(val)
          }
        },
        extra: {
          line: {
            type: 'curve'
          },
          tooltip: {
            format: {
              name: '',
              value: (val) => Math.round(val)
            }
          }
        },
        legend: {
        },
        enableScroll: true
      },
    };
  },
  watch:{
    pest_order:{
      handler(val){
        this.tabs = [];
        this.activeTab = 0;
        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,
      immediate: true
    },
  },
  mounted() {
    this.cWidth = uni.upx2px(650);
    this.cHeight = uni.upx2px(400);
    this.pixelRatio = uni.getSystemInfoSync().pixelRatio;
  },
  methods: {
    async getPestNameDetail(name){
      try{
        const res = await this.$myRequest({
          url: '/api/pest_name_detail',
          method: 'POST',
          data: {
            name
          },
        });
        this.deviceInfo = res
        this.$emit('getInfo',res)
      }catch(err){
        this.$emit('getInfo',{})
      }
    },
    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(() => {
        this.updateChartsData(0);
      });
    },
    drawChart(index) {
      const dayData = this.day || [];
      this.dayData = dayData;
      const pestData = this.pest[index];
      const ctx = uni.createCanvasContext('pestChart', this);
      chartInstance = new uCharts({
        context: ctx,
        type: 'line',
        fontSize: 11,
        legend: {
          show: false
        },
        background: '#FFFFFF',
        pixelRatio: this.pixelRatio,
        animation: true,
        dataLabel: false,
        categories: dayData,
        series: [{
          name: '',
          data: pestData
        }],
        color: ['#0085FF'],
        xAxis: {
          disableGrid: false,
          boundaryGap: 'justify',
          axisLine: true,
          lineColor: '#CCCCCC',
          fontColor: '#999999'
        },
        yAxis: {
          min: 0,
          minInterval: 1,
          splitNumber: 4,
          axisLine: true,
          lineColor: '#CCCCCC',
          fontColor: '#999999',
          gridType: 'dash',
          gridColor: '#E5E5E5'
        },
        width: this.cWidth * this.pixelRatio,
        height: this.cHeight * this.pixelRatio,
        extra: {
          line: {
            type: 'curve',
            width: 2,
            activeType: 'hollow'
          },
          tooltip: {
            showBox: true,
            bgOpacity: 0.7
          }
        }
      });
    },
    touchChart(e) {
      if (chartInstance) {
        chartInstance.scrollStart(e);
      }
    },
    moveChart(e) {
      if (chartInstance) {
        chartInstance.scroll(e);
      }
    },
    touchEndChart(e) {
      if (chartInstance) {
        chartInstance.scrollEnd(e);
        chartInstance.showToolTip(e, {
          format: function(item, category) {
            return category + ' ' + item.name + ':' + item.data
          }
        });
      }
    },
    switchTab(index) {
      this.activeTab = index;
      const name = this.tabs[index]?.name;
      this.currentPest = name
      this.getPestNameDetail(name);
      this.setChartData();
      this.$nextTick(() => {
        this.updateChartsData(index);
      });
    },
    updateChartsData(index){
      const dayData = this.day || [];
      this.dayData = dayData;
      const pestData = this.pest[index];
      const lineData = {
        categories: dayData,
        series: [
          {
            name: '',
            data: pestData
          }
        ]
      };
      
      this.chartData = lineData;
    }
  }
};
</script>

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

.tab-list {
  width: 100%;
  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;
}

.charts {
  width: 100%;
  height: 100%;
}
</style>
