<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" v-auth="'deviceAlarm:export'" @click="handleExport">
          {{ t('导出') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'level'">
          <a-tag :color="getLevel(record.level)">
            {{ levelData.filter((x) => x.id === record.level)[0]?.name }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex == 'state'">
          <span :style="`color:${record.state === 1 ? '#67c23a' : '#F56C6C'}`">
            {{ record.state === 1 ? '已处理' : '待处理' }}
          </span>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                label: '查看',
                auth: 'deviceAlarm:view',
                onClick: handleView.bind(null, record),
              },
              {
                label: '处理',
                auth: 'deviceAlarm:dispose',
                onClick: handleDispose.bind(null, record),
              },
              {
                label: '删除',
                auth: 'deviceAlarm:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AlarmModal @register="registerModal" @success="reload" />
    <AlarmInfomation @register="registerCheckModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, onMounted, ref } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getDeviceAlarmPageList, deleteDeviceAlarm, exportInfo } from '/@/api/erp/device/alarm';
  import { getDicDetailList } from '/@/api/system/dic';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { downloadByData } from '/@/utils/file/download';
  import AlarmModal from './components/AlarmModal.vue';
  import AlarmInfomation from './components/AlarmInfomation.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '设备编号',
      dataIndex: 'number',
      width: 100,
      resizable: true,
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      width: 100,
      resizable: true,
    },
    {
      title: '设备类型',
      dataIndex: 'typeName',
      width: 100,
      resizable: true,
    },
    {
      title: '设备位置',
      dataIndex: 'address',
      width: 100,
      resizable: true,
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      width: 100,
      resizable: true,
    },
    {
      title: '故障等级',
      dataIndex: 'level',
      width: 100,
      resizable: true,
    },
    {
      title: '故障描述',
      dataIndex: 'remark',
      width: 150,
      resizable: true,
    },
    {
      title: '负责人',
      dataIndex: 'dealUserNames',
      width: 100,
      resizable: true,
    },
    {
      title: '告警时间',
      dataIndex: 'createDate',
      width: 150,
      resizable: true,
    },
    {
      title: '处理状态',
      dataIndex: 'state',
      width: 100,
      resizable: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'typeId',
      label: '设备类型',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        datasourceType: 'dic',
        params: { itemId: '1671412696707850241' },
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择设备类型',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'state',
      label: '状态',
      component: 'Select',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请选择状态',
        options: [
          { label: '已处理', value: 1 },
          { label: '待处理', value: 0 },
        ],
      },
    },
    {
      field: 'createDate',
      label: '告警时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
      },
    },
  ];
  const levelData = ref<Recordable[]>([]);

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerModal, { openModal }] = useModal();
  const [registerCheckModal, { openModal: openCheckModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: '设备告警',
    api: getDeviceAlarmPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['createDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 132,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('deviceAlarm:dispose')) {
            handleDispose(record);
          }
        },
      };
    },
    tableSetting: {
      size: false,
    },
  });

  onMounted(async () => {
    levelData.value = (await getDicDetailList({ itemId: '1679372182895345665' })) || [];
  });

  const getLevel = (level) => {
    const data = levelData.value.filter((x) => x.id === level);
    if (!data.length) return '';
    switch (data[0].value) {
      case '0':
        return 'error';
      case '1':
        return 'warning';
      case '2':
        return 'processing';
    }
  };

  const handleDispose = (record) => {
    openModal(true, {
      id: record.id,
    });
  };

  const handleView = (record) => {
    openCheckModal(true, {
      id: record.id,
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteDeviceAlarm(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };
  const handleExport = async () => {
    const res = await exportInfo();
    downloadByData(
      res.data,
      '设备告警.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
