<!--
 * @Author: chris
 * @Date: 2025-08-18 09:24:26
 * @LastEditors: DESKTOP-P4Q6IC1\CHRIS_PC 510148846@qq.com
 * @LastEditTime: 2026-03-25 09:57:48
-->
<script setup name="PestStatistics">
import { useSettings } from "@/hooks/useSettings";
import DeviceList from './components/DeviceList.vue';
import SearchForm from './components/SearchForm.vue';
import StatisticsChart from './components/StatisticsChart.vue';
import ChartAction from "./components/chartAction.vue";
import { devices } from './mockData'
import { listDevice } from '@/api/device'
import { listDeviceData } from '@/api/deviceData'
import { defaultParams } from './config'

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 deviceList = ref(devices);
const chartData = ref([]);
const formateData = ref({})
const options = ref([]);
const loading = ref(false);
const deviceLoading = ref(false);
const queryParams = ref({
  ...defaultParams
})

const checkList = ref([])

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;
    formateData.value = formatData(res.rows)
    chartData.value = createChartData(formateData.value);
    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) {
  // queryParams.value.deviceId = items.join(',')
  // getList()
}

function handlePestChange(names) {
  console.log('handlePestChange', names)
  const filterRes = {}
  names.forEach(name => {
    filterRes[name] = formateData.value[name] || []
  })
  chartData.value = createChartData(filterRes)
}


async function exportAnalysis() {
  const fileName = await proxy.download_2('/business/device-data/insect/analysis/export', queryParams.value, `分析导出_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}

async function exportTrend() {
  const fileName = await proxy.download_2('/business/device-data/insect/trend/export', queryParams.value, `统计导出_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}

function resetQuery() {
  console.log('重置查询')
  queryParams.value = {
    ...defaultParams
  }
  getList()
}

function formatData (data) {
  const res = {}
  data.forEach(item => {
    res[item.name] ? res[item.name].push(item) : res[item.name] = [item]
  })
  return res
}

function createChartData(data) {
  const obj = {}
  const names = Object.keys(data)
  names.forEach(key => {
    obj[key] = data[key].reduce((pre, cur) => pre + (cur.value || 0), 0)
  })
  // formateData.value = obj
  return {
    names,
    data: Object.values(obj)
  }
}

function createPestOption (names) {
  return names.map((name, index) => ({
    id: index + 1,
    name
  }))
}
</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" @selected="handleSelect"></device-list>
      </el-col>
      <el-col :span="20">
        <search-form v-model:params="queryParams" @reset="resetQuery" @query="getList" @exportAnalysis="exportAnalysis" @exportTrend="exportTrend" />
        <chart-action :options="options" @pestChange="handlePestChange" class="action" />
        <statistics-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>
