<script setup lang="ts">
import { reactive, onMounted, toRaw, onBeforeUnmount, ref } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { Modal, message } 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 {
  delSMFDataCDR,
  exportSMFDataCDR,
  listSMFDataCDR,
} from '@/api/neData/smf';
import { OptionsType, WS } from '@/plugins/ws-websocket';
import PQueue from 'p-queue';
import saveAs from 'file-saver';
import { parseDateToStr } from '@/utils/date-utils';
const { t } = useI18n();
const ws = new WS();
const queue = new PQueue({ concurrency: 1, autoStart: true });

/**开始结束时间 */
let queryRangePicker = ref<[string, string]>(['', '']);

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

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

/**表格状态类型 */
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: 'center',
  //   width: 100,
  // },
  {
    title: t('views.dashboard.cdr.chargingID'), // 计费ID
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 100,
    customRender(opt) {
      const cdrJSON = opt.value;
      return cdrJSON.chargingID;
    },
  },
  {
    title: t('views.dashboard.cdr.smfSubscriptionIDType'), // 订阅 ID 类型
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const cdrJSON = opt.value;
      return cdrJSON.subscriberIdentifier?.subscriptionIDType;
    },
  },
  {
    title: t('views.dashboard.cdr.smfSubscriptionIDData'), // 订阅 ID 数据
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const cdrJSON = opt.value;
      return cdrJSON.subscriberIdentifier?.subscriptionIDData;
    },
  },
  {
    title: t('views.dashboard.cdr.smfDataVolumeUplink'), // 数据量上行链路
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const cdrJSON = opt.value;
      const listOfMultipleUnitUsage = cdrJSON.listOfMultipleUnitUsage;
      if (
        !Array.isArray(listOfMultipleUnitUsage) ||
        listOfMultipleUnitUsage.length < 1
      ) {
        return 0;
      }
      const usedUnitContainer = listOfMultipleUnitUsage[0].usedUnitContainer;
      if (!Array.isArray(usedUnitContainer) || usedUnitContainer.length < 1) {
        return 0;
      }
      return usedUnitContainer[0].dataVolumeUplink;
    },
  },
  {
    title: t('views.dashboard.cdr.smfDataVolumeDownlink'), // 数据量下行链路
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 180,
    customRender(opt) {
      const cdrJSON = opt.value;
      const listOfMultipleUnitUsage = cdrJSON.listOfMultipleUnitUsage;
      if (
        !Array.isArray(listOfMultipleUnitUsage) ||
        listOfMultipleUnitUsage.length < 1
      ) {
        return 0;
      }
      const usedUnitContainer = listOfMultipleUnitUsage[0].usedUnitContainer;
      if (!Array.isArray(usedUnitContainer) || usedUnitContainer.length < 1) {
        return 0;
      }
      return usedUnitContainer[0].dataVolumeDownlink;
    },
  },
  {
    title: t('views.dashboard.cdr.smfDataTotalVolume'), // 数据总量
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 150,
    customRender(opt) {
      const cdrJSON = opt.value;
      const listOfMultipleUnitUsage = cdrJSON.listOfMultipleUnitUsage;
      if (
        !Array.isArray(listOfMultipleUnitUsage) ||
        listOfMultipleUnitUsage.length < 1
      ) {
        return 0;
      }
      const usedUnitContainer = listOfMultipleUnitUsage[0].usedUnitContainer;
      if (!Array.isArray(usedUnitContainer) || usedUnitContainer.length < 1) {
        return 0;
      }
      return usedUnitContainer[0].dataTotalVolume;
    },
  },
  {
    title: t('views.dashboard.cdr.durationTime'), // 持续时间
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 100,
    customRender(opt) {
      const cdrJSON = opt.value;
      return cdrJSON.duration;
    },
  },
  {
    title: t('views.dashboard.cdr.invocationTime'), // 调用时间
    dataIndex: 'cdrJSON',
    align: 'left',
    width: 200,
    customRender(opt) {
      const cdrJSON = opt.value;
      return parseDateToStr(cdrJSON.invocationTimestamp);
    },
  },
];

/**表格分页器参数 */
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;
}



/**对话框对象信息状态类型 */
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.cdr.delTip', { msg }),
    onOk() {
      modalState.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      delSMFDataCDR(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 (!queryRangePicker.value) {
    queryRangePicker.value = ['', ''];
  }
  queryParams.startTime = queryRangePicker.value[0];
  queryParams.endTime = queryRangePicker.value[1];
  listSMFDataCDR(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tablePagination.total = res.total;
      // 遍历处理cdr字符串数据
      tableState.data = res.rows.map(item => {
        let cdrJSON = item.cdrJSON;
        if (!cdrJSON) {
          Reflect.set(item, 'cdrJSON', {});
        }

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

        return item;
      });

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

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

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

/**
 * 实时数据
 */
function fnRealTime() {
  realTimeData.value = !realTimeData.value;
  if (realTimeData.value) {
    // 建立链接
    const options: OptionsType = {
      url: '/ws',
      params: {
        /**订阅通道组
         *
         * CDR会话事件-SMF (GroupID:1006)
         */
        subGroupID: '1006',
      },
      onmessage: wsMessage,
      onerror: wsError,
    };
    ws.connect(options);
  } else {
    ws.close();
  }
}

/**接收数据后回调 */
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;
  }

  // 订阅组信息
  if (!data?.groupId) {
    return;
  }
  // cdrEvent CDR会话事件
  if (data.groupId === '1006') {
    const cdrEvent = data.data;
    queue.add(async () => {
      modalState.maxId += 1;
      tableState.data.unshift({
        id: modalState.maxId,
        neType: cdrEvent.neType,
        neName: cdrEvent.neName,
        rmUID: cdrEvent.rmUID,
        timestamp: cdrEvent.timestamp,
        cdrJSON: cdrEvent.CDR,
      });
      tablePagination.total += 1;
      if (tableState.data.length > 100) {
        tableState.data.pop();
      }
      await new Promise(resolve => setTimeout(resolve, 800));
    });
  }
}

onMounted(() => {
  // 获取列表数据
  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="t('views.dashboard.cdr.smfSubscriptionIDData')"
              name="calledParty "
            >
              <a-input
                v-model:value="queryParams.subscriberID"
                allow-clear
                :placeholder="t('common.inputPlease')"
                :maxlength="40"
              ></a-input>
            </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"
                allow-clear
                bordered
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="x"
                style="width: 100%"
              ></a-range-picker>
            </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="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="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"
            />
          </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 * 150, y: 'calc(100vh - 480px)' }"
      >
        <template #expandedRowRender="{ record }">
          <a-row :gutter="16">
            <a-col :lg="8" :md="12" :xs="24" :offset="2">
              <a-divider orientation="left">
                {{ t('views.dashboard.cdr.cdrInfo') }}
              </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>
              <div>
                <span>{{ t('views.dashboard.cdr.time') }}: </span>
                <span>{{ parseDateToStr(record.cdrJSON.invocationTimestamp) }}</span>
              </div>
              <a-divider orientation="left">
                {{ t('views.dashboard.cdr.rowInfo') }}
              </a-divider>
              <div>
                <span>Record Network Function ID: </span>
                <span>{{ record.cdrJSON.recordingNetworkFunctionID }}</span>
              </div>
              <div>
                <span>Record Type: </span>
                <span>{{ record.cdrJSON.recordType }}</span>
              </div>
              <div>
                <span>Record Opening Time: </span>
                <span>{{ record.cdrJSON.recordOpeningTime }}</span>
              </div>
              <div>
                <span>Charging ID: </span>
                <span>{{ record.cdrJSON.chargingID }}</span>
              </div>
              <div>
                <span>Duration: </span>
                <span>{{ record.cdrJSON.duration }}</span>
              </div>
              <a-divider orientation="left"> Subscriber Identifier </a-divider>
              <div>
                <span>Subscription ID Type: </span>
                <span>
                  {{ record.cdrJSON.subscriberIdentifier?.subscriptionIDType }}
                </span>
              </div>
              <div>
                <span>Subscription ID Data: </span>
                <span>
                  {{ record.cdrJSON.subscriberIdentifier?.subscriptionIDData }}
                </span>
              </div>
            </a-col>
            <a-col :lg="8" :md="12" :xs="24">
              <a-divider orientation="left">
                List Of Multiple Unit Usage
              </a-divider>
              <div v-for="u in record.cdrJSON.listOfMultipleUnitUsage">
                <!-- <div>RatingGroup: {{ u.ratingGroup }}</div> -->
                <div v-for="udata in u.usedUnitContainer">
                  <div>
                    <span>Data Total Volume: </span>
                    <span>{{ udata.dataTotalVolume }}</span>
                  </div>
                  <div>
                    <span>Data Volume Downlink: </span>
                    <span>{{ udata.dataVolumeDownlink }}</span>
                  </div>
                  <div>
                    <span>Data Volume Uplink: </span>
                    <span>{{ udata.dataVolumeUplink }}</span>
                  </div>
                  <div>
                    <span>Time: </span>
                    <span>{{ udata.time }}</span>
                  </div>
                </div>
              </div>
              <a-divider orientation="left">
                PDU Session Charging Information
              </a-divider>
              <div>
                <span>User Identifier: </span>
                <span>{{
                  record.cdrJSON.pDUSessionChargingInformation?.userIdentifier
                }}</span>
              </div>
              <div>
                <span>SSC Mode: </span>
                <span>{{
                  record.cdrJSON.pDUSessionChargingInformation?.sSCMode
                }}</span>
                &nbsp;&nbsp;
                <span>RAT Type: </span>
                <span>{{
                  record.cdrJSON.pDUSessionChargingInformation?.rATType
                }}</span>
                &nbsp;&nbsp;
                <span>DNN ID: </span>
                <span>
                  {{ record.cdrJSON.pDUSessionChargingInformation?.dNNID }}
                </span>
              </div>
              <div>
                <span>PDU Type: </span>
                <span>
                  {{ record.cdrJSON.pDUSessionChargingInformation?.pDUType }}
                </span>
              </div>
              <div>
                <span>PDU IPv4 Address: </span>
                <span>
                  {{
                    record.cdrJSON.pDUSessionChargingInformation?.pDUAddress
                      ?.pDUIPv4Address
                  }}
                </span>
              </div>
              <div>
                <span>PDU IPv6 Addres Swith Prefix: </span>
                <span>
                  {{
                    record.cdrJSON.pDUSessionChargingInformation?.pDUAddress
                      ?.pDUIPv6AddresswithPrefix
                  }}
                </span>
              </div>
              <div>
                <span>Network Function IPv4: </span>
                <span>{{
                  record.cdrJSON.nFunctionConsumerInformation
                    .networkFunctionIPv4Address
                }}</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>
