<template>
  <div :class="['pest-monitor-page', 'page-height', { 'hasTagsView': hasTags }]">
    <el-row :gutter="12">
      <!-- 左侧部分 -->
      <el-col :span="4" class="page-left">
        <el-card class="device-three-card">
          <template #header>
            <span class="model-title">设备列表</span>
          </template>
          <device-flat-list :list="deviceList" @change="handleChangeDevice" />  
        </el-card>
      </el-col>
      <!-- 右侧部分 -->
      <el-col :span="20" class="page-right">
        <div class="page-title text-center" v-if="false">
          检测设备名称
        </div>
        <el-card class="run-model-container" v-if="false">
          <template #header>
            <span class="model-title">运行模式</span>
            <el-segmented v-model="modelValue" :options="modelOptions" size="default" @change="handleModelChange">
              <template #default="{ item }">
                <p>{{ item.label }}</p>
              </template>
            </el-segmented>
          </template>
          <div class="device-content">
            <div class="device-img">
              <img :src="pestImg" alt="">
            </div>
            <div class="device-args">
              <div class="args-item">
                <span class="args-item__name">参数名称</span>
                <span class="args-item__value">参数值</span>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="history-container">
          <template #header>
            <el-row :gutter="10" justify="space-between">
              <el-col :span="14" class="model-header__left">
                <span class="model-title">历史数据</span>
                <el-segmented v-model="historyValue" :options="historyOptions" size="default" v-if="false">
                  <template #default="{ item }">
                    <p>{{ item.label }}</p>
                  </template>
                </el-segmented>
              </el-col>
              <el-col :span="10" class="model-header__right text-right">
                <span>查询范围</span>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
                <el-button type="primary" @click="getDeviceDataList">查询</el-button>
                <el-button type="warning" @click="exportHistory">导出</el-button>
              </el-col>
            </el-row>
          </template>
          <div class="history-content">
            <el-table :data="operationData" style="width: 100%" v-if="historyValue === '0'">
              <el-table-column prop="deviceAddr" label="地址码" />
              <el-table-column prop="value" label="操作内容" />
              <el-table-column prop="userName" label="操作用户" />
              <el-table-column prop="createTime" label="操作时间" />
            </el-table>
            <el-table :data="operationData" v-loading="loading" style="width: 100%" v-if="historyValue === '1'">
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="value" label="数量" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="createTime" label="时间" />
            </el-table>
            <!-- 分页 -->
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getDeviceDataList" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import DeviceFlatList from '@/components/deviceFlatList';
import Pagination from '@/components/Pagination'
import useSettingsStore from '@/store/modules/settings';
import pestImg from '@/assets/images/devices/pest.png';
import { listDevice } from '@/api/device';
import { listDeviceData } from '@/api/deviceData';

const settingsStore = useSettingsStore();

const modelOptions = readonly([
  { label: '自动', value: '0' },
  { label: '手动', value: '1' },
])

const historyOptions = readonly([
  { label: '操作记录', value: '0' },
  { label: '历史数据', value: '1' },
])

const { proxy } = getCurrentInstance()

const total = ref(0)
const modelValue = ref('0')
const historyValue = ref('1')
const dateRange = ref(null)
const operationData = ref([])
const loading = ref(false)
const liveLoading = ref(false)
const deviceList = ref([])
const liveData = ref({})
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  type: 1,
  deviceId: null,
  beginTime: null,
  endTime: null
})

const hasTags = computed(() => settingsStore.tagsView);

watch(() => dateRange.value, () => {
  if (!dateRange.value.length) return;
  queryParams.value.beginTime = dateRange.value[0]
  queryParams.value.endTime = dateRange.value[1]
})

getDeviceList();
getDeviceDataList();

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

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

function handleChangeDevice(device) {
  queryParams.value.deviceId = device.id
  getDeviceDataList()
}

function handleModelChange(val) {
  console.log(val)
}

async function exportHistory() {
  const fileName = await proxy.download_2('/business/device-data/export', queryParams.value, `虫情历史数据_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}
</script>

<style lang="scss" scoped>
.pest-monitor-page {
  padding: 10px;
  > .el-row,
  .device-three-card {
    height: 100%;
  }
}

.page-right {
  @apply flex flex-col;
}

.run-model-container {
  @apply h-450px;

  :deep(.el-card__body) {
    height: calc(100% - 54px);
  }

  .device-content {
    @apply flex items-center justify-around h-100%;
  }

  .device-img,
  img {
    @apply h-100%;
  }

  .device-args {
    @apply flex;

    .args-item {
      @apply flex flex-col justify-between items-center;
      border-radius: 5px;
      width: 150px;
      border: 1px solid var(--el-color-primary);
      overflow: hidden;

      > span {
        @apply w-100% text-center;
      }
    }

    .args-item__name {
      background-color: var(--el-color-primary);
      color: #fff;
      @apply h-36px line-height-36px;
    }

    .args-item__value {
      @apply h-50px line-height-50px;
      background-color: var(--el-color-info-light-9);
    }
  }
}

.history-container {
  @apply flex-1;
}

.page-title {
  @apply font-size-24px fw-bold mt-10px mb-20px;
}

.model-title {
  @apply fw-bold mr-15px;
}

.model-header__left,
.model-header__right {
  @apply flex items-center;
}

.model-header__right {
  > :nth-child(2) {
    margin: 0 10px;
  }
}
</style>
