<script setup lang="ts">
import { reactive, onMounted, onBeforeUnmount, ref } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { message } from 'ant-design-vue/lib';
import useI18n from '@/hooks/useI18n';
import { OptionsType, WS } from '@/plugins/ws-websocket';
import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
} from '@/constants/result-constants';
import useNeInfoStore from '@/store/modules/neinfo';
const neInfoStore = useNeInfoStore();
const { t } = useI18n();
const ws = new WS();

/**网元参数 */
let neCascaderOptions = ref<Record<string, any>[]>([]);

/**状态对象 */
let state = reactive({
  /**初始化 */
  initialized: false,
  /**网元类型 */
  neType: [],
  /**数据类型 */
  dataType: 'options' as 'options' | 'command',
  /**ws参数 */
  params: {
    neType: 'AMF',
    neId: '001',
    cols: 120,
    rows: 40,
  },
  /**ws数据 */
  data: {
    command: '', // 命令字符串
    desAddr: 'www.baidu.com', // dns name or ip address
    // Options
    interval: 1, //  seconds between sending each packet
    ttl: 255, // define time to live
    count: 4, // <count> 次回复后停止
    size: 56, // 使用 <size> 作为要发送的数据字节数
    timeout: 2, //  seconds time to wait for response
  },
});

/**接收数据后回调（成功） */
function wsMessage(res: Record<string, any>) {
  const { code, requestId, data } = res;
  if (code === RESULT_CODE_ERROR) {
    console.warn(res.msg);
    return;
  }

  // 建联时发送请求
  if (!requestId && data.clientId) {
    state.initialized = true;
    return;
  }

  // 收到消息数据
  if (requestId.startsWith('ping_')) {
    console.log(data);
  }
}

/**连接到ws*/
function fnConnect(reLink: boolean) {
  if (reLink) {
    ws.close();
  }
  const options: OptionsType = {
    url: '/tool/ping/run',
    params: state.params,
    onmessage: wsMessage,
    onerror: (ev: any) => {
      // 接收数据后回调
      console.error(ev);
    },
  };
  //建立连接
  ws.connect(options);
}

/**钩子函数，界面打开初始化*/
onMounted(() => {
  // 获取网元网元列表
  neInfoStore.fnNelist().then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      if (res.data.length > 0) {
        // 过滤不可用的网元
        for (const item of neInfoStore.getNeCascaderOptions) {
          neCascaderOptions.value.push(item);
        }

        if (neCascaderOptions.value.length === 0) {
          message.warning({
            content: t('common.noData'),
            duration: 2,
          });
          return;
        }
      }
    } else {
      message.warning({
        content: t('common.noData'),
        duration: 2,
      });
    }
  });
});

/**钩子函数，界面关闭*/
onBeforeUnmount(() => {
  if (ws.state() === WebSocket.OPEN) ws.close();
});
</script>

<template>
  <PageContainer>
    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8">
          <a-cascader
            v-model:value="state.neType"
            :options="neCascaderOptions"
            :placeholder="t('common.selectPlease')"
          />
          <a-radio-group v-model:value="state.dataType" button-style="solid">
            <a-radio-button value="options">Options</a-radio-button>
            <a-radio-button value="commandb">Command</a-radio-button> 
          </a-radio-group>
          <a-button @click.prevent="fnConnect(false)">
            <template #icon><PlayCircleOutlined /></template>
            Connect {{ state.initialized }}
          </a-button>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        :columns="[]"
        :data-source="[]"
        :pagination="false"
        :loading="false"
      />
    </a-card>
  </PageContainer>
</template>

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