<script setup lang="ts">
import { reactive, onMounted, toRaw, ref, onBeforeUnmount } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/lib/table';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useDictStore from '@/store/modules/dict';
import { listIMSDataCDR } from '@/api/neData/smf';
import { WS } from '@/plugins/ws-websocket';
import PQueue from 'p-queue';
const { t } = useI18n();
const { getDict } = useDictStore();
const ws = new WS();
const queue = new PQueue({ concurrency: 1, autoStart: true });

/**字典数据 */
let dict: {
  /**CDR SIP响应代码类别类型 */
  cdrSipCode: DictType[];
  /**CDR 呼叫类型 */
  cdrCallType: DictType[];
} = reactive({
  cdrSipCode: [],
  cdrCallType: [],
});

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

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

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

/**查询记录类型变更 */
function fnQueryRecordTypeChange(value: any) {
  if (Array.isArray(value)) {
    queryParams.recordType = 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: 'ID',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: 'Record Type',
    dataIndex: 'cdrJSON',
    align: 'left',
  },
  {
    title: 'Charging ID',
    dataIndex: 'chargingId',
    key: 'chargingId',
    align: 'center',
    width: 100,
  },
  {
    title: 'Subscriber ID',
    dataIndex: 'subscriberId',
    key: 'subscriberId',
    align: 'center',
    width: 120,
  },
  {
    title: 'Duration',
    dataIndex: 'duration',
    key: 'duration',
    align: 'center',
  },
  {
    title: 'Data Volume Uplink',
    dataIndex: 'dataVolumeUplink',
    key: 'dataVolumeUplink',
    align: 'center',
  },
  {
    title: 'Data Volume Downlink',
    dataIndex: 'dataVolumeDownlink',
    key: 'dataVolumeDownlink',
    align: 'center',
  },
  {
    title: 'DataTotal Volume',
    dataIndex: 'dataTotalVolume',
    align: 'center',
  },
  {
    title: 'pduAddress',
    key: 'pduAddress',
    dataIndex: 'pduAddress',
    align: 'center',
  },
  {
    title: 'createdAt',
    dataIndex: 'createdAt',
    align: 'center',
  },
];

/**表格分页器参数 */
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;
  /**表单数据 */
  from: Record<string, any>;
  /**标题 */
  title: string;
  /**详细框是否显示 */
  visibleByView: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  confirmLoading: false,
  maxId: 0,
  from: {
    iPV4dynamicAddressFlag: 'true',
    iPv6dynamicPrefixFlag: 'false',
    pDUIPv4Address: '',
    pDUIPv6AddresswithPrefix: '',
  },
  title: 'View',
  visibleByView: false,
});

/**
 * 对话框弹出显示为 查看
 * @param row 单行记录信息
 */
function fnModalVisibleByVive(row: Record<string, any>) {
  modalState.from = Object.assign(modalState.from, row);
  modalState.from.pduAddress = JSON.parse(row.pduAddress);
  modalState.title = `${row.subscriberID}`;
  modalState.visibleByView = true;
}

/**查询列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }
  listIMSDataCDR(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      /**测试数据 */

      // res.rows = [
      //   {
      //     id: '12',
      //     neType: 'SMF',
      //     neName: 'SMF_001',
      //     rmUID: '4400HX1SMF001',
      //     timestamp: 1700020424,
      //     recordType: '"21212"',
      //     chargingID: '82',
      //     subscriberID: '"82"',
      //     duration: '68',
      //     dataVolumeUplink: '[45]',
      //     dataVolumeDownlink: '[67]',
      //     dataTotalVolume: '[5]',
      //     pduAddress:
      //       '{"iPV4dynamicAddressFlag": true, "iPv6dynamicPrefixFlag":false, "pDUIPv4Address":"192.168.2.219","pDUIPv6AddresswithPrefix": ""}',
      //     createdAt: '2024-05-27T16:41:02Z',
      //   },
      // ];

      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tablePagination.total = res.total;
      tableState.data = res.rows;
    }
    tableState.loading = false;
  });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.visibleByView = false;
}

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([getDict('cdr_sip_code'), getDict('cdr_call_type')])
    .then(resArr => {
      if (resArr[0].status === 'fulfilled') {
        dict.cdrSipCode = resArr[0].value;
      }
      if (resArr[1].status === 'fulfilled') {
        dict.cdrCallType = resArr[1].value;
      }
    })
    .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="8" :md="12" :xs="24">
            <a-form-item
              :label="t('views.dashboard.cdr.recordType')"
              name="recordType "
            >
              <a-select
                v-model:value="recordTypes"
                mode="multiple"
                :options="
                  ['MOC', 'MTC', 'MOSM', 'MTSM'].map(v => ({ value: v }))
                "
                :placeholder="t('common.selectPlease')"
                @change="fnQueryRecordTypeChange"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :xs="24">
            <a-form-item label="Subscriber ID" name="subscriberID">
              <a-input
                v-model:value="queryParams.subscriberID"
                allow-clear
              ></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="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 #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 * 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 === 'callType'">
            <DictTag
              :options="dict.cdrCallType"
              :value="record.cdrJSON.callType"
            />
          </template>

          <template v-if="column.key === 'pduAddress'">
            <a-tooltip>
              <template #title>{{ t('common.viewText') }}</template>
              <a-button
                type="link"
                @click.prevent="fnModalVisibleByVive(record)"
              >
                <template #icon><ProfileOutlined /></template>
              </a-button>
            </a-tooltip>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <DraggableModal
      width="800px"
      :visible="modalState.visibleByView"
      :title="modalState.title"
      @cancel="fnModalCancel"
      :footer="null"
    >
      <a-form layout="horizontal" labelAlign="left" :labelWrap="false">
        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item label="subscriberID" name="subscriberID">
              {{ modalState.from.subscriberID }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item label="chargingID" name="chargingID">
              {{ modalState.from.chargingID }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-descriptions title="PDU Address" :column="2" size="small" bordered>
          <a-descriptions-item label="IPV4 Dynamic Address Flag">
            {{ modalState.from.pduAddress.iPV4dynamicAddressFlag }}
          </a-descriptions-item>
          <a-descriptions-item label="IPV6 Dynamic Prefix Flag">
            {{ modalState.from.pduAddress.iPv6dynamicPrefixFlag }}
          </a-descriptions-item>
          <a-descriptions-item label="PDU IPV4 Address">{{
            modalState.from.pduAddress.pDUIPv4Address
          }}</a-descriptions-item>
          <a-descriptions-item label="PDU IPV6 Address With Prefix">{{
            modalState.from.pduAddress.pDUIPv6AddresswithPrefix
          }}</a-descriptions-item>
        </a-descriptions>
      </a-form>
    </DraggableModal>
  </PageContainer>
</template>

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