<template>
  <ContentWrap>
    <el-form
      class="-mb-15px history-data-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('DataCollection.HistoryData.searchDeviceCodeLabel')" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          :placeholder="t('DataCollection.HistoryData.searchDeviceCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.HistoryData.searchDeviceNameLabel')" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          :placeholder="t('DataCollection.HistoryData.searchDeviceNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
       <el-form-item :label="t('DataCollection.HistoryData.searchLineCodeLabel')" prop="lineNode">
        <el-input
          v-model="queryParams.lineNode"
          :placeholder="t('DataCollection.HistoryData.searchLineCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('DataCollection.HistoryData.searchLineNameLabel')" prop="lineName">
        <el-input
          v-model="queryParams.lineName"
          :placeholder="t('DataCollection.HistoryData.searchLineNamePlaceholder')"
          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.HistoryData.searchButtonText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('DataCollection.HistoryData.resetButtonText') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('DataCollection.HistoryData.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.HistoryData.tableDeviceCodeColumn')"
        align="left"
        prop="deviceCode"
        min-width="140px"
        sortable
      />
      <el-table-column
        :label="t('DataCollection.HistoryData.tableDeviceNameColumn')"
        align="left"
        prop="deviceName"
        min-width="160px"
        sortable
      />
       <el-table-column
        :label="t('DataCollection.HistoryData.tableLineCodeColumn')"
        align="left"
        prop="lineNode"
        min-width="140px"
      />
      <el-table-column
        :label="t('DataCollection.HistoryData.tableLineNameColumn')"
        align="left"
        prop="lineName"
        min-width="160px"
       sortable />
      <el-table-column
        :label="t('DataCollection.HistoryData.tableCollectionTimeColumn')"
        align="center"
        prop="collectionTime"
        :formatter="dateFormatter"
        width="180px"
        sortable
      />
      <el-table-column
        :label="t('DataCollection.HistoryData.tableOperateColumn')"
        align="center"
        fixed="right"
        width="300px"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleSingleView(scope.row)">
            {{ t('DataCollection.HistoryData.tableActionHistoryLabel') }}
          </el-button>
          <el-button link type="primary" @click="handleSingleAnalyseView(scope.row)">
            {{ t('DataCollection.HistoryData.tableActionHistoryAnalyseLabel') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <HistorySingleDeviceDialog
    v-model="singleDialogVisible"
    :device-id="singleDeviceId"
    :device-name="singleDeviceName"
  />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceApi, LineDeviceVO, LineDevicePageParams } from '@/api/iot/device'
import HistorySingleDeviceDialog from './HistorySingleDeviceDialog.vue'
import {useRouter} from "vue-router";
// 路由
const router = useRouter()
defineOptions({ name: 'HistoryData' })
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 as string | number | undefined,
  lineNode: undefined as string | undefined,
  lineName: undefined as string | undefined,
  deviceCode: undefined as string | undefined,
  deviceName: undefined as string | undefined,
  status: undefined as string | number | 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 singleDialogVisible = ref(false)
const singleDeviceId = ref<string | number>()
const singleDeviceName = ref<string>('')

const buildQueryParams = (): LineDevicePageParams => {
  const params: LineDevicePageParams = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize
  }

  if (queryParams.lineNode) {
    params.lineNode = queryParams.lineNode
  }
  if (queryParams.lineName) {
    params.lineName = queryParams.lineName
  }
  if (queryParams.deviceCode) {
    params.deviceCode = queryParams.deviceCode
  }
  if (queryParams.deviceName) {
    params.deviceName = queryParams.deviceName
  }

  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 handleSingleView = (row: LineDeviceVO) => {
  const deviceId = (row as any)?.deviceId ?? row?.id
  if (deviceId === undefined || deviceId === null || deviceId === '') {
    return
  }
  singleDeviceId.value = deviceId
  singleDeviceName.value = row.deviceName || ''
  singleDialogVisible.value = true
}

const handleSingleAnalyseView = (row: LineDeviceVO) => {
  const deviceId = (row as any)?.deviceId ?? row?.id
  if (deviceId === undefined || deviceId === null || deviceId === '') {
    return
  }
  singleDeviceId.value = deviceId
  singleDeviceName.value = row.deviceName || ''
  router.push({
    path: '/iot/historySingleAnalyse',
    query: {
      id: deviceId,
      name: singleDeviceName.value,
      deviceCode: row.deviceCode,
      lineNode: row.lineNode,
      lineName: row.lineName,
      collectionTime: row.collectionTime
    }
  });
}


onMounted(() => {
  getList()
})

const activatedOnce = ref(false)
onActivated(() => {
  if (!activatedOnce.value) {
    activatedOnce.value = true
    return
  }
  getList()
})

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.HistoryData.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}
</script>

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