<script setup lang="ts">
import { reactive ,toRaw, onMounted } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { ColumnsType} from 'ant-design-vue/lib/table';
import useI18n from '@/hooks/useI18n';
import { OptionsType, WS } from '@/plugins/ws-websocket';
import {
  RESULT_CODE_ERROR
} from '@/constants/result-constants';

const { t } = useI18n();
const ws = new WS();

//查询数据
let queryParams = reactive({
  pid: undefined,
  name:"",
  port:undefined,
  flag: false,
  changeTime:5000,
});

//临时缓存
let queryParams2 = reactive({
  pid: undefined,
  name:"",
  port:undefined,
  flag: false,
  changeTime:5000,
})

//时间粒度
let timeOptions =[
  {label:t('views.tool.ps.fastSpeed'),value:3000},
  {label:t('views.tool.ps.normalSpeed'),value:5000},
  {label:t('views.tool.ps.slowSpeed'),value:10000},
];

/**钩子函数，界面打开初始化*/
onMounted(() =>{
  fnRealTime()//建立连接
  extracted()//先立刻发送请求获取第一次的数据
  queryReset2(false)//设置定时器
});

/**查询按钮**/
function queryTime(){//将表单中的数据传递给缓存数据（缓存数据自动同步请求信息中）
  queryParams2.pid=queryParams.pid;
  queryParams2.port=queryParams.port;
  queryParams2.name=queryParams.name;
  //queryParams.flag = true
  queryParams2.flag=true
  queryParams.pid=undefined;
  queryParams.name="";
  queryParams.port=undefined;
}

/**重置按钮**/
function queryReset(){
  queryParams.flag = false
  queryParams2.flag = false
}

let s:any = null
/**定时器**/
function queryReset2(c:boolean){
  if(c){
    clearInterval(s)//清理旧定时器
    ws.close();//断开原来的wb连接
    fnRealTime();//建立新的实时数据连接
  }
  s = setInterval(()=>{//设置新的定时器s
    extracted();
  },queryParams.changeTime)
}

/**刷新频率改变**/
function fnRealTime2() {//时间粒度改变时触发
  queryReset2(true)//改变定时器
}
/**
 * 实时数据
 */
function fnRealTime() {
  const options: OptionsType = {
    url: '/ws',
    onmessage: wsMessage,
    onerror: wsError,
  };
  //建立连接
  ws.connect(options);
}

/**接收数据后回调(失败） */
function wsError(ev: any) {
  // 接收数据后回调
  console.error(ev);
}

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

    processedData = data.map((item:any) => {
      const localAddr = `${item.localaddr.ip} : ${item.localaddr.port}`;
      const remoteAddr = `${item.remoteaddr.ip} : ${item.remoteaddr.port}`;
      return { ...item, localAddr, remoteAddr };
    });

  if (requestId) {
    tableState.data = processedData; // 将数据填入表格
  }
}

function extracted() {//将表单各条件值取出，并打包在data中发送请求
  const {pid,name, port, flag} = toRaw(queryParams2)//从queryParams中取出各属性值
  let data = {} // { 'PID': PID, 'name': name, 'port': port }
  if (flag){//若flag为真则把值封装进data
    data = { 'pid': pid, 'name': name, 'port': port }
  }
  //发送请求
  ws.send({
    'requestId': 'dxxx',
    'type': 'net',
    'data': data,
  });

}

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

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

/**表格字段列 */
const tableColumns: ColumnsType<any> = [
  {
    title: t('views.tool.net.PID'),
    dataIndex: 'pid',
    align: 'center',
    width: 50,
    sorter:{//PID排序
      compare:(a:any, b:any)=>a.pid-b.pid,
      multiple:1,
    }
  },
  {
    title: t('views.tool.net.name'),
    dataIndex: 'name',
    align: 'center',
    width: 100,
  },
  {
    title: t('views.tool.net.localAddr'),
    dataIndex: 'localAddr',
    align: 'center',
    width: 70,
  },
  {
    title: t('views.tool.net.remoteAddr'),
    dataIndex:'remoteAddr',
    align: 'center',
    width: 100,
  },
  {
    title: t('views.tool.net.status'),
    dataIndex: 'status',
    align: 'center',
    width: 70,
  },
  {
    title: t('views.tool.net.type'),
    dataIndex: 'type',
    align: 'center',
    width: 100,
  },
];


</script>
<template>
  <PageContainer>
    <a-card
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <a-form :model="queryParams" name="formParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="3" :md="6" :xs="12">
            <a-form-item  :label="t('views.tool.ps.changeTime')" name="changeTime">
              <a-select
                v-model:value="queryParams.changeTime"
                :options="timeOptions"
                :placeholder="t('common.selectPlease')"
                @change='fnRealTime2'
              />
            </a-form-item></a-col>
          <a-col :lg="3" :md="6" :xs="12">
            <a-form-item  :label="t('views.tool.ps.PID')" name="pid">
              <a-input-number
                v-model:value="queryParams.pid"
                allow-clear
                :placeholder="t('common.inputPlease')"
                style='width: 100%'
              ></a-input-number>
            </a-form-item></a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item  :label="t('views.tool.net.name')" name="name">
              <a-input
                v-model:value="queryParams.name"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item></a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item  :label="t('views.tool.net.port')" name="port">
              <a-input
                v-model:value="queryParams.port"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item></a-col>
          <a-col :lg="3" :md="4" :xs="5">
            <a-form-item>
              <a-button type="primary" @click='queryTime()'>
                <template #icon><SearchOutlined /></template>
                {{ t('common.search') }}
              </a-button>
              <a-button type="default" @click.prevent="queryReset()" style='left: 20px;'>
                <template #icon><ClearOutlined /></template>
                {{ t('common.reset') }}
              </a-button>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-card>
    <a-table
      class="table"
      row-key="id"
      :columns="tableColumns"
      :loading="tableState.loading"
      :data-source="tableState.data"
      :size="tableState.size"
      :scroll="{ y: 'calc(100vh - 480px)' }"
      :pagination='false'
    ></a-table>
  </PageContainer>
</template>
<style lang="less" scoped>
.table :deep(.ant-pagination) {
  padding: 0 24px;
}
</style>
