<script setup lang="ts">
import { reactive, onMounted, toRaw, ref, onBeforeUnmount } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { message, Modal } from 'ant-design-vue/es';
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 useI18n from '@/hooks/useI18n';
import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
} from '@/constants/result-constants';
import useDictStore from '@/store/modules/dict';
import useNeInfoStore from '@/store/modules/neinfo';
import { listAMFDataUE, delAMFDataUE, exportAMFDataUE } from '@/api/neData/amf';
import { parseDateToStr } from '@/utils/date-utils';
import { OptionsType, WS } from '@/plugins/ws-websocket';
import dayjs, { Dayjs } from 'dayjs';
import saveAs from 'file-saver';
import PQueue from 'p-queue';
import { useClipboard } from '@vueuse/core';
const { copy } = useClipboard({ legacy: true });
const { t } = useI18n();
const { getDict } = useDictStore();
const ws = new WS();
const queue = new PQueue({ concurrency: 1, autoStart: true });
/**网元可选 */
let neOtions = ref<Record<string, any>[]>([]);

/**字典数据 */
let dict: {
  /**UE 事件认证代码类型 */
  ueAauthCode: DictType[];
  /**UE 事件类型 */
  ueEventType: DictType[];
  /**UE 事件CM状态 */
  ueEventCmState: DictType[];
} = reactive({
  ueAauthCode: [],
  ueEventType: [],
  ueEventCmState: [],
});

/**开始结束时间 */
let queryRangePicker = ref<[Dayjs, Dayjs] | undefined>([
  dayjs().startOf('hour'),
  dayjs().endOf('hour'),
]);
/**时间范围 */
let rangePickerPresets = ref([
  {
    label: 'Now hour',
    value: [dayjs().startOf('hour'), dayjs().endOf('hour')],
  },
  { label: 'Today', value: [dayjs().startOf('day'), dayjs().endOf('day')] },
  {
    label: 'Yesterday',
    value: [
      dayjs().subtract(1, 'day').startOf('day'),
      dayjs().subtract(1, 'day').endOf('day'),
    ],
  },
]);

/**查询参数 */
let queryParams = reactive({
  /**网元类型 */
  neType: 'AMF',
  neId: '001',
  eventType: '',
  imsi: '',
  sortField: 'timestamp',
  sortOrder: 'desc',
  /**开始时间 */
  beginTime: undefined as undefined | number,
  /**结束时间 */
  endTime: undefined as undefined | number,
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  eventTypes.value = [];
  queryParams = Object.assign(queryParams, {
    eventType: '',
    imsi: '',
    beginTime: undefined,
    endTime: undefined,
    pageNum: 1,
    pageSize: 20,
  });
  queryRangePicker.value = [dayjs().startOf('hour'), dayjs().endOf('hour')];
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

/**记录类型 */
const eventTypes = ref<string[]>([]);

/**查询记录类型变更 */
function fnQueryEventTypeChange(value: any) {
  if (Array.isArray(value)) {
    queryParams.eventType = value.join(',');
  }
}

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
};

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

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('common.rowId'),
    dataIndex: 'id',
    align: 'left',
    width: 100,
  },
  {
    title: 'IMSI',
    dataIndex: 'eventJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const eventJSON = opt.value;
      return eventJSON.imsi;
    },
  },
  {
    title: t('views.dashboard.ue.eventType'),
    dataIndex: 'eventType',
    key: 'eventType',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.dashboard.ue.result'),
    dataIndex: 'eventJSON',
    key: 'result',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.dashboard.ue.time'),
    dataIndex: 'eventJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const record = opt.value;
      if (record?.time) {
        return record.time;
      }
      return parseDateToStr(+record.timestamp * 1000);
    },
  },
  {
    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;
}

/**表格多选 */
function fnTableSelectedRowKeys(keys: (string | number)[]) {
  tableState.selectedRowKeys = keys;
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**最大ID值 */
  maxId: number;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  confirmLoading: false,
  maxId: 0,
});

/**
 * 记录删除
 * @param id  编号
 */
function fnRecordDelete(id: string) {
  if (!id || modalState.confirmLoading) return;
  let msg = id;
  if (id === '0') {
    msg = `${id}...  ${tableState.selectedRowKeys.length}`;
    id = tableState.selectedRowKeys.join(',');
  }

  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.dashboard.ue.delTip', { msg }),
    onOk() {
      modalState.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      delAMFDataUE(id)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.operateOk'),
              duration: 3,
            });
            fnGetList(1);
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    },
  });
}

/**查询列表, 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;
  }

  listAMFDataUE(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      const { total, rows } = res.data;
      tablePagination.total = total;
      // 遍历处理cdr字符串数据
      tableState.data = rows.map((item: any) => {
        let eventJSON = item.eventJSON;
        if (!eventJSON) {
          Reflect.set(item, 'eventJSON', {});
        }

        try {
          eventJSON = JSON.parse(eventJSON);
          Reflect.set(item, 'eventJSON', eventJSON);
        } catch (error) {
          console.error(error);
          Reflect.set(item, 'eventJSON', {});
        }

        return item;
      });

      // 取最大值ID用作实时累加
      if (total > 0) {
        modalState.maxId = Number(rows[0].id);
      }
    }
    tableState.loading = false;
  });
}

/**列表导出 */
function fnExportList() {
  if (modalState.confirmLoading) return;
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.dashboard.ue.exportTip'),
    onOk() {
      const hide = message.loading(t('common.loading'), 0);
      const querys = toRaw(queryParams);
      querys.pageSize = 10000;
      exportAMFDataUE(querys)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.operateOk'),
              duration: 3,
            });
            saveAs(res.data, `amf_ue_event_export_${Date.now()}.xlsx`);
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    },
  });
}

/**
 * 复制CDR
 * @param jsonStr JSON字符串
 */
function fnRecordCopy(jsonStr: string) {
  if (!jsonStr) return;
  const text = JSON.stringify(jsonStr, null, 2);
  copy(text).then(() => {
    message.success(t('common.copyOk'), 3);
  });
}

/**实时数据开关 */
const realTimeData = ref<boolean>(false);

/**
 * 实时数据
 */
function fnRealTime() {
  realTimeData.value = !realTimeData.value;
  if (realTimeData.value) {
    tableState.seached = false;
    // 建立链接
    const options: OptionsType = {
      url: '/ws',
      params: {
        /**订阅通道组
         *
         * AMF_UE会话事件(GroupID:1010_neId)
         */
        subGroupID: `1010_${queryParams.neId}`,
      },
      onmessage: wsMessage,
      onerror: (ev: any) => {
        console.error(ev);
      },
    };
    ws.connect(options);
  } else {
    ws.close();
    tableState.seached = true;
    fnGetList(1);
  }
}

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

  // 订阅组信息
  if (!data?.groupId) {
    return;
  }
  // ueEvent AMF_UE会话事件
  if (data.groupId === `1010_${queryParams.neId}`) {
    const ueEvent = data.data;
    queue.add(async () => {
      modalState.maxId += 1;
      tableState.data.unshift({
        id: modalState.maxId,
        neType: ueEvent.neType,
        neName: ueEvent.neName, // 空
        rmUID: ueEvent.rmUID, // 空
        timestamp: ueEvent.timestamp,
        eventType: ueEvent.eventType,
        eventJSON: ueEvent.eventJSON,
      });
      tablePagination.total += 1;
      if (tableState.data.length > 100) {
        tableState.data.pop();
      }
      await new Promise(resolve => setTimeout(resolve, 800));
    });
  }
}

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([
    getDict('ue_auth_code'),
    getDict('ue_event_type'),
    getDict('ue_event_cm_state'),
  ]).then(resArr => {
    if (resArr[0].status === 'fulfilled') {
      dict.ueAauthCode = resArr[0].value;
    }
    if (resArr[1].status === 'fulfilled') {
      dict.ueEventType = resArr[1].value;
    }
    if (resArr[2].status === 'fulfilled') {
      dict.ueEventCmState = resArr[2].value;
    }
  });

  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
        let arr: Record<string, any>[] = [];
        res.data.forEach((v: any) => {
          if (v.neType === 'AMF') {
            arr.push({ value: v.neId, label: v.neName });
          }
        });
        neOtions.value = arr;
        if (arr.length > 0) {
          queryParams.neId = arr[0].value;
        } else {
          message.warning({
            content: t('common.noData'),
            duration: 2,
          });
        }
      } else {
        message.warning({
          content: t('common.noData'),
          duration: 2,
        });
      }
    })
    .finally(() => {
      // 获取列表数据
      fnGetList();
    });
});

onBeforeUnmount(() => {
  if (ws.state() !== -1) {
    ws.close();
  }
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item label="AMF" name="neId ">
              <a-select
                v-model:value="queryParams.neId"
                :options="neOtions"
                :placeholder="t('common.selectPlease')"
                @change="fnGetList(1)"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.dashboard.ue.eventType')"
              name="eventType "
            >
              <a-select
                v-model:value="eventTypes"
                mode="multiple"
                :options="dict.ueEventType"
                :placeholder="t('common.selectPlease')"
                @change="fnQueryEventTypeChange"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item label="IMSI" name="imsi ">
              <a-input
                v-model:value="queryParams.imsi"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </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-col :lg="8" :md="12" :xs="24">
            <a-form-item
              :label="t('views.dashboard.cdr.time')"
              name="queryRangePicker"
            >
            <a-range-picker
                v-model:value="queryRangePicker"
                :presets="rangePickerPresets"
                :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-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8" align="center">
          <a-popconfirm
            placement="bottomLeft"
            :title="
              !realTimeData
                ? t('views.dashboard.ue.realTimeDataStart')
                : t('views.dashboard.ue.realTimeDataStop')
            "
            ok-text="Yes"
            cancel-text="No"
            @confirm="fnRealTime()"
          >
            <a-button type="primary" :danger="realTimeData">
              <template #icon><FundOutlined /> </template>
              {{
                !realTimeData
                  ? t('views.dashboard.ue.realTimeDataStart')
                  : t('views.dashboard.ue.realTimeDataStop')
              }}
            </a-button>
          </a-popconfirm>

          <a-button
            type="default"
            danger
            :disabled="tableState.selectedRowKeys.length <= 0"
            :loading="modalState.confirmLoading"
            @click.prevent="fnRecordDelete('0')"
            v-perms:has="['cdr:ne:remove']"
          >
            <template #icon><DeleteOutlined /></template>
            {{ t('common.deleteText') }}
          </a-button>

          <a-button type="dashed" @click.prevent="fnExportList()">
            <template #icon><ExportOutlined /></template>
            {{ t('common.export') }}
          </a-button>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.searchBarText') }}</template>
            <a-switch
              v-model:checked="tableState.seached"
              :checked-children="t('common.switch.show')"
              :un-checked-children="t('common.switch.hide')"
              size="small"
              :disabled="realTimeData"
            />
          </a-tooltip>
          <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" placement="bottomRight">
              <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: tableColumns.length * 120, y: 'calc(100vh - 480px)' }"
        :row-selection="{
          type: 'checkbox',
          columnWidth: '48px',
          selectedRowKeys: tableState.selectedRowKeys,
          onChange: fnTableSelectedRowKeys,
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'eventType'">
            <DictTag :options="dict.ueEventType" :value="record.eventType" />
          </template>
          <template v-if="column.key === 'result'">
            <span v-if="record.eventType === 'auth-result'">
              <DictTag
                :options="dict.ueAauthCode"
                :value="record.eventJSON.result"
              />
            </span>
            <span v-if="record.eventType === 'detach'">
              <span>{{ t('views.dashboard.ue.resultOk') }}</span>
            </span>
            <span v-if="record.eventType === 'cm-state'">
              <DictTag
                :options="dict.ueEventCmState"
                :value="record.eventJSON.result"
              />
            </span>
          </template>
          <template v-if="column.key === 'id'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.copyText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnRecordCopy(record.eventJSON)"
                >
                  <template #icon>
                    <CopyOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnRecordDelete(record.id)"
                  v-perms:has="['cdr:ne:remove']"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
        <template #expandedRowRender="{ record }">
          <a-row :gutter="16">
            <a-col :lg="8" :md="12" :xs="24" :offset="2">
              <a-divider orientation="left">
                {{ t('views.dashboard.ue.ueInfo') }}
              </a-divider>
              <div>
                <span>{{ t('views.ne.common.neName') }}: </span>
                <span>{{ record.neName }}</span>
              </div>
              <div>
                <span>{{ t('views.ne.common.rmUid') }}: </span>
                <span>{{ record.rmUID }}</span>
              </div>
            </a-col>
            <a-col :lg="8" :md="12" :xs="24">
              <a-divider orientation="left">
                {{ t('views.dashboard.ue.rowInfo') }}
              </a-divider>
              <div>
                <span>{{ t('views.dashboard.ue.time') }}: </span>
                <template v-if="record.eventJSON?.time">
                  {{ record.eventJSON.time }}
                </template>
                <template v-else>
                  {{ parseDateToStr(record.eventJSON.timestamp * 1000) }}
                </template>
              </div>
              <div>
                <span>{{ t('views.dashboard.ue.eventType') }}: </span>
                <DictTag
                  :options="dict.ueEventType"
                  :value="record.eventType"
                />
              </div>
              <div>
                <span>{{ t('views.dashboard.ue.result') }}: </span>
                <span v-if="record.eventType === 'auth-result'">
                  <DictTag
                    :options="dict.ueAauthCode"
                    :value="record.eventJSON.result"
                  />
                </span>
                <span v-if="record.eventType === 'detach'">
                  {{ t('views.dashboard.ue.resultOk') }}
                </span>
                <span v-if="record.eventType === 'cm-state'">
                  <DictTag
                    :options="dict.ueEventCmState"
                    :value="record.eventJSON.result"
                  />
                </span>
              </div>
            </a-col>
          </a-row>
        </template>
      </a-table>
    </a-card>
  </PageContainer>
</template>

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