<template>
  <BasicDrawer v-bind="$attrs" title="告警详情" @register="registerDrawer" width="30%">
    <BasicForm @register="registerForm" />
    <div class="flex justify-end">
      <a-button
        type="primary"
        class="mr-4"
        @click="handleAlarm"
        v-if="alarmStatus !== 'ACTIVE_ACK' && alarmStatus !== 'CLEARED_ACK'"
        >处理</a-button
      >
      <a-button
        danger
        type="primary"
        @click="clearAlarm"
        v-if="alarmStatus !== 'CLEARED_UNACK' && alarmStatus !== 'CLEARED_ACK'"
        >清除</a-button
      >
    </div>
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { alarmSchemasForm } from '../config/detail.config';
  import { clearOrAckAlarm } from '/@/api/device/deviceManager';
  import { alarmLevel, statusType } from '/@/views/device/list/config/detail.config';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  export default defineComponent({
    name: 'AlarmDetailDrawer',
    components: {
      BasicForm,
      BasicDrawer,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const [registerForm, { setFieldsValue, resetFields }] = useForm({
        showActionButtonGroup: false,
        schemas: alarmSchemasForm,
        labelCol: {
          span: 5,
        },
      });
      const alarmId = ref('');
      const alarmStatus = ref('');
      const [registerDrawer, { closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        await setFieldsValue({
          ...data,
          severity: alarmLevel(data.severity),
          status: statusType(data.status),
          details: JSON.stringify(data.details),
        });
        alarmStatus.value = data.status;
        alarmId.value = data.id;
      });
      // 处理报警
      const handleAlarm = async () => {
        await clearOrAckAlarm(unref(alarmId), false);
        emit('success');
        closeDrawer();
      };
      // 清除报警
      const clearAlarm = async () => {
        await clearOrAckAlarm(unref(alarmId), true);
        emit('success');
        closeDrawer();
      };
      return {
        registerDrawer,
        registerForm,
        clearAlarm,
        handleAlarm,
        alarmStatus,
      };
    },
  });
</script>

<style lang="less" scoped></style>
