<template>
  <view class="device-detail">
    <view class="device-detail__header">
      <u-icon
        size="36"
        class="arrow-left"
        name="arrow-left"
        @click="handleBack"
      ></u-icon>
      {{ title }}
    </view>
    <view class="device-detail__body">
      <DeviceCard
        :dataSource="deviceInfo"
        :collectTime="time"
        :title="title"
        :deviceType="deviceType"
      />
      <view class="tabs">
        <view class="tab-container">
          <view class="tab-item" :class="activeTab === 'pestAnalysis'?'active':''" @click="handleTabClick('pestAnalysis')">
            害虫分析
          </view>
          <view class="tab-item" :class="activeTab === 'viewImage'?'active':''" @click="handleTabClick('viewImage')">
            查看图片
          </view>
          <view class="tab-item" :class="activeTab === 'deviceData'?'active':''" @click="handleTabClick('deviceData')">
            设备数据
          </view>
        </view>
        <view class="select-timer-container">
          <view class="select-year">
            <view class="select-year-item" @click="showPicker = true">
              {{ currentYear }}
              <u-icon name="arrow-down" size="18" class="arrow-down"></u-icon>
            </view>
          </view>
          <view class="tabs-timer-container" @click="showCalendar">
            <view class="tabs-timer-item">
              {{startDate}}
            </view>
            至
            <view class="tabs-timer-item">
              {{endDate}}
            </view>
            <u-icon name="calendar" size="36" class="calendar-icon"></u-icon>
          </view>
        </view>
      </view>
      <view v-if="activeTab === 'pestAnalysis'" class="tab-content">
        <PestDiscern
          :total="total"
          :pest_order="pest_order"
        />
        <PestEchart
          :pest_order="pest_order"
          @getInfo="getInfo" 
          :endDate="endDate"
          :d_id="deviceInfo.d_id"
          :day="day"
          :pest="pest"
        />
        <PestArchive
          :pest_info="pestInfo"
        />
      </view>
      <view v-if="activeTab === 'viewImage'">
        <photoImage
          :images="imageList"
          :pestList="pestList"
          @changeTab="changeTab"
          :currentYear="currentYear"
          :id="deviceInfo.id"
        />
      </view>
      <view v-if="activeTab === 'deviceData'">
        <DeviceData
          :deviceStatic="deviceStatic"
          :deviceInfo="deviceInfo"
          :polylineList="polylineList"
          :deviceHistoryList="deviceHistoryList"
        />
      </view>
    </view>
		<u-calendar v-model="show" :mode="mode" @change="handleChange" :max-date="maxDate" :min-date="minDate"></u-calendar>
		<u-picker v-model="showPicker" mode="selector" :range="selectorRange" range-key="id" :default-selector="[0]" @confirm="confirmHandler"></u-picker>
  </view>
</template>
<script>
import DeviceCard from './components/DeviceCard.vue';
import PestDiscern from './components/pestDiscern.vue';
import PestEchart from './components/pestEchart.vue';
import PestArchive from './components/pestArchive.vue';
import photoImage from './components/photoImage.vue';
import DeviceData from './components/deviceData.vue';

export default {
  components: {
    DeviceCard,
    PestDiscern,  
    PestEchart,
    PestArchive,
    photoImage,
    DeviceData
  },
  data(){
    return {
      showPicker: false,
      currentYear: new Date().getFullYear(),
      selectorRange: [],
      maxDate: this.formatDate(new Date()),
      minDate: this.formatDate(new Date(new Date().getFullYear(), 0, 1)),
      show: false,
      // 当前年份的第一天 格式2026-01-01 月份和日期小于10的时候前面加个0
      startDate: this.formatDate(new Date(new Date().getFullYear(), 0, 1)),
      endDate: this.formatDate(new Date()),
      mode: 'range',
      imageList: [],
      pest_order:{},
      deviceInfo: {},
      pestInfo: {},
      time: '',
      activeTab: 'pestAnalysis',
      title: '虫情测报灯详情',
      deviceType: '',
      location: '',
      total: 0,
      day: [],
      pest: [],
      page:1,
      is_pest:'',
      page_size:24,
      pestList:[],
      pest_names:'',
      polylineList:[],
      deviceHistoryList:[],
      deviceStatic:{}
    }
  },
  onLoad(options){
    this.deviceInfo = JSON.parse(options.info);
    this.getPestAnalysis();
    const currentYear = new Date().getFullYear();
    this.selectorRange = [];
    for(let i = 0;i<50;i++){
      const item = {
        label: currentYear - i,
        id: currentYear - i
      }
      this.selectorRange.push(item);
    }
  },
  methods: {
    changeTab(pestList){
      let pest_names = pestList.map(item => item.pest_name);
      this.pest_names = pest_names.join(',');
      this.initImageList();
    },
    confirmHandler(e){
      this.currentYear = this.selectorRange[e].id;
      if(this.currentYear == new Date().getFullYear()){
        this.startDate = this.formatDate(new Date(new Date().getFullYear(), 0, 1));
        this.endDate = this.formatDate(new Date());
        this.maxDate = this.formatDate(new Date());
        this.minDate = this.formatDate(new Date(new Date().getFullYear(), 0, 1));
      }else{
        this.startDate = this.formatDate(new Date(this.currentYear, 0, 1));
        this.endDate = this.formatDate(new Date(this.currentYear, 11, 31));
        this.maxDate = this.formatDate(new Date(this.currentYear, 11, 31));
        this.minDate = this.formatDate(new Date(this.currentYear, 0, 1));
      }
      this.initAction();
      this.showPicker = false;
    },
    getInfo(info){
      this.pestInfo = info;
    },
    // 格式化日期为YYYY-MM-DD格式，月份和日期小于10时前面加0
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleChange(e){
      this.startDate = e.startDate;
      this.endDate = e.endDate;
      this.initAction();
    },
    showCalendar(){
      this.show = true;
    },
    handleBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    initAction(){
      if(this.activeTab === 'pestAnalysis'){
        this.getPestAnalysis();
      }else if(this.activeTab === 'viewImage'){
        this.initPest();
        this.initImageList();
      }else if(this.activeTab === 'deviceData'){
        this.getDeviceData();
        this.getPolylineData();
        this.getDeviceHistoryData();
      }
    },
    handleTabClick(tab) {
      this.activeTab = tab;
      this.initAction();
    },
    async getDeviceData(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.worm_lamp.device_status_data',
        method: 'POST',
        data: {
          device_id: this.deviceInfo.id,
        },
      });
      this.deviceStatic = res;
    },
    async initImageList(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.new_cbd.photo_list',
        method: 'POST',
        data: {
          page:this.page,
          page_size:this.page_size,
          device_id: this.deviceInfo.id,
          is_pest: this.is_pest,
          identify_model: 'B',
          pest_names: this.pest_names,
          time_begin: this.formatDate(new Date(this.startDate)) + ' 00:00:00',// 格式化开始时间YYYY-MM-DD HH:MM:SS
          time_end: this.formatDate(new Date(this.endDate)) + ' 23:59:59',// 格式化结束时间YYYY-MM-DD HH:MM:SS
        },
      });
      const data = res?.data || [];
      this.imageList = data
    },
    async initPest(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.new_cbd.pest_type_list',
        method: 'POST',
        data:{
          page:1,
          page_size:999999,
          device_id: this.deviceInfo.id,
          identify_model: 'B',
          time_begin: this.formatDate(new Date(this.startDate)) + ' 00:00:00',// 格式化开始时间YYYY-MM-DD HH:MM:SS
          time_end: this.formatDate(new Date(this.endDate)) + ' 23:59:59',// 格式化结束时间YYYY-MM-DD HH:MM:SS
        },
      });
      const data = res?.data || [];
      this.pestList = data
    },
    async getPolylineData(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.worm_lamp.device_polyline_data',
        method: 'POST',
        data: {
          device_type_id: this.deviceInfo.type_id,
          d_id: this.deviceInfo.d_id,
          start_time: new Date(this.startDate).getTime()/1000,// 转成毫秒
          end_time: new Date(this.endDate).getTime()/1000,// 转成毫秒
        },
      });
      const data = res || [];
      this.polylineList = data
    },
    async getDeviceHistoryData(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.worm_lamp.device_history_data',
        method: 'POST',
        data: {
          device_type_id: this.deviceInfo.type_id,
          device_id: this.deviceInfo.id,
          start_time: new Date(this.startDate).getTime()/1000,
          end_time: new Date(this.endDate).getTime()/1000,
          page: this.page,
          page_size: this.page_size,
        },
      });
      const data = res?.data || [];
      this.deviceHistoryList = data
    },
    async getPestAnalysis(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.cbd_analysis.analysis_pest_result',
        method: 'POST',
        data: {
        d_id: this.deviceInfo.d_id,
        start: this.startDate,
        end: this.endDate,
        model: 'B'
        },
      });
      const pest_order = res?.pest_order;
      let total = 0;
      for(let key in pest_order){
        total += pest_order[key] || 0;
      }
      this.pest_order = pest_order;
      this.day = res?.day || [];
      const pest = res?.pest || [];
      this.pest = [];
      pest.forEach(p =>{
        for(let i = 0;i< p.length;i++){
          this.pest.push(p[i]);
        }
      })
      this.total = total;
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .u-calendar__action{
  display:flex;
  justify-content: space-between;
}
::v-deep .u-hover-class{
  .u-calendar__content__item__inner{
    color:#aaa !important;
  }
}
.device-detail {
  display: flex;
  width: 100%;
  height: 100vh;
  padding-top: 112rpx;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(180deg, #ffffff00 0%, #F5F6FA 23.64%, #F5F6FA 100%), linear-gradient(102deg, #BFEADD 6.77%, #B8F1E7 40.15%, #B9EEF5 84.02%);
  .device-detail__header {
    width: 100%;
    font-size: 28rpx;
    color: #999;
    color: #042118;
    font-family: 'Source Han Sans CN VF';
    font-weight: 700;
    position: relative;
    text-align: center;
    .arrow-left {
      position: absolute;
      left: 32rpx;
      margin-right: 12rpx;
    }
  }
  .device-detail__body {
    width: calc(100% - 64rpx);
    margin: 0 auto;
    border-radius: 16rpx;
    overflow-x: hidden;
    overflow-y: auto;
    // 隐藏滚动条
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  .tab-content{
    width: 100%;
    padding-bottom: 32rpx;
  }
  .tabs {
    background: #ffffff;
    margin: 24rpx 0;
    border-radius: 16rpx;
    padding: 16rpx 0;
    padding-top: 0;
    .tab-container{
      display: flex;
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 700;
      color: #042118;
      font-family: 'Source Han Sans CN VF';
    }
    .select-timer-container{
      display:flex;
      align-items: center;
      padding-left: 32rpx;
      .select-year{
        width: 128rpx;
        text-align: center;
        height: 64rpx;
        border-radius: 32rpx;
        font-family: 'Source Han Sans CN VF';
        line-height: 64rpx;
        background: #F1F4F8;
        padding: 0 32rpx;
        .select-year-item{
          color: #656565;
          font-size: 24rpx;
          display: flex;
          align-items: center;
          justify-content: space-around;
        }
      }
    }
    .tabs-timer-container{
      display: flex;
      width: calc(100% - 256rpx);
      height: 64rpx;
      line-height: 64rpx;
      text-align: center;
      font-size: 24rpx;
      font-weight: 500;
      font-family: 'Source Han Sans CN VF';
      border-radius: 32rpx;
      background: #F1F4F8;
      padding: 0 32rpx;
      color: #656565;
      margin: 16rpx 32rpx;
      position: relative;
      .tabs-timer-item{
        width: 40%;
        text-align: center;
        color: #656565;
        text-align: center;
        font-family: "Source Han Sans CN VF";
        font-size: 24rpx;
        font-weight: 400;
      }
      .calendar-icon{
        position: absolute;
        right: 78rpx;
        margin-top: 4rpx;
        top: 12rpx;
        right: 24rpx;
      }
    }
    .tab-item {
      flex: 1;
    }
    .active{
      position: relative;
      color: #303133;
      text-align: center;
      font-family: "Source Han Sans CN VF";
      font-size: 28rpx;
      font-weight: 700;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        width: 36rpx;
        height: 36rpx;
        border: 6rpx solid #0BBC58;
        border-radius: 50%;
        border-color: transparent;
        border-bottom-color: #0BBC58;
      }
    }
  }
}
</style>