<template>
  <div class="screen-left">
    <!-- 水质设备 -->
    <water
      :height="waterHeight"
      :isExpanded="waterExpand"
      :controlExpand="controlExpand"
      :pond-options="pondOptions"
      :data="waterDeviceData"
      @pond="handleWaterChang"
      @expand="handleWaterExpand"
    ></water>

    <!-- 控制器 -->
    <controller
      :height="controlHeight"
      :isExpanded="controlExpand"
      :waterExpand="waterExpand"
      :pond-options="pondOptions"
      :data="controlData"
      @pond="handleControlChang"
      @refresh="getControlInfo"
      @expand="handleControlExpand"
    ></controller>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getPond, getEquipment, getHistory } from "@/api/screen/screen"
import water from "../modules/water.vue"
import controller from "../modules/controller.vue"
import { useTimeoutPoll } from "@vueuse/core"
import { useExpandManager } from "@/hooks/useExpandManager.js"

// 使用展开收缩管理器
const { waterExpand, controlExpand, waterHeight, controlHeight, initializeExpandStatus, handleWaterExpand, handleControlExpand } = useExpandManager()

// 获取塘口数据
const pondOptions = ref([])
const getPondOption = () => {
  getPond().then(res => {
    pondOptions.value = res.data
  })
}

// 获取水质设备数据
const waterDeviceData = ref([])
const waterQueryParams = ref({
  deviceType: "1",
  pondIds: null
})
const getWaterInfo = () => {
  return new Promise((resolve, reject) => {
    getEquipment(waterQueryParams.value).then(res => {
      const hasWaterData = res.data.length > 0
      const hasControlData = controlData.value.length > 0
      
      if (!hasWaterData) {
        waterDeviceData.value = []
        initializeExpandStatus(hasWaterData, hasControlData, 'water')
        resolve()
        return
      }
      waterDeviceData.value = res.data.map(item => {
        // 依次为 溶解氧、PH、水温、饱和度、盐度
        const { dissolvedOxygen, ph, temperature, saturability, salinity, ...rest } = item
        return {
          ...rest,
          data: [
            { name: "溶解氧 (mg/L)", title: "溶解氧", code: "dissolvedOxygen", value: dissolvedOxygen, isActive: true },
            { name: "水温 (℃)", title: "水温", code: "temperature", value: temperature, isActive: false },
            { name: "饱和度 (%)", title: "饱和度", code: "saturability", value: saturability, isActive: false },
            { name: "PH", title: "PH", code: "ph", value: ph, isActive: false },
            { name: "盐度 (g/L)", title: "盐度", code: "salinity", value: salinity, isActive: false }
          ]
        }
      })

      // 获取历史数据
      const promises = res.data.map(item => {
        const param = {
          deviceId: item.id
        }

        return getHistory(param).then(res => {
          return { deviceId: item.id, data: res.data }
        })
      })

      Promise.all(promises).then(results => {
        results.forEach(item => {
          const index = waterDeviceData.value.findIndex(i => i.id === item.deviceId)
          waterDeviceData.value[index].chartData = {
            dissolvedOxygen: {
              title: "溶解氧",
              suffix: "mg/L",
              data: item.data.map(data => {
                return {
                  name: data.day + " " + data.time,
                  value1: data.dissolvedOxygen
                }
              })
            },
            temperature: {
              title: "水温",
              suffix: "℃",
              data: item.data.map(data => {
                return {
                  name: data.day + " " + data.time,
                  value1: data.temperature
                }
              })
            },
            saturability: {
              title: "饱和度",
              suffix: "%",
              data: item.data.map(data => {
                return {
                  name: data.day + " " + data.time,
                  value1: data.saturability
                }
              })
            },
            ph: {
              title: "ph",
              suffix: "",
              data: item.data.map(data => {
                return {
                  name: data.day + " " + data.time,
                  value1: data.ph
                }
              })
            },
            salinity: {
              title: "盐度",
              suffix: "g/L",
              data: item.data.map(data => {
                return {
                  name: data.day + " " + data.time,
                  value1: data.salinity
                }
              })
            }
          }
        })
        
        // 初始化展开状态
        initializeExpandStatus(hasWaterData, hasControlData, 'water')
        resolve()
      })
    })
  })
}

const handleWaterChang = value => {
  if (value === undefined) {
    waterQueryParams.value.pondIds = null
  } else {
    waterQueryParams.value.pondIds = [value]
  }
  getWaterInfo()
}

// 获取控制器
const controlData = ref([])
const controlQueryParams = ref({
  deviceType: "2",
  pondIds: null
})
const getControlInfo = () => {
  return new Promise((resolve, reject) => {
    getEquipment(controlQueryParams.value).then(res => {
      const hasControlData = res.data.length > 0
      const hasWaterData = waterDeviceData.value.length > 0
      
      if (!hasControlData) {
        controlData.value = []
        // 初始化展开状态
        initializeExpandStatus(hasWaterData, hasControlData, 'control')
        resolve()
        return
      }
      controlData.value = res.data.map(item => {
        if (item.oxygenUsed && Array.isArray(item.switches)) {
          item.switches.push({
            switchName: "溶解氧",
            openStatus: item.dissolvedOxygen
          })
        }

        if (!Array.isArray(item.switches)) {
          item.switches = []
        }

        return item
      })
      
      // 初始化展开状态
      initializeExpandStatus(hasWaterData, hasControlData, 'control')
      resolve()
    })
  })
}

const handleControlChang = value => {
  if (value === undefined) {
    controlQueryParams.value.pondIds = null
  } else {
    controlQueryParams.value.pondIds = [value]
  }
  getControlInfo()
}

// 定期刷新数据的函数
const refreshData = async () => {
  try {
    await Promise.all([getWaterInfo(), getControlInfo()])
  } catch (error) {
    console.error('刷新数据失败:', error)
  }
}

// 挂载时执行
onMounted(() => {
  getPondOption()
  refreshData()
  useTimeoutPoll(refreshData, 5000)
})
</script>

<style lang="scss" scoped>
.screen-left {
  position: absolute;
  bottom: 30px;
  left: 30px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  row-gap: 2%;
  width: 71%;
  height: 86%;
}
</style>
