<template>
  <BasicTable class="command-record-table" @register="registerTable">
    <template #recordContent="{ record }">
      <a-button type="link" class="ml-2" @click="handleRecordContent(record)"> 查看 </a-button>
    </template>
    <template #responseContent="{ record }">
      <div v-if="!record.request?.oneway">
        <a-button v-if="record?.response === null" type="text" class="ml-2"> 未响应 </a-button>
        <a-button v-else type="link" class="ml-2" @click="handleRecordResponseContent(record)">
          查看
        </a-button>
      </div>
      <div v-else>--</div>
    </template>
  </BasicTable>
</template>
<script lang="ts" setup>
  import { h } from 'vue';
  import { configColumns, searchFormSchema } from './config';
  import { deviceCommandRecordGetQuery } from '/@/api/device/deviceConfigApi';
  import { BasicTable, useTable } from '/@/components/Table';
  import { Modal } from 'ant-design-vue';
  import { JsonPreview } from '/@/components/CodeEditor';

  const props = defineProps({
    fromId: {
      type: String,
      default: '',
    },
  });
  const [registerTable] = useTable({
    api: deviceCommandRecordGetQuery,
    columns: configColumns,
    beforeFetch: (params) => {
      return {
        ...params,
        tbDeviceId: props.fromId,
      };
    },
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      fieldMapToTime: [['sendTime', ['startTime', 'endTime'], 'x']],
    },
    useSearchForm: true,
  });
  const commonModalInfo = (title, value) => {
    Modal.info({
      title,
      width: 600,
      content: h(JsonPreview, { data: value }),
    });
  };
  const handleRecordContent = (record) => {
    if (!record?.request?.body?.params) return;
    //如果是正常格式则返回params，否则输入什么内容则显示什么内容
    const jsonParams = JSON.parse(record?.request?.body?.params);
    commonModalInfo('命令下发内容', jsonParams?.params ? jsonParams?.params : jsonParams);
  };
  const handleRecordResponseContent = (record) => {
    const jsonParams = record?.response;
    commonModalInfo('响应内容', jsonParams);
  };
</script>

<style lang="less" scoped>
  .command-record-table {
    background-color: #f0f2f5;
    padding: 16px;
  }
</style>
