<template>
  <SearchCommands @search="onSearch" />
  <template v-if="data">
    <el-table :data="data" :style="{ 'max-height': contentHeight + 'px' }" border stripe style="width: 100%">
      <el-table-column align="center" fixed label="设备ID" min-width="140" prop="deviceId" />
      <el-table-column align="center" label="类型" min-width="100">
        <template #default="scope">
          {{ computeType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" min-width="100">
        <template #default="scope">
          <el-tag :type="computeStatus(scope.row.status)">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="起始时间" min-width="200">
        <template #default="scope">
          {{ formatDate(+scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="截止时间" min-width="200">
        <template #default="scope">
          {{ formatDate(+scope.row.endTime) }}
        </template>
      </el-table-column>
    </el-table>
  </template>
</template>

<script setup>
import SearchCommands from 'components/search-commands.vue';
import { getCommansStatus } from 'apis';
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

const data = ref([]);
let contentHeight = 600;

// 设置表格高度
onMounted(() => {
  const winHeight = document.documentElement.clientHeight;
  contentHeight = winHeight - 150;
});

/**
 * 查询
 * @param {object} options
 * @returns {Promise<void>}
 */
async function onSearch(options) {
  try {
    data.value = await getCommansStatus(options);
  } catch (error) {
    ElMessage.error('查询失败');
    throw new Error(error);
  }
}

/**
 * 计算状态
 * @param {string} status
 * @returns {string}
 */
function computeStatus(status) {
  let statusStyle = 'success';
  switch (status) {
    case 'PENDING':
      statusStyle = 'primary';
      break;
    case 'FAIL':
      statusStyle = 'danger';
      break;
    case 'SUCCESS':
      statusStyle = 'success';
      break;
    default:
      statusStyle = 'primary';
      break;
  }
  return statusStyle;
}

/**
 * 转换类型
 * @param {string} type
 * @returns {string}
 */
function computeType(type) {
  return type === 'DATA' ? '业务' : '事件';
}

/**
 * 格式化时间为日期格式
 * @param {number} time
 * @returns {string}
 */
function formatDate(time) {
  try {
    return dayjs(time).format('YYYY-MM-DD');
  } catch (error) {
    return '';
  }
}
</script>
