<template>
  <template v-for="(images,index) in imagesList" :key="index">
    <album-carousel-item :farmId="farmId" :images="images"></album-carousel-item>
    <div style="height: 5px"></div>
  </template>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import AlbumDrawBoxItem from "./albumCarouselItem";
import "./cacheImg.js"
import AlbumCarouselItem from "./albumCarouselItem";
import {dateFormat} from "@/utils/date_util.js"
import eventBus from "@/api/eventBus";
const props =defineProps({
  // sampleId:{
  //   type: [Number, String],
  //   required: false
  // },
  farmId:{
    type: [Number, String],
    required: true
  },
  farmWork:{
    type: Object,
    required: false
  }
})
const imagesList = ref([]);
let params = {farmId: props.farmId}

onMounted(() => {
  if(props.farmWork?.executeDate){
    let execcuteDate = new Date(props.farmWork.executeDate)
    let beforeExecuteDate = new Date(props.farmWork.beforeExecuteDate)
    const pastDate = new Date(beforeExecuteDate);
    const futureDate = new Date(execcuteDate);
    params.startDate = dateFormat(pastDate, "YY-mm-dd");
    params.endDate = dateFormat(futureDate, "YY-mm-dd");
    params.limit = 20
  }
  getImageList(params)
});

const updateData = () =>{
  params.farmId = props.farmId
  getImageList(params)
}

onUnmounted(()=>{
  eventBus.off("chart:updateOption",updateData)
})

const getImageList = (params) =>{
  VE_API.image.list(params).then(res => {
    if(res.code === 0){
      let result = splitByWeek(res.data, params.startDate, params.endDate);
      if(result && result.length > 0){
        result = result.reverse()
      }
      for(let i=0;result != null && i<result.length;i++){
        if (result[i] && result[i].length > 0){
          imagesList.value.push(result[i])
        }
      }
    }
  })
}

eventBus.on("chart:updateOption",updateData)

function splitByWeek(items, startDate, endDate) {
  // 将开始时间和结束时间转换为时间戳
  const start = new Date(startDate).getTime();
  const end = new Date(endDate).getTime();

  // 创建一个用于存储按周分组的结果
  const weeklyGroups = [];

  // 遍历每一项
  items.forEach(item => {
    const uploadDate = new Date(item.uploadDate).getTime();

    // 确保上传日期在开始日期和结束日期之间
    if (uploadDate >= start && uploadDate <= end) {
      // 计算上传日期属于第几周
      const weekIndex = Math.floor((uploadDate - start) / (7 * 24 * 60 * 60 * 1000));

      // 如果该周的数组不存在，则创建一个
      if (!weeklyGroups[weekIndex]) {
        weeklyGroups[weekIndex] = [];
      }

      // 将当前项添加到对应的周数组中
      weeklyGroups[weekIndex].push(item);
    }
  });

  return weeklyGroups;
}


</script>

<style lang="scss" scoped>
@import "src/styles/index";
</style>
