<script setup lang="ts">
import { reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ColumnsType } from 'ant-design-vue/es/table';
import useI18n from '@/hooks/useI18n';
import { OptionsType, WS } from '@/plugins/ws-websocket';
import { RESULT_CODE_ERROR } from '@/constants/result-constants';
import { diffValue, parseDuration } from '@/utils/date-utils';
import { parseSizeFromFile } from '@/utils/parse-utils';

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

/**表单查询参数 */
let queryParams = reactive({
  pid: undefined,
  name: '',
  username: '',
});

/**状态对象 */
let state = reactive({
  /**调度器 */
  interval: null as any,
  /**刷新周期 */
  intervalTime: 5_000,
  /**查询参数 */
  query: {
    pid: undefined,
    name: '',
    username: '',
  },
});

/**接收数据后回调（成功） */
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) {
    fnGetList();
    return;
  }

  // 收到消息数据
  if (requestId.startsWith('ps_')) {
    // 将数据填入表格
    if (Array.isArray(data)) {
      if (tableState.loading) {
        tableState.loading = false;
      }
      tableState.data = data;
    } else {
      tableState.data = [];
    }
  }
}

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

/**调度器周期变更*/
function fnIntervalChange(v: any) {
  clearInterval(state.interval);
  state.interval = null;
  const timer = parseInt(v);
  if (timer > 1_000) {
    state.intervalTime = v;
    fnGetList();
  }
}

/**查询列表 */
function fnGetList() {
  if (tableState.loading || ws.state() === -1) return;
  tableState.loading = true;
  const msg = {
    requestId: `ps_${state.interval}`,
    type: 'ps',
    data: state.query,
  };
  // 首发
  ws.send(msg);
  // 定时刷新数据
  state.interval = setInterval(() => {
    msg.data = JSON.parse(JSON.stringify(state.query));
    ws.send(msg);
  }, state.intervalTime);
}

/**查询参数传入 */
function fnQuery() {
  state.query = JSON.parse(JSON.stringify(queryParams));
  nextTick(() => {
    ws.send({
      requestId: `ps_${state.interval}`,
      type: 'ps',
      data: state.query,
    });
  });
}

/**查询参数重置 */
function fnQueryReset() {
  Object.assign(queryParams, {
    pid: undefined,
    name: '',
    username: '',
  });
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  // 重置查询条件
  Object.assign(state.query, {
    pid: undefined,
    name: '',
    username: '',
  });
}

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

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

/**表格字段列 */
const tableColumns: ColumnsType<any> = [
  {
    title: t('views.tool.ps.pid'),
    dataIndex: 'pid',
    align: 'right',
    width: 100,
    sorter: {
      compare: (a: any, b: any) => a.pid - b.pid,
      multiple: 3,
    },
  },
  {
    title: t('views.tool.ps.cpuPercent'),
    dataIndex: 'cpuPercent',
    align: 'left',
    width: 120,
    sorter: {
      compare: (a: any, b: any) => a.cpuPercent - b.cpuPercent,
      multiple: 3,
    },
    customRender(opt) {
      return `${opt.value} %`;
    },
  },
  {
    title: t('views.tool.ps.diskRead'),
    dataIndex: 'diskRead',
    align: 'right',
    width: 100,
    sorter: {
      compare: (a: any, b: any) => a.diskRead - b.diskRead,
      multiple: 3,
    },
    customRender(opt) {
      return parseSizeFromFile(+opt.value);
    },
  },
  {
    title: t('views.tool.ps.diskWrite'),
    dataIndex: 'diskWrite',
    align: 'right',
    width: 100,
    sorter: {
      compare: (a: any, b: any) => a.diskWrite - b.diskWrite,
      multiple: 3,
    },
    customRender(opt) {
      return parseSizeFromFile(+opt.value);
    },
  },
  {
    title: t('views.tool.ps.numThreads'),
    dataIndex: 'numThreads',
    align: 'left',
    width: 100,
    sorter: {
      //线程数比较大小
      compare: (a: any, b: any) => a.numThreads - b.numThreads,
      multiple: 4, //优先级4
    },
  },
  {
    title: t('views.tool.ps.runTime'),
    dataIndex: 'startTime',
    align: 'left',
    width: 100,
    customRender(opt) {
      const second = diffValue(Date.now(), +opt.value, 'second');
      return parseDuration(second);
    },
  },
  {
    title: t('views.tool.ps.username'),
    dataIndex: 'username',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.tool.ps.name'),
    dataIndex: 'name',
    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;
  },
});

/**钩子函数，界面打开初始化*/
onMounted(() => {
  fnRealTime(false);
});

/**钩子函数，界面关闭*/
onBeforeUnmount(() => {
  clearInterval(state.interval);
  state.interval = null;
  ws.close();
});
</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="4" :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.ps.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.ps.username')" name="username">
              <a-input
                v-model:value="queryParams.username"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnQuery()">
                  <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-form layout="inline">
          <a-form-item :label="t('views.tool.ps.realTime')" name="realTime">
            <a-select
              v-model:value="state.intervalTime"
              :options="[
                { label: t('views.tool.ps.realTimeHigh'), value: 3_000 },
                { label: t('views.tool.ps.realTimeRegular'), value: 5_000 },
                { label: t('views.tool.ps.realTimeLow'), value: 10_000 },
                { label: t('views.tool.ps.realTimeStop'), value: -1 },
              ]"
              :placeholder="t('common.selectPlease')"
              @change="fnIntervalChange"
              style="width: 100px"
            />
          </a-form-item>
        </a-form>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="pid"
        :columns="tableColumns"
        :pagination="tablePagination"
        :loading="tableState.loading"
        :data-source="tableState.data"
        size="small"
        :scroll="{ x: tableColumns.length * 120 }"
      ></a-table>
    </a-card>
  </PageContainer>
</template>

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