<template>
  <a-drawer title="设备告警信息" placement="right" v-model:visible="sVisible" @update:visible="onVisibleChange"
    :destroyOnClose="true" :width="800">
    <Search :onClickSearch="onClickSearch" :onClickReset="onClickReset" />
    <a-table :scroll="{ x: '100%', y: 500 }" rowKey="hms_id" :loading="state.listLoading" :columns="columns"
      @change="refreshData" :rowClassName="rowClassName" :dataSource="state.list" :pagination="paginationConfig">
      <template #time="{ record }">
        <div>{{ record.create_time }}</div>
        <div :style="record.update_time ? '' : record.level === 1 ? 'color: orange;' :
          record.level === 2 ? 'color: red;' : 'color: #28d445;'">
          {{ record.update_time ?? '它正在发生……' }}</div>
      </template>
      <template #level="{ text }">
        <a-tag color="success" v-if="text === 0">
          正常
        </a-tag>
        <a-tag color="warning" v-else-if="text === 1">
          警告
        </a-tag>
        <a-tag color="error" v-else-if="text === 2">
          危险
        </a-tag>
      </template>
      <template v-for="col in ['code', 'message']" #[col]="{ text }" :key="col">
        <a-tooltip :title="text">
          {{ text }}
        </a-tooltip>
      </template>
    </a-table>
  </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import Search from './components/Search.vue'
import { Device, DeviceHms } from '/@/types/device'
import { apis } from '/@/api/custom'

const props = defineProps<{
  visible: boolean,
  device: null | Device,
}>()

const emit = defineEmits(['update:visible', 'ok', 'cancel'])

// 健康状态
const sVisible = ref(false)

watch(props, () => {
  sVisible.value = props.visible
  // 显示弹框时，获取设备hms信息
  if (props.visible) {
    showHms()
  }
})

function onVisibleChange(sVisible: boolean) {
  setVisible(sVisible)
}

function setVisible(v: boolean, e?: Event) {
  sVisible.value = v
  emit('update:visible', v, e)
}

interface State {
  query: any,
  listLoading: boolean,
  list: DeviceHms[],
};

const state: State = reactive({
  query: undefined,
  listLoading: false,
  list: [],
});

const paginationConfig = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 20,
  current: 1,
  total: 0
})

const fetchList = async () => {
  state.listLoading = true;
  try {
    const res = await apis.fetchDeviceHmsList({
      ...state.query,
      language: 'zh',
      page: paginationConfig.current,
      page_size: paginationConfig.pageSize
    });
    if (res.code === 0) {
      state.list = res.data.list;
      paginationConfig.total = res.data.pagination.total
      paginationConfig.current = res.data.pagination.page
      paginationConfig.pageSize = res.data.pagination.page_size
    }
  } catch (e) {
    console.error(e);
  } finally {
    state.listLoading = false;
  }
}

const showHms = async () => {
  const dock = props.device
  if (!dock) return
  await fetchList()
}

const columns = [
  {
    title: '发生时间',
    dataIndex: 'create_time',
    width: 180,
    slots: { customRender: 'time' }
  },
  {
    title: '告警等级',
    dataIndex: 'level',
    width: 100,
    slots: { customRender: 'level' }
  },
  {
    title: '设备SN',
    dataIndex: 'sn',
    width: 150,
  },
  {
    title: '错误码',
    dataIndex: 'key',
    ellipsis: true,
    slots: { customRender: 'code' }
  },
  {
    title: '告警内容',
    dataIndex: 'message_zh',
    ellipsis: true,
    slots: { customRender: 'message' }
  }
]

const rowClassName = (record: any, index: number) => {
  const className = []
  if ((index & 1) === 0) {
    className.push('table-striped')
  }
  return className.toString().replaceAll(',', ' ')
}

const refreshData = async (page: any) => {
  paginationConfig.current = page?.current!
  paginationConfig.pageSize = page?.pageSize!
  await fetchList();
}

// 点击搜索
const onClickSearch = async (query: any) => {
  state.query = query;
  await fetchList();
}

// 点击重置
const onClickReset = async (query: any) => {
  state.query = query;
  await fetchList();
}
</script>

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