<template>
  <div>
    <ContentWrap title="温湿度监测">
      <!-- 搜索栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="80px">
        <el-form-item label="点位" prop="pointName">
          <el-input v-model="queryParams.pointName" class="!w-240px" clearable placeholder="请输入点位" @keyup.enter="getList" />
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="defaultShortcuts"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="!w-420px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <ContentWrap title="趋势折线图">
      <el-row :gutter="16">
        <el-col :span="12">
          <div class="mb-8px text-14px font-700">空气温度</div>
          <Echart :height="260" :options="optAirTemp" />
        </el-col>
        <el-col :span="12">
          <div class="mb-8px text-14px font-700">空气湿度</div>
          <Echart :height="260" :options="optAirHumidity" />
        </el-col>
        <el-col :span="12" class="mt-12px">
          <div class="mb-8px text-14px font-700">土壤温度</div>
          <Echart :height="260" :options="optSoilTemp" />
        </el-col>
        <el-col :span="12" class="mt-12px">
          <div class="mb-8px text-14px font-700">土壤湿度</div>
          <Echart :height="260" :options="optSoilHumidity" />
        </el-col>
      </el-row>
    </ContentWrap>

    <ContentWrap title="数据列表">
      <el-table :data="list" v-loading="loading" border stripe>
        <el-table-column prop="pointName" label="点位" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column prop="airTemp" label="空气温度(°C)" min-width="120" />
        <el-table-column prop="airHumidity" label="空气湿度(%)" min-width="120" />
        <el-table-column prop="soilTemp" label="土壤温度(°C)" min-width="120" />
        <el-table-column prop="soilHumidity" label="土壤湿度(%)" min-width="120" />
        <el-table-column label="时间" min-width="170">
          <template #default="scope">
            {{ formatDate(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160" :show-overflow-tooltip="true" />
      </el-table>
      <div class="mt-12px flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup>
import { ContentWrap } from '@/components/ContentWrap'
import { Echart } from '@/components/Echart'
import { defaultShortcuts, formatDate } from '@/utils/formatTime'
import * as HumidityApi from '@/api/mes/humidity'
import dayjs from 'dayjs'

defineOptions({ name: 'MesHumidityIndex' })

// 查询参数
const queryParams = reactive<any>({
  pointName: undefined,
  timeRange: getDefaultTimeRange() as any,
  pageNo: 1,
  pageSize: 10
})

// 列表数据
const loading = ref<boolean>(false)
const list = ref<HumidityApi.HumidityRecordVO[]>([])
const total = ref<number>(0)

// 定时器
const timer = ref<number | null>(null)

// 折线图配置（四张图：按点位分组，多条线）
import type { EChartsOption, SeriesOption } from 'echarts'
const baseOption = () => ({
  grid: { left: 20, right: 20, bottom: 20, top: 60, containLabel: true },
  tooltip: { trigger: 'axis', axisPointer: { type: 'cross' }, padding: [5, 10] },
  legend: { top: 20, data: [] as string[] },
  xAxis: { type: 'category', boundaryGap: false, data: [] as string[] },
  yAxis: { type: 'value' },
  series: [] as SeriesOption[],
  toolbox: { feature: { dataZoom: { yAxisIndex: false }, brush: { type: ['lineX', 'clear'] }, saveAsImage: { show: true } } }
}) as any
const optAirTemp = reactive(baseOption()) as unknown as EChartsOption
const optAirHumidity = reactive(baseOption()) as unknown as EChartsOption
const optSoilTemp = reactive(baseOption()) as unknown as EChartsOption
const optSoilHumidity = reactive(baseOption()) as unknown as EChartsOption

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const params: any = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      pointName: queryParams.pointName
    }
    if (queryParams.timeRange && queryParams.timeRange.length === 2) {
      params.beginTime = queryParams.timeRange[0]
      params.endTime = queryParams.timeRange[1]
    }
    const data = await HumidityApi.getHumidityPage(params)
    list.value = data.list || []
    total.value = data.total || 0

    // 同步刷新趋势
    await getTrend()
  } finally {
    loading.value = false
  }
}

// 获取折线图数据（按点位分组）
const getTrend = async () => {
  const params: any = {
    pointName: queryParams.pointName
  }
  if (queryParams.timeRange && queryParams.timeRange.length === 2) {
    params.beginTime = queryParams.timeRange[0]
    params.endTime = queryParams.timeRange[1]
  }
  const trend = await HumidityApi.getHumidityTrend(params)
  const times: string[] = trend?.times || []
  const points: any[] = trend?.points || []

    // x 轴同步
  ;[optAirTemp, optAirHumidity, optSoilTemp, optSoilHumidity].forEach((opt: any) => {
    if (opt.xAxis) opt.xAxis.data = times
  })
  // 图例（点位名）
  const legend = points.map((p) => p.pointName || '未命名点位')
  ;[optAirTemp, optAirHumidity, optSoilTemp, optSoilHumidity].forEach((opt: any) => {
    opt.legend.data = legend
  })
  // series 按点位生成
  const toNums = (arr: any[]) => (arr || []).map((v) => (v === null || v === undefined || v === '' ? null : Number(v)))
  const common = { smooth: true, connectNulls: true, showSymbol: false } as any
  const sAirTemp: SeriesOption[] = points.map((p) => ({ name: p.pointName || '未命名点位', type: 'line', ...common, data: toNums(p.airTemp) }))
  const sAirHumidity: SeriesOption[] = points.map((p) => ({ name: p.pointName || '未命名点位', type: 'line', ...common, data: toNums(p.airHumidity) }))
  const sSoilTemp: SeriesOption[] = points.map((p) => ({ name: p.pointName || '未命名点位', type: 'line', ...common, data: toNums(p.soilTemp) }))
  const sSoilHumidity: SeriesOption[] = points.map((p) => ({ name: p.pointName || '未命名点位', type: 'line', ...common, data: toNums(p.soilHumidity) }))
  ;(optAirTemp as any).series = sAirTemp
  ;(optAirHumidity as any).series = sAirHumidity
  ;(optSoilTemp as any).series = sSoilTemp
  ;(optSoilHumidity as any).series = sSoilHumidity
}

// 重置
const queryFormRef = ref()
const resetQuery = async () => {
  queryParams.pointName = undefined
  queryParams.timeRange = getDefaultTimeRange() as any
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  await getList()
}

// 默认时间范围：最近 24 小时
function getDefaultTimeRange(): [string, string] {
  return [
    dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
}

// 定时获取数据
const startFetchTimer = () => {
  // 清除可能存在的旧定时器
  if (timer.value) {
    clearInterval(timer.value)
  }
  
  // 立即执行一次
  fetchLatestData()
  
  // 设置新定时器，每30分钟执行一次
  timer.value = setInterval(() => {
    fetchLatestData()
  }, 30 * 60 * 1000) // 30分钟 = 30 * 60 * 1000毫秒
}

// 获取最新数据
const fetchLatestData = async () => {
  try {
    await HumidityApi.fetchAndCreateHumidity()
    console.log('温湿度数据已自动更新')
    // 刷新列表和趋势图
    await getList()
  } catch (error) {
    console.error('自动获取温湿度数据失败:', error)
  }
}

onMounted(async () => {
  await getList()
  startFetchTimer()
})

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>

<style scoped>
</style>
