<template>
  <view class="device-detail">
    <view class="device-detail__header">
      <u-icon
        size="36"
        class="arrow-left"
        name="arrow-left"
        @click="handleBack"
      ></u-icon>
      {{ deviceInfo.name }}
    </view>
    <view class="operation" @click.stop="isShowOperation = !isShowOperation">操作</view>
    <view class="operation-container" v-if="isShowOperation" @click="closeOperationHandler">
      <view class="operation-background"></view>
      <view class="operation-content">
        <view class="operation-item" v-if="isShowPhoto" @click="handlePhotoClick">
          <image :src="photoIcon" class="operation-icon"></image>
          拍照
        </view>
        <view class="operation-item" @click="handleServiceClick">
          <image :src="serviceIcon" class="operation-icon"></image>
          维修
        </view>
        <view class="operation-item" @click="handleSettingClick">
          <image :src="settingIcon" class="operation-icon"></image>
          设置
        </view>
        <view class="operation-item" @click="handleSimClick">
          <image :src="simIcon" class="operation-icon"></image>
          SIM卡
        </view>
        <view class="operation-item" @click="modification">
          <image :src="editIcon" class="operation-icon"></image>
          修改
        </view>
      </view>
    </view>
    <view class="device-detail__body">
      <DeviceCard
        :dataSource="deviceInfo"
        :collectTime="time"
        :title="deviceInfo.name"
        :deviceType="deviceType"
      />
      <view class="tabs">
        <view class="tab-container" v-if="isShowTab">
          <view class="tab-item" :class="activeTab === 'pestAnalysis'?'active':''" @click="handleTabClick('pestAnalysis')" v-if="disableShow">
            害虫分析
          </view>
          <view class="tab-item" :class="activeTab === 'aiAnalysis'?'active':''" @click="handleTabClick('aiAnalysis')" v-if="disableShow">
            AI智能分析
          </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-show="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 v-if="!pests.length">
          <u-empty text="暂无数据"></u-empty>
        </view>
      </view>
      <view v-if="activeTab === 'viewImage'">
        <!-- 实现下拉加载 -->
         <scroll-view class="scroll-view" scroll-y style="height: 60vh;" @scrolltolower="handleReachBottom">
          <photoImage
            :images="imageList"
            :pestList="pestList"
            :disableShow="disableShow"
            @changeTab="changeTab"
            :currentYear="currentYear"
            :deviceInfo="deviceInfo"
          />
        </scroll-view>
      </view>
      <view v-if="activeTab === 'aiAnalysis'">
        <AiChat
          :pestMessage="pestMessage"
        />
      </view>
      <view v-if="activeTab === 'deviceData'">
        <DeviceData
          :deviceStatic="deviceStatic"
          :deviceInfo="deviceInfo"
          :polylineList="polylineList"
          :deviceHistoryList="deviceHistoryList"
          :totalPage="totalPage"
          :currentPage="page"
          :page_size="page_size"
          @prevPage="prevPage"
          @nextPage="nextPage"
        />
      </view>
    </view>
    <u-calendar v-model="show" :mode="mode" range-color="#999" btn-type="success" active-bg-color="#0BBC58" range-bg-color="rgba(11,188,88,0.13)" @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';
import AiChat from './components/aiChat.vue';

export default {
  components: {
    DeviceCard,
    PestDiscern,
    AiChat,
    PestEchart,
    PestArchive,
    photoImage,
    DeviceData,
  },
  data(){
    return {
      isShowTab:false,
      showPicker: false,
      disableShow: false,
      isShowOperation: false,
      photoIcon:'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/photoIcon.png',
      editIcon:'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/editIcon.png',
      serviceIcon:'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/serviceIcon.png',
      simIcon:'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/simIcon.png',
      settingIcon:'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/settingIcon.png',
      totalPage:0,
      currentYear: new Date().getFullYear(),
      selectorRange: [],
      maxDate: this.formatDate(new Date()),
      minDate: this.formatDate(new Date(new Date().getFullYear(), 0, 1)),
      show: false,
      showSim: false,
      // 当前日期向前推30天 格式2026-01-01 月份和日期小于10的时候前面加个0
      startDate: this.formatDate(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)),
      endDate: this.formatDate(new Date()),
      mode: 'range',
      imageList: [],
      pest_order:{},
      pestMessage:'',
      deviceInfo: {},
      pestInfo: {},
      time: '',
      activeTab: 'pestAnalysis',
      deviceType: '',
      location: '',
      total: 0,
      imgTotal: 0,
      day: [],
      pest: [],
      page:1,
      is_pest:'',
      page_size:24,
      pestList:[],
      pest_names:'',
      pests:[],
      polylineList:[],
      isShowPhoto:false,
      deviceHistoryList:[],
      deviceStatic:{}
    }
  },
  onLoad(options){
    this.deviceInfo = JSON.parse(options.info);
    const newVal = this.deviceInfo;
    if (newVal.device_model == '11'){
      this.isShowPhoto = true
    } else if(newVal.device_model == '12'){
      this.isShowPhoto = false
    } else if(newVal.device_model == '13'){
      this.isShowPhoto = true
    } else if(newVal.device_model == '14'){
      this.isShowPhoto = true
    } else if(newVal.device_model == '15'){
      this.isShowPhoto = false
    } else{
      this.isShowPhoto = true
    }
    this.getPestAnalysis();
    this.isShow();
    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: {
    formatePestMessage(data) {
      if (data.length === 0) {
        this.pestMessage = '';
        return;
      }
      this.pestMessage = `当前设备位置为${this.deviceInfo.address}，在${this.startDate}至${this.endDate} 监测到的害虫如下：`;
      data.map((item, index) => {
        if(index === data.length - 1){
          this.pestMessage += `${item.name}：${item.value}头.`;
        } else {
          this.pestMessage += `${item.name}：${item.value}头,`;
        }
      });
    },
    handleReachBottom(){
      if (this.activeTab === 'viewImage') {
        if(this.imageList.length >= this.imgTotal){
          return
        }
        this.initImageList(true);
      }
    },
    handleSimClick(){
      // this.showSim = true;
      //`/pages/deviceDetails/weatherStation/${type}?deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`
      uni.navigateTo({
        url:
          '/pages/deviceDetails/weatherStation/simDetail?deviceInfo=' +
          encodeURIComponent(JSON.stringify(this.deviceInfo))
      }); 
    },
		modification() {
      uni.navigateTo({
        url:
          '/pages/equipList2/seabox/modification?data=' +
          JSON.stringify(this.deviceInfo) +
          '&id=' +
          this.deviceInfo.type,
      }); 
    },
    async handlePhotoClick(){
       const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.send_control.admin_device_control',
        method: 'POST',
        data: {
          device_type_id: this.deviceInfo.type,
          d_id: this.deviceInfo.d_id,
          cmd: 'takephoto',
        },
      });
      if(res){
        this.$u.toast('拍照成功')
      }
    },
    handleServiceClick(){
      uni.navigateTo({
        url: '/pages/afterSale/addafter?d_id=' + this.deviceInfo.d_id +'&device_id='+this.deviceInfo.id + '&device_type=' + this.deviceInfo.type,
      })
    },
    handleSettingClick(){
      uni.navigateTo({
        url: '/pages/cbd/deviceControl?deviceId=' + this.deviceInfo.id + '&d_id=' + this.deviceInfo.d_id,
      });
    },
    closeOperationHandler(){
      this.isShowOperation = false;
    },
    isShow(){
      // disable == 0 或者 device_model == 15 表示不可以查看
      if(!this.deviceInfo.d_id){
        return false;
      }
      let showStatus = true;
      if(this.deviceInfo.device_model == 15 || this.deviceInfo.device_model == 12){
        showStatus = false;
      }
      if(showStatus){
        this.activeTab = 'pestAnalysis';
      }else{
        this.activeTab = 'deviceData';
      }
      this.initAction();
      this.isShowTab = showStatus;
      if(this.deviceInfo.disable == 0){
        this.disableShow = false;
        if(showStatus){
          this.activeTab = 'viewImage';
          this.handleTabClick('viewImage');
        }
      }else{
        this.disableShow = true;
      }
    },
    prevPage(e){
      if(e == 1){
        return
      }
      this.page = e-=1;
      this.getDeviceHistoryData();
    },
    nextPage(e){
      if(e * this.page_size >= this.totalPage){
        return
      }
      this.page = e+=1;
      this.getDeviceHistoryData();
    },
    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.endDate的月份和日期加上选择的年份
        const timeDate = this.currentYear + '-' + this.endDate.split('-')[1] + '-' + this.endDate.split('-')[2];
        this.endDate = this.formatDate(new Date(timeDate));
        // 开始日期为结束日期前30天
        this.startDate = this.formatDate(new Date(new Date(this.endDate).getTime() - 30 * 24 * 60 * 60 * 1000));
        this.maxDate = this.formatDate(new Date());
        this.minDate = this.formatDate(new Date(new Date().getFullYear(), 0, 1));
      }else{
        // 结束日期为this.endDate的月份和日期加上选择的年份
        const timeDate = this.currentYear + '-' + this.endDate.split('-')[1] + '-' + this.endDate.split('-')[2];
        this.endDate = this.formatDate(new Date(timeDate));
        // 开始日期为结束日期前30天
        this.startDate = this.formatDate(new Date(new Date(this.endDate).getTime() - 30 * 24 * 60 * 60 * 1000));
        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.page = 1;
      this.initAction();
    },
    showCalendar(){
      this.show = true;
    },
    handleBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    initAction(){
      // this.pest_order = 
      if(this.activeTab === 'pestAnalysis'){
        this.getPestAnalysis();
      }else if(this.activeTab === 'aiAnalysis'){
        this.getAiAnalysis();
      }else if(this.activeTab === 'viewImage'){
        this.initPest();
        this.initImageList();
      }else if(this.activeTab === 'deviceData'){
        this.getDeviceData();
        this.getPolylineData();
        this.getDeviceHistoryData();
      }
    },
    getAiAnalysis(){

    },
    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(isLoadMore){
      if(isLoadMore){
        this.page++;
      }
      uni.showLoading({
        title: '加载中',
      })
      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 || [];
      uni.hideLoading();
      this.imgTotal = res?.num || 0;
      if (isLoadMore) {
        this.imageList = [...this.imageList, ...data];
      } else {
        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 + ' 00:00:00').getTime()/1000,// 转成毫秒
          end_time: new Date(this.endDate + ' 23:59:59').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 + ' 00:00:00').getTime()/1000,
          end_time: new Date(this.endDate + ' 23:59:59').getTime()/1000,
          page: this.page,
          page_size: this.page_size,
        },
      });
      const data = res?.data || [];
      this.totalPage = res.counts;
      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'
        },
      });
      console.log(res,'resresres')
      const pest_order = res?.pest_order;
      this.getInfo({});
      let total = 0;
      this.pests = [];
      const data = [];
      for(let key in pest_order){
        total += pest_order[key] || 0;
        this.pests.push({
          name: key,
          percent: (pest_order[key] / total) * 100
        })
        data.push({
          name: key,
          value: pest_order[key] || 0
        })
      }
      this.pest_order = pest_order;
      this.formatePestMessage([...data.reverse()]);
      this.day = res?.day || [];
      const pest = res?.pest || [];
      this.pest = 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;
  }
}
.operation-container{
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
}
.operation{
  position: fixed;
  top: 260rpx;
  right: 0;
  z-index: 999;
  width:48rpx;
  height: 100rpx;
  line-height: 50rpx;
  border-radius: 8px 0 0 8px;
  border-top: 4rpx solid #FFF;
  border-bottom: 4rpx solid #FFF;
  border-left: 4rpx solid #FFF;
  background: #dddfe6a3;
  color: #515153;
  text-align: center;
  font-family: "Source Han Sans CN VF";
  font-size: 24rpx;
  font-weight: 500;
  writing-mode: vertical-rl;
}
.operation-background{
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 998;
  background: #00000040;
}
.operation-content{
  position: fixed;
  top: 240rpx;
  right: 80rpx;
  height: 126rpx;
  display: flex;
  padding: 16rpx 32rpx;
  align-items: center;
  gap: 64rpx;
  z-index: 999;
  border-radius: 32rpx;
  border: 2rpx solid #FFF;
  background: #FFF;
  backdrop-filter: blur(8rpx);
  .operation-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #333333;
    text-align: center;
    font-family: "Source Han Sans CN VF";
    font-size: 24rpx;
    font-weight: 400;
  }
  .operation-icon{
    width: 58rpx;
    height: 58rpx;
  }
}
.device-detail {
  display: flex;
  width: 100%;
  min-height: calc(100vh - 112rpx);
  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: 110rpx;
        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;
      align-items: center;
      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;
      position: relative;
      .tabs-timer-item{
        width: 42%;
        color: #656565;
        text-align: center;
        font-family: "Source Han Sans CN VF";
        font-size: 24rpx;
        font-weight: 400;
      }
      .calendar-icon{
        margin-left: 24rpx;
      }
    }
    .tab-item {
      flex: 1;
      color: #999999;
      text-align: center;
      font-family: "Source Han Sans CN VF";
      font-size: 28rpx;
      font-weight: 400;
    }
    .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>