<!--
 * @Author: chris
 * @Date: 2025-09-05 09:29:59
 * @LastEditors: chris
 * @LastEditTime: 2026-01-21 14:41:54
-->
<script setup>
import LiveData from './components/LiveData.vue'
import WeatherChart from './components/WeatherChart.vue';
import { useSettings } from '@/hooks/useSettings';
// import { getFormattedWeatherData } from './mock';
import { getDeviceDataAnalysis } from '@/api/deviceData';
import { controlCamera, listDevice } from '@/api/device';
import { formatDate } from '@/utils';
import { weatherTypes, weatherDict } from './config';

const { hasTags } = useSettings()
const { proxy } = getCurrentInstance()

const cameraList = ref([])
const liveData = ref([])
const chartData = ref({ dates: [], values: []})
const weatherType = ref('Temperature')
const analysisData = ref({})
const selectedTimeRange = ref(7)
const chartLoading = ref(false)
const loading = ref(false)

// getChartData()
getDeviceAnalysisData()
getCameraList()

async function getCameraList() {
  try {
    const res = await listDevice({ type: '4', status: '0', pageNum: 1, pageSize: 10 })
    cameraList.value = res.rows || []
  } catch (error) {
    proxy.$modal.msgError('获取摄像头列表失败: ' + (error.message || '未知错误'))
    console.error('Failed to get camera list:', error)
  }
}

async function getDeviceAnalysisData() {
  loading.value = true
  const beginTime = formatDate(new Date().getTime() - 24 * 60 * 60 * 1000)
  const endTime = formatDate(new Date().getTime())
  try {
    const res = await getDeviceDataAnalysis({ type: 3 })
    analysisData.value = formatData(res.rows)
    liveData.value = createLiveData(analysisData.value)
    chartData.value =createChartData(analysisData.value, weatherType.value)
  } catch (error) {
    proxy.$modal.msgError('获取气象分析数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get device live data:', error)
  } finally {
    loading.value = false;
  }
  
}

// function getChartData() {
//   chartLoading.value = true
//   setTimeout(() => {
//     console.log(getFormattedWeatherData(weatherType.value, selectedTimeRange.value))
//     chartData.value = getFormattedWeatherData(weatherType.value, selectedTimeRange.value)
//     chartLoading.value = false
//   }, 300)
//   return chartData.value
// }

function handleSelectionChange(selection) {
  console.log(selection)
}

async function handleControlCamera({ deviceNo, action, code }) {
  try {
    await controlCamera({
      param: code,
      deviceSerial: deviceNo,
    })
  } catch (error) {
    proxy.$modal.msgError('控制摄像头失败: ' + (error.message || '未知错误'))
    console.error('Failed to control camera:', error)
  }
}

function handleSelectWeatherItem(item) {
  weatherType.value = item.type
  chartData.value = createChartData(analysisData.value, weatherType.value)
}

function handleTimeRangeChange(range) {
  selectedTimeRange.value = range
}

function createLiveData (data) {
  const liveData = []
  weatherTypes.forEach((type, index) => {
    const dictItem = weatherDict[type]
    liveData.push({
      id: index + 1,
      title: dictItem.name,
      type,
      value: data[type][0]?.value || '--',
      icon: dictItem.icon,
      color: dictItem.color,
      unit: dictItem.unit,
    })
  })
  return liveData;
}

function createChartData(data, type) {
  const dates = []
  const values = []
  const typeList = data[type] || []
  typeList.forEach(item => {
    dates.push(item.createTime)
    values.push(item.value)
  })
  return { dates, values }
}

function formatData(data) {
  const obj = {};
  const res = {};
  // data.sort((a,b) => soilTypes.indexOf(a.identifier) - soilTypes.indexOf(b.identifier))
  data.forEach(item => {
    const identifier = item.identifier;
    if (!identifier || identifier === 'null') return false;
    obj[identifier] ? obj[identifier].push(item) : (obj[identifier] = [item])
  })
  weatherTypes.forEach(type => {
    res[type] = obj[type] || []
  })
  return res;
}

</script>

<template>
  <div :class="['weather-monitor-page', 'page-height', { 'hasTagsView': hasTags }]">
    <el-row :gutter="20">
      <el-col class="real-time-data" :span="6">
        <live-data :items="liveData" :cameraList="cameraList" @select="handleSelectWeatherItem" @controlCamera="handleControlCamera"/>
      </el-col>
      <el-col class="history-data" :span="18">
        <weather-chart :weather-type="weatherType" :chart-data="chartData" :selected-time-range="selectedTimeRange" :loading="chartLoading" @time-range-change="handleTimeRangeChange" /> 
        <!-- <search-form v-model:params="queryParams" class="mb-12px" />
        <history-table :dataList="historyList" :columns="columnsConfig" @selection-change="handleSelectionChange" /> -->
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.weather-monitor-page {
  @apply p-20px;

  > .el-row {
    @apply h-full;
  }
  
  .export-btn {
    @apply float-right mr-10px mt-10px;
  }
}
</style>
