<!--
 * @Author: chris
 * @Date: 2025-08-18 09:24:26
 * @LastEditors: chris
 * @LastEditTime: 2025-10-09 10:53:17
-->
<script setup name="PestStatistics">
import { useSettings } from "@/hooks/useSettings";
import DeviceList from './components/DeviceList.vue';
import SearchForm from './components/SearchForm.vue';
import TrendChart from './components/TrendChart.vue';
import ChartAction from "./components/chartAction.vue";
import { devices } from './mockData'
import { listDevice } from '@/api/device'
import { listDeviceData } from '@/api/deviceData'

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

const nowDate = new Date().toLocaleDateString().replace(/\//g, '-')
const nextDate = new Date(+new Date(nowDate) + 24 * 60 * 60 * 1000).toLocaleDateString().replace(/\//g, '-')

const loading = ref(false);
const deviceLoading = ref(false);
const chartAllData = ref({});
const chartData = ref({});
const deviceList = ref(devices);
const options = ref([])
const checkList = ref([]);
const queryParams = ref({
  pageNum: 1,
  deviceType: 1,
  deviceId: null,
  beginTime: `${nowDate} 00:00:00`,
  endTime: `${nextDate} 23:59:59`
});

const deviceIds = computed({
  get: () => {
    return checkList.value || []
  },
  set: (value) => {
    checkList.value = value
    queryParams.value.deviceId = value.join(',')
    getList()
  }
})

getDeviceList();

async function getList () {
  loading.value = true;
  try {
    const res = await listDeviceData(queryParams.value);
    // imageList.value = res.rows;
    chartAllData.value = chartData.value = createChartData(res.rows);
    options.value = createPestOption(chartData.value.names)
  } catch (error) {
    proxy.$modal.msgError('获取虫情设备实时数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get device live data:', error)
  } finally {
    loading.value = false;
  }
}

async function getDeviceList () {
  const params = {
    pageNum: 1,
    pageSize: 50,
    type: 1
  }
  deviceLoading.value = true;
  try {
    const res = await listDevice(params);
    deviceList.value = res.rows;
    deviceIds.value = res.rows.map(item => item.id)
  } catch (error) {
    proxy.$modal.msgError('获取虫情设备数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get pest list:', error)
  } finally {
    deviceLoading.value = false;
  }
}

function handleSelect(items) {
  console.log(items);
}

function exportView() {
  console.log('导出视图')
}

function resetQuery() {
  console.log('重置查询')
}

function createChartData(data) {
  const res = {}
  data.forEach(item => {
    const date = item.createTime.split(' ')[0]
    const name = item.name
    if (!res[date]) {
      res[date] = {}
      res[date][name] = item.value
    } else {
      res[date][name] = res[date][name] ? (res[date][name] + item.value) : item.value
    }
  })
  
  let maxItemKeys = []
  Object.keys(res).forEach(dateKey => {
    const item = res[dateKey]
    const pestKeys = Object.keys(item)
    pestKeys.length > maxItemKeys.length ? (maxItemKeys = pestKeys) : null
  })

  const values = []
  maxItemKeys.forEach(pestKey => {
    values.push({
      name: pestKey,
      data: Object.keys(res).map(key => res[key][pestKey] || 0)
    })
  })

  return {
    names: maxItemKeys,
    dates: Object.keys(res),
    values
  }
}

function createPestOption (names) {
  return names.map((name, index) => ({
    id: index + 1,
    name
  }))
}

function handlePestChange(names) {
  const data = JSON.parse(JSON.stringify(chartAllData.value))
  
  Object.keys(data).forEach(key => {
    const item = data[key]
    key =='names' && (data[key] = item.filter(name => names.includes(name)))
    key =='values' && (data[key] = item.filter(item => names.includes(item.name)))
  })

  chartData.value = data
}
</script>

<template>
  <div :class="['pest-statistics-page', 'page-height', { 'hasTagsView': hasTags }]">
    <el-row :gutter="40" class="h-100%">
      <el-col :span="4">
        <device-list v-model="deviceIds" :devices="deviceList" @select="handleSelect"></device-list>
      </el-col>
      <el-col :span="20">
        <search-form v-model:params="queryParams" @reset="resetQuery" @query="getList" @export="exportView" />
        <chart-action :options="options" @pestChange="handlePestChange" class="action" />
        <trend-chart :chartData="chartData" class="chart"/>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.pest-statistics-page {
  @apply p-20px
}
.action {
  @apply mt-20px;
}
.chart {
  @apply h-88% w-100% mt-10px;
}
</style>
