<template>
  <ContentWrap>
    <el-form
      class="-mb-15px real-time-monitoring-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('DataCollection.RealTimeMonitoring.searchLineCodeLabel')" prop="lineNode">
        <el-input
          v-model="queryParams.lineNode"
          :placeholder="t('DataCollection.RealTimeMonitoring.searchLineCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.RealTimeMonitoring.searchLineNameLabel')" prop="lineName">
        <el-input
          v-model="queryParams.lineName"
          :placeholder="t('DataCollection.RealTimeMonitoring.searchLineNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.RealTimeMonitoring.searchDeviceCodeLabel')" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          :placeholder="t('DataCollection.RealTimeMonitoring.searchDeviceCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.RealTimeMonitoring.searchDeviceNameLabel')" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          :placeholder="t('DataCollection.RealTimeMonitoring.searchDeviceNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('DataCollection.RealTimeMonitoring.searchButtonText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('DataCollection.RealTimeMonitoring.resetButtonText') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('DataCollection.RealTimeMonitoring.exportButtonText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" reserve-selection />
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableDeviceCodeColumn')"
        align="left"
        prop="deviceCode"
        min-width="140px"
      />
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableDeviceNameColumn')"
        align="left"
        prop="deviceName"
        min-width="160px"
      />
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableLineCodeColumn')"
        align="left"
        prop="lineNode"
        min-width="140px"
      />
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableLineNameColumn')"
        align="left"
        prop="lineName"
        min-width="160px"
      />
      <!-- <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableStatusColumn')"
        align="center"
        prop="status"
        width="120px"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IOT_GATEWAY_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableCollectionTimeColumn')"
        align="center"
        prop="collectionTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        :label="t('DataCollection.RealTimeMonitoring.tableOperateColumn')"
        align="center"
        fixed="right"
        width="150px"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleSingleMonitor(scope.row)">
            {{ t('DataCollection.RealTimeMonitoring.tableActionSingleMonitorLabel') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <SingleDeviceMonitorDialog
    v-model="monitorDialogVisible"
    :device-id="monitorDeviceId"
    :device-name="monitorDeviceName"
    :collection-time="monitorCollectionTime"
  />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceApi, LineDeviceVO } from '@/api/iot/device'
import SingleDeviceMonitorDialog from './SingleDeviceMonitorDialog.vue'

defineOptions({ name: 'RealTimeMonitoring' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<LineDeviceVO[]>([])
const total = ref(0)
const exportLoading = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  lineNode: undefined,
  lineName: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  status: undefined,
  collectionTime: undefined
})
const queryFormRef = ref()

const selectedIds = ref<(string | number)[]>([])
const handleSelectionChange = (rows: LineDeviceVO[]) => {
  selectedIds.value =
    rows?.map((row) => ((row as any)?.id ?? (row as any)?.deviceId) as string | number).filter(
      (id) => id !== undefined && id !== null && id !== ''
    ) ?? []
}

const monitorDialogVisible = ref(false)
const monitorDeviceId = ref<string | number>()
const monitorDeviceName = ref<string>()
const monitorCollectionTime = ref<string | number>()

const buildQueryParams = (): Parameters<typeof DeviceApi.getLineDevicePage>[0] => {
  const params: Parameters<typeof DeviceApi.getLineDevicePage>[0] = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize
  }
  const keys = ['id', 'lineNode', 'lineName', 'deviceCode', 'deviceName', 'status', 'collectionTime'] as const
  for (const key of keys) {
    const value = queryParams[key]
    if (value === undefined || value === null || value === '') {
      continue
    }
    (params as any)[key] = value
  }
  return params
}

const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceApi.getLineDevicePage(buildQueryParams())
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleSingleMonitor = (row: LineDeviceVO) => {
  const deviceId = (row as any)?.deviceId ?? row?.id
  if (deviceId === undefined || deviceId === null || deviceId === '') {
    message.error(t('DataCollection.RealTimeMonitoring.messageDeviceInfoIncomplete'))
    return
  }
  monitorDeviceId.value = deviceId
  monitorDeviceName.value = row?.deviceName ?? ''
  monitorCollectionTime.value = row?.collectionTime
  monitorDialogVisible.value = true
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: any = {
      ...buildQueryParams(),
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await DeviceApi.exportLineDevice(params)
    download.excel(data, t('DataCollection.RealTimeMonitoring.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.real-time-monitoring-form :deep(.el-form-item__label) {
  min-width: 100px;
}
</style>
