<script setup lang="ts">
import { reactive, onMounted, toRaw, ref } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ProModal } from 'antdv-pro-modal';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/es/table';
import { parseDateToStr } from '@/utils/date-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useDictStore from '@/store/modules/dict';
import useTabsStore from '@/store/modules/tabs';
import { type Dayjs } from 'dayjs';
import useI18n from '@/hooks/useI18n';
import { getTraceData, listTraceData } from '@/api/trace/task';
import { decode } from 'js-base64';
import { useRoute, useRouter } from 'vue-router';
const { t } = useI18n();
const { getDict } = useDictStore();
const tabsStore = useTabsStore();
const router = useRouter();
const route = useRoute();

/**跟踪编号 */
const traceId = ref<string>(route.query.traceId as string);

/**关闭跳转 */
function fnClose() {
  const to = tabsStore.tabClose(route.path);
  if (to) {
    router.push(to);
  } else {
    router.back();
  }
}

/**字典数据 */
let dict: {
  /**跟踪消息类型 */
  traceMsgType: DictType[];
  /**跟踪消息方向 */
  traceMsgDirect: DictType[];
} = reactive({
  traceMsgType: [],
  traceMsgDirect: [],
});

/**开始结束时间 */
let queryRangePicker = ref<[Dayjs, Dayjs] | undefined>(undefined);
/**查询参数 */
let queryParams = reactive({
  traceId: traceId.value,
  sortBy: 'timestamp',
  sortOrder: 'asc',
  /**开始时间 */
  beginTime: undefined as undefined | number,
  /**结束时间 */
  endTime: undefined as undefined | number,
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 20,
  });
  queryRangePicker.value = undefined;
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**记录数据 */
  data: object[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'small',
  data: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('common.rowId'),
    dataIndex: 'id',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.traceManage.task.msgNe'),
    dataIndex: 'msgNe',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.traceManage.task.rowTime'),
    dataIndex: 'timestamp',
    align: 'left',
    width: 250,
    customRender(opt) {
      if (!opt.value) return '';
      const nanoseconds = opt.value; // 纳秒时间戳
      const milliseconds = Math.floor(nanoseconds / 1000000);
      const nanosecondsPart = (nanoseconds % 1000000)
        .toString()
        .padStart(6, '0');

      return `${parseDateToStr(
        milliseconds,
        'YYYY-MM-DD HH:mm:ss.SSS'
      )}.${nanosecondsPart}`;
    },
    sorter: true,
  },
  {
    title: t('views.traceManage.task.protocolOrInterface'),
    dataIndex: 'ifType',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.traceManage.task.msgEvent'),
    dataIndex: 'msgEvent',
    align: 'left',
    width: 200,
    ellipsis: true,
  },
  {
    title: t('views.traceManage.task.msgType'),
    dataIndex: 'msgType',
    key: 'msgType',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.traceManage.task.msgDirect'),
    dataIndex: 'msgDirect',
    key: 'msgDirect',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.traceManage.task.srcIp'),
    dataIndex: 'srcAddr',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.traceManage.task.dstIp'),
    dataIndex: 'dstAddr',
    align: 'left',
    width: 200,
  },
  {
    title: t('common.operate'),
    key: 'id',
    align: 'left',
  },
];

/**表格分页器参数 */
let tablePagination = reactive({
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: false,
  /**是否可以快速跳转至某页 */
  showQuickJumper: true,
  /**是否可以改变 pageSize */
  showSizeChanger: true,
  /**数据总数 */
  total: 0,
  showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**表格紧凑型变更操作 */
function fnTableSize({ key }: MenuInfo) {
  tableState.size = key as SizeType;
}

/**表格分页、排序、筛选变化时触发操作, 排序方式，取值为 ascend descend */
function fnTableChange(pagination: any, filters: any, sorter: any, extra: any) {
  const { field, order } = sorter;
  if (order) {
    queryParams.sortBy = field;
    queryParams.sortOrder = order.replace('end', '');
  } else {
    queryParams.sortOrder = 'asc';
  }
  fnGetList(1);
}

/**查询备份信息列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }

  // 时间范围
  if (
    Array.isArray(queryRangePicker.value) &&
    queryRangePicker.value.length > 0
  ) {
    queryParams.beginTime = queryRangePicker.value[0].valueOf();
    queryParams.endTime = queryRangePicker.value[1].valueOf();
  } else {
    queryParams.beginTime = undefined;
    queryParams.endTime = undefined;
  }

  listTraceData(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      const { total, rows } = res.data;
      tablePagination.total = total;
      tableState.data = rows;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

/**抽屉对象信息状态类型 */
type ModalStateType = {
  /**抽屉框是否显示 */
  open: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
};

/**抽屉对象信息状态 */
let modalState: ModalStateType = reactive({
  open: false,
  title: '',
  from: {
    rawData: '',
    rawDataHTML: '',
    downBtn: false,
  },
});

/**
 * 对话框弹出显示
 * @param row 记录信息
 */
function fnModalVisible(row: Record<string, any>) {
  getTraceData(row.id).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      Object.assign(modalState.from, res.data);
      // 进制转数据
      const hexString = parseBase64Data(res.data.rawMsg);
      const rawData = convertToReadableFormat(hexString);
      modalState.from.rawData = rawData;
      modalState.title = t('views.traceManage.task.taskInfo');
      modalState.open = true;
    }
  });
}

/**
 * 对话框弹出关闭
 */
function fnModalVisibleClose() {
  modalState.open = false;
  modalState.from.rawData = '';
}

// 将Base64编码解码为字节数组
function parseBase64Data(base64Data: string) {
  // 将Base64编码解码为字节数组
  const byteString = decode(base64Data);
  const byteArray = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    byteArray[i] = byteString.charCodeAt(i);
  }

  // 将每一个字节转换为2位16进制数表示，并拼接起来
  let hexString = '';
  for (let i = 0; i < byteArray.length; i++) {
    const hex = byteArray[i].toString(16);
    hexString += hex.length === 1 ? '0' + hex : hex;
  }
  return hexString;
}

// 转换十六进制字节流为可读格式和ASCII码表示
function convertToReadableFormat(hexString: string) {
  let result = '';
  let asciiResult = '';
  let arr = [];
  let row = 10000;
  for (let i = 0; i < hexString.length; i += 2) {
    const hexChars = hexString.substring(i, i + 2);
    const decimal = parseInt(hexChars, 16);
    const asciiChar =
      decimal >= 32 && decimal <= 126 ? String.fromCharCode(decimal) : '.';

    result += hexChars + ' ';
    asciiResult += asciiChar;

    if ((i + 2) % 32 === 0) {
      arr.push({
        row: row,
        code: result,
        asciiText: asciiResult,
      });
      result = '';
      asciiResult = '';
      row += 10;
    }
    if (2 + i == hexString.length) {
      arr.push({
        row: row,
        code: result,
        asciiText: asciiResult,
      });
      result = '';
      asciiResult = '';
      row += 10;
    }
  }
  return arr;
}

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([getDict('trace_msg_type'), getDict('trace_msg_direct')])
    .then(resArr => {
      if (resArr[0].status === 'fulfilled') {
        dict.traceMsgType = resArr[0].value;
      }
      if (resArr[1].status === 'fulfilled') {
        dict.traceMsgDirect = resArr[1].value;
      }
    })
    .finally(() => {
      // 获取列表数据
      fnGetList();
    });
});
</script>

<template>
  <PageContainer>
    <a-card
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="8" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.rowTime')"
              name="queryRangePicker"
            >
              <a-range-picker
                v-model:value="queryRangePicker"
                :bordered="true"
                :allow-clear="false"
                style="width: 100%"
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
              ></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnGetList(1)">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
                <a-button type="default" @click.prevent="fnQueryReset">
                  <template #icon><ClearOutlined /></template>
                  {{ t('common.reset') }}
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8" align="center">
          <a-button type="default" @click.prevent="fnClose()">
            <template #icon><CloseOutlined /></template>
            {{ t('common.close') }}
          </a-button>
          <span>
            {{ t('views.traceManage.task.traceId') }}:&nbsp;
            <strong>{{ traceId }}</strong>
          </span>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown trigger="click">
              <a-button type="text">
                <template #icon><ColumnHeightOutlined /></template>
              </a-button>
              <template #overlay>
                <a-menu
                  :selected-keys="[tableState.size as string]"
                  @click="fnTableSize"
                >
                  <a-menu-item key="default">{{
                    t('common.size.default')
                  }}</a-menu-item>
                  <a-menu-item key="middle">{{
                    t('common.size.middle')
                  }}</a-menu-item>
                  <a-menu-item key="small">{{
                    t('common.size.small')
                  }}</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="id"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: true }"
        @change="fnTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'msgType'">
            <DictTag :options="dict.traceMsgType" :value="record.msgType" />
          </template>
          <template v-if="column.key === 'msgDirect'">
            <DictTag :options="dict.traceMsgDirect" :value="record.msgDirect" />
          </template>
          <template v-if="column.key === 'id'">
            <a-space :size="8" align="center">
              <a-tooltip placement="topRight">
                <template #title>{{ t('common.viewText') }}</template>
                <a-button type="link" @click.prevent="fnModalVisible(record)">
                  <template #icon><ProfileOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <ProModal
      :drag="true"
      :width="800"
      :title="modalState.title"
      :open="modalState.open"
      @cancel="fnModalVisibleClose"
      :footer="false"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 8 }"
        :label-wrap="true"
      >
        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.msgType')"
              name="msgType"
            >
              <DictTag
                :options="dict.traceMsgType"
                :value="modalState.from.msgType"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.msgDirect')"
              name="msgDirect"
            >
              <DictTag
                :options="dict.traceMsgDirect"
                :value="modalState.from.msgDirect"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.srcIp')"
              name="srcAddr"
            >
              {{ modalState.from.srcAddr }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.dstIp')"
              name="dstAddr"
            >
              {{ modalState.from.dstAddr }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.msgNe')"
              name="msgNe"
            >
              {{ modalState.from.msgNe }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.traceManage.task.msgEvent')"
              name="msgEvent"
            >
              {{ modalState.from.msgEvent }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          v-if="modalState.from.imsi"
          :label="t('views.traceManage.task.imsi')"
          name="imsi"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.imsi }}
        </a-form-item>

        <a-form-item
          v-if="modalState.from.ifType"
          :label="t('views.traceManage.task.protocolOrInterface')"
          name="ifType"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.ifType }}
        </a-form-item>

        <a-form-item
          :label="t('views.traceManage.task.msgLen')"
          name="length"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.length }}
        </a-form-item>

        <a-form-item>
          <a-row class="raw" v-for="v in modalState.from.rawData" :key="v.row">
            <a-col class="num" :span="2">{{ v.row }}</a-col>
            <a-col class="code" :span="12">{{ v.code }}</a-col>
            <a-col class="txt" :span="10">{{ v.asciiText }}</a-col>
          </a-row>
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

<style lang="less" scoped>
.table :deep(.ant-pagination) {
  padding: 0 24px;
}

.raw {
  .num {
    background-color: #f0f0f0;
  }
  .code {
    background-color: #0078d4;
    color: #fff;
  }
  .txt {
    background-color: #d9d9d9;
  }
}
</style>
