<!--
 * @Author: chris
 * @Date: 2025-10-17 11:52:06
 * @LastEditors: chris
 * @LastEditTime: 2025-11-17 10:50:12
-->
<script setup>
import { useToast } from 'wot-design-uni'

import { getDeviceDataAnalysis } from '@/api/deviceData/index'

const echarts = require('../../uni_modules/lime-echart_1.0.5/static/echarts.min2.js')

import LineChart from './components/lineChart.vue'
import PieChart from './components/pieChart.vue'

definePage({
  style: {
    navigationBarTitleText: '虫情监测',
  },
})

const toast = useToast()
const { proxy } = getCurrentInstance()
const query = uni.createSelectorQuery().in(proxy)

const orchardId = ref(0)
const daysRange = getDateRange(7)
const lineChartData = ref({})
const pieChartData = ref({})

const chartSize = ref({
  lineChart: {
    width: 0,
    height: 0,
  },
  pieChart: {
    width: 0,
    height: 0,
  },
})

onMounted(async () => {
  // await getChartCanvasSize('lineChart')
  // await getChartCanvasSize('pieChart')
  const res = await getPestAnalysisData()
  const { lineRes, pieRes } = formatData(res.rows)
  lineChartData.value = createChartData(lineRes, 'line')
  pieChartData.value = createChartData(pieRes, 'pie')
})

async function getPestAnalysisData() {
  try {
    return await getDeviceDataAnalysis({
      beginTime: daysRange[0],
      endTime: daysRange[1],
      type: 1,
      deptId: orchardId.value,
    })
  }
  catch (error) {
    toast.error(`获取虫情数据失败: ${error.message || '未知错误'}`)
    console.error('Failed to get soil analysis data:', error)
    return error
  }
}

function formatData(data = []) {
  const lineRes = {}
  const pieRes = {}
  data.forEach((item) => {
    const date = item.createTime.split(' ')[0].replace(/-/g, '/')
    lineRes[item.name] ? lineRes[item.name].push(item) : (lineRes[item.name] = [item])
    pieRes[date] ? pieRes[date].push(item) : (pieRes[date] = [item])
  })
  return {
    lineRes,
    pieRes,
  }
}

function createChartData(data, type) {
  const keys = Object.keys(data)
  const values = []
  keys.forEach((key) => {
    values.push(data[key].reduce((pre, cur) => cur + (pre.value || 0), 0))
  })
  return type === 'line' ? { dates: keys, values } : { names: keys, values }
}

function getDateRange(num) {
  const nowDate = new Date().toLocaleString().replace(/\//g, '-')
  const preDate = new Date(+new Date(nowDate) - num * 24 * 60 * 60 * 1000).toLocaleString().replace(/\//g, '-')
  return [preDate, nowDate]
}

async function getCanvasSize(id) {
  return new Promise((resolve, reject) => {
    query.select(`#${id}`).boundingClientRect((info) => {
      resolve(info)
    }).exec()
  })
}

async function getChartCanvasSize(id) {
  const { width = 0, height = 0 } = await getCanvasSize(id)
  chartSize.value[id].width = width
  chartSize.value[id].height = height
}
</script>

<template>
  <view class="pest-monitor-page">
    <wd-card class="pest-info-card">
      <view class="pest-total-title">
        <view class="title-text">
          虫害总数(近7天)
        </view>
        <view class="update-time">
          更新时间: {{ '2023-10-17 11:52:06' }}
        </view>
      </view>
      <view class="pest-total-count">
        {{ 12345 }}
      </view>
    </wd-card>

    <!-- 折线图区域 -->
    <wd-card class="chart-card">
      <!-- <view class="chart-title">
        近7天虫害趋势
      </view> -->
      <!-- <l-echart id="lineChart" ref="lineChartRef" class="chart" /> -->
      <line-chart id="lineChart" :echarts="echarts" :chart-data="lineChartData" />
    </wd-card>

    <!-- 饼图区域 -->
    <wd-card class="chart-card">
      <!-- <view class="chart-title">
        虫害类型分布
      </view> -->
      <pie-chart id="pieChart" :echarts="echarts" :chart-data="pieChartData" />
    </wd-card>
  </view>
</template>

<style lang="scss" scoped>
$bg-color: #f5f7fa;

.pest-monitor-page {
  @apply py-15px min-h-[100vh];
  background-color: $bg-color;

  > .wd-card {
    @apply p-15px;
  }
}

.pest-info-card {
  .pest-total-title {
    @apply flex flex-col items-center justify-between mb-20px;

    .title-text {
      @apply text-20px font-bold tracking-[4px] mb-2px;
      color: $-color-theme;
    }
    .update-time {
      @apply text-12px;
      color: $-color-secondary;
    }
  }

  .pest-total-count {
    @apply text-center font-size-20px font-600;
    color: $-color-warning;
  }
}

.chart-card {
  .chart-title {
    @apply mb-20px font-bold;
  }
}

.chart {
  @apply w-[100%] h-[300px];
}
</style>
