<!--
 * @Author: chris
 * @Date: 2025-09-05 09:29:59
 * @LastEditors: DESKTOP-P4Q6IC1\CHRIS_PC 510148846@qq.com
 * @LastEditTime: 2026-03-25 09:54:00
-->
<script setup>
import LiveData from './components/LiveData.vue'
import SoilChart from './components/SoilChart.vue';
import { useSettings } from '@/hooks/useSettings';
import { getFormattedSoilData } from './mock';
import { getDeviceDataAnalysis } from '@/api/deviceData';
import { soilTypes, soilDict } from './config';

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

const liveData = ref([])
const chartData = ref({ dates: [], values: []})
const soilType = ref('SoilTemperature')
const selectedTimeRange = ref(7)
const chartLoading = ref(false) 
const analysisData = ref(null)

// getChartData()

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

getAnalysisData()

async function getAnalysisData () {
  chartLoading.value = true
  try {
    const res = await getDeviceDataAnalysis({ type: 2 })
    chartLoading.value = false
    analysisData.value = formatData(res.rows)
    liveData.value = createLiveData(analysisData.value)
    chartData.value = createChartData(analysisData.value, soilType.value)
  } catch (error) {
    proxy.$modal.msgError('获取分析数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get analysis data:', error)
  } finally {
    chartLoading.value = false
  }
}

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

}

function handleSelectSoilItem(item) {
  soilType.value = item.type
  chartData.value = createChartData(analysisData.value, soilType.value)
}

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

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])
  })
  soilTypes.forEach(type => {
    res[type] = obj[type] || []
  })
  return res;
}

function createLiveData (data) {
  const liveData = []
  Object.keys(data).forEach((type, index) => {
    const dictItem = soilDict[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 }
}

async function exportAnalysis() {
  const fileName = await proxy.download_2('/business/device-data/soil/analysis/export',{ type: 2 } , `分析导出_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}
</script>

<template>
  <div :class="['soil-monitor-page', 'page-height', { 'hasTagsView': hasTags }]">
    <el-row :gutter="20">
      <el-col class="real-time-data" :span="6">
        <live-data :items="liveData" @select="handleSelectSoilItem"/>
      </el-col>
      <el-col class="history-data" :span="18">
        <el-button type="warning" @click="exportAnalysis" class="export-btn">导出</el-button>
        <soil-chart :soil-type="soilType" :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>
.soil-monitor-page {
  @apply p-20px;

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