<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { Space } from 'ant-design-vue'
import { columns, searchFormSchema } from '../exa.data'
import EXAModal from './EXAModal.vue'
import CreateBatchModal from './CreateBatchModal.vue'

import HistoryModal from './HistoryModal.vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useModal } from '@/components/Modal'
import { IconEnum } from '@/enums/appEnum'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import type { RoleExportReqVO } from '@/api/system/role'
import { deletePoint, getEXAPage, getExaNow } from '@/api/alert/exa'

defineOptions({ name: 'EXAConfig' })

const { t } = useI18n()
const { createConfirm, createMessage } = useMessage()
const [registerModal, { openModal }] = useModal()
const [registerCreateBatchModal, { openModal: openCreateBatchModal }] = useModal()

const [registerHistoryModal, { openModal: openHistoryModal }] = useModal()
const [registerTable, { getForm, reload, getDataSource, updateTableDataRecord }] = useTable({
  title: '测点列表',
  api: getEXAPage,
  rowKey: 'serialNumber',
  immediate: false,
  columns,
  formConfig: {
    labelWidth: 150,
    schemas: searchFormSchema,
    showResetButton: false,
    actionColOptions: {
      span: 6,
    },
  },
  useSearchForm: true,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 80,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

async function getNow() {
  const params = getDataSource()
  params.forEach((item: any) => {
    // 对数组中的每个元素执行异步操作
    getExaNow(item.itemName).then((result) => {
      updateTableDataRecord(item.serialNumber, Object.assign(item, { value: result }))
    })
  })
}

let timerId
onMounted(() => {
  // 启动定时器，每5秒刷新一次
  timerId = setInterval(() => {
    getNow()
  }, 5000) // 每5秒执行一次[^1]
})

onUnmounted(() => {
  // 组件销毁时清除定时器
  clearInterval(timerId)
})
function handleCreate() {
  openModal(true, {})
}
function handleCreateBatch() {
  openCreateBatchModal(true, {})
}
const itemName = ref<string>()
const legendName = ref<string[]>()
function handleHistory(record: Recordable) {
  itemName.value = record.itemName
  legendName.value = []
  legendName.value.push(`${record.descriptor}-${record.itemName}`)
  openHistoryModal(true, { record })
}
async function handleExport() {
  createConfirm({
    title: t('common.exportTitle'),
    iconType: 'warning',
    content: t('common.exportMessage'),
    async onOk() {
      await exportRole(getForm().getFieldsValue() as RoleExportReqVO)
      createMessage.success(t('common.exportSuccessText'))
    },
  })
}

async function handleDelete(record: Recordable) {
  await deletePoint(record.itemName)
  createMessage.success(t('common.delSuccessText'))
  reload()
}
</script>

<template>
  <div>
    <BasicTable @register="registerTable">
      <template #form-advanceBefore>
        <Space style="margin-right: 10%;">
          <a-button v-auth="['system:role:create']" type="primary" :pre-icon="IconEnum.ADD" @click="handleCreate">
            {{ t('action.create') }}
          </a-button>
          <a-button v-auth="['system:role:create']" type="primary" :pre-icon="IconEnum.ADDS" @click="handleCreateBatch">
            {{ t('action.createBatch') }}
          </a-button>
        </Space>
      </template>

      <template #value="{ record }">
        <a class="click-status" @click="handleHistory(record)">
          {{ record.value }}
        </a>
        <!-- <SlidersOutlined class="click-status" /> -->
      </template>
      <template #toolbar>
        <!-- <a-button v-auth="['system:role:create']" type="primary" :pre-icon="IconEnum.ADD" @click="handleCreate">
          {{ t('action.create') }}
        </a-button>
        <a-button v-auth="['system:role:create']" type="primary" :pre-icon="IconEnum.ADDS" @click="handleCreateBatch">
          {{ t('action.createBatch') }}
        </a-button> -->
        <!-- <a-button v-auth="['system:role:create']" :pre-icon="IconEnum.EXPORT" @click="handleExport">
          {{ t('action.export') }}
        </a-button> -->
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[{
              icon: IconEnum.DELETE,
              danger: true,
              label: t('action.delete'),
              auth: 'alert:exa:delete',
              popConfirm: {
                title: t('common.delMessage'),
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <EXAModal @register="registerModal" @success="reload" />
    <CreateBatchModal @register="registerCreateBatchModal" @success="reload" />
    <HistoryModal :item-name="itemName" :legend-name="legendName" @register="registerHistoryModal" />
  </div>
</template>

<style lang="less" scoped>
:deep(.value) {
  font-weight:bold;
  color: #0B55A4
}
</style>
