<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ProModal } from 'antdv-pro-modal';
import { message, Modal, Form, notification } 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 UploadModal from '@/components/UploadModal/index.vue';
import TableColumnsDnd from '@/components/TableColumnsDnd/index.vue';
import useNeInfoStore from '@/store/modules/neinfo';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import saveAs from 'file-saver';
import {
  addUDMSub,
  batchAddUDMSub,
  batchDelUDMSub,
  delUDMSub,
  exportUDMSub,
  getUDMSub,
  importUDMSub,
  listUDMSub,
  resetUDMSub,
  updateUDMSub,
} from '@/api/neData/udm_sub';
import { uploadFile } from '@/api/tool/file';
import { getNeViewFile } from '@/api/tool/neFile';
const { t } = useI18n();

/**网元参数 */
let neOtions = ref<Record<string, any>[]>([]);

/**查询参数 */
let queryParams = reactive({
  /**网元ID */
  neId: undefined,
  /**移动编号 */
  imsi: '',
  /**移动号 */
  msisdn: '',
  /**排序字段 */
  sortField: 'imsi',
  /**排序方式 */
  sortOrder: 'asc',
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    imsi: '',
    msisdn: '',
    sortField: 'imsi',
    sortOrder: 'asc',
    pageNum: 1,
    pageSize: 20,
  });
  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: 'small',
  seached: true,
  data: [],
  selectedRowKeys: [],
});

/**表格字段列 */
let tableColumns = ref<ColumnsType>([
  {
    title: 'IMSI',
    dataIndex: 'imsi',
    align: 'center',
    fixed: 'left',
    sorter: true,
    resizable: true,
    width: 150,
    minWidth: 150,
    maxWidth: 300,
  },
  {
    title: 'MSISDN',
    dataIndex: 'msisdn',
    align: 'center',
    fixed: 'left',
    sorter: true,
    width: 150,
  },
  {
    title: 'Subscribed AMBR',
    dataIndex: 'ambr',
    align: 'center',
    width: 100,
  },
  {
    title: 'Subscribed SNSSAIs',
    dataIndex: 'nssai',
    align: 'center',
    width: 100,
  },
  {
    title: 'Forbidden Areas',
    dataIndex: 'arfb',
    align: 'center',
    width: 100,
  },
  {
    title: 'Service Area Restrict',
    dataIndex: 'sar',
    align: 'center',
    width: 100,
  },
  {
    title: '5G',
    dataIndex: 'cn',
    key: 'cnFlag',
    align: 'center',
    width: 100,
  },
  {
    title: '4G',
    dataIndex: 'epsFlag',
    key: 'epsFlag',
    align: 'center',
    width: 100,
  },
  {
    title: 'Subscribed Data',
    dataIndex: 'smData',
    align: 'left',
    resizable: true,
    width: 500,
    minWidth: 150,
    maxWidth: 500,
  },
  {
    title: t('common.operate'),
    key: 'imsi',
    align: 'left',
    fixed: 'right',
    width: 100,
  },
]);

/**表格字段列排序 */
let tableColumnsDnd = ref<ColumnsType>([]);

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

/**表格分页、排序、筛选变化时触发操作, 排序方式，取值为 ascend descend */
function fnTableChange(pagination: any, filters: any, sorter: any, extra: any) {
  const { field, order } = sorter;
  if (order) {
    queryParams.sortField = field;
    queryParams.sortOrder = order.replace('end', '');
  } else {
    queryParams.sortOrder = 'asc';
  }
  fnGetList(1);
}

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

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  openByView: boolean;
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**批量新增否显示 */
  openByBatch: boolean;
  /**批量删除否显示 */
  openByBatchDel: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**表单数据 */
  BatchDelForm: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**更新加载数据按钮 loading */
  loadDataLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByView: false,
  openByEdit: false,
  openByBatch: false,
  openByBatchDel: false,
  title: 'UDM签约用户',
  from: {
    id: undefined,
    neId: '',
    imsi: '',
    msisdn: '',
    // amDat
    ambr: 'def_ambr',
    nssai: 'def_nssai',
    rat: '0', // 0x00:VIRTUAL 0x01:WLAN 0x02:EUTRA 0x03:NR
    arfb: 'def_arfb',
    sar: 'def_sar',
    cnType: '3', // 0x00:EPC和5GC 0x01:5GC 0x02:EPC 0x03:EPC+5GC
    rfspIndex: 1,
    regTimer: 12000,
    ueUsageType: 1,
    activeTime: 1000,
    mico: '0',
    odbPs: '1',
    groupId: '-',
    // epsDat
    epsFlag: '1',
    epsOdb: [2],
    hplmnOdb: [3, 4],
    ard: [1, 7],
    epstpl: 'def_eps',
    contextId: '1',
    apnContext: [1, 2, 0, 0, 0, 0],
    staticIp: '-',
    //
    smData: '',
    smfSel: 'def_snssai',
    cag: '',
    // 非字段
    num: 1,
    remark: '',
  },
  BatchDelForm: {
    num: 1,
    imsi: '',
  },
  confirmLoading: false,
  loadDataLoading: false,
});

/**表单中多选的OPTION */
const modalStateFromOption = reactive({
  ardJson: [
    { label: 'UTRAN Not Allowed', value: 0 },
    { label: 'GERAN Not Allowed', value: 1 },
    { label: 'GAN Not Allowed', value: 2 },
    { label: 'I HSPA Evolution Not Allowed', value: 3 },
    { label: 'WB E-UTRAN Not Allowed', value: 4 },
    { label: 'HO To Non-3GPP Access Not Allowed', value: 5 },
    { label: 'NB IoT Not Allowed', value: 6 },
    { label: 'Enhanced Coverage Not Allowed', value: 7 },
  ],
  odbJson: [
    {
      label:
        'Barring of all outgoing international calls except those directed to the home PLMN country and outgoing inter-zonal calls barred',
      value: 0,
    },
    { label: 'All Packet Oriented Services Barred', value: 1 },
    { label: 'Roamer Access HPLMN-AP Barred', value: 2 },
    { label: 'Roamer Access to VPLMN-AP Barred', value: 3 },
    { label: 'Barring of all outgoing calls', value: 4 },
    { label: 'Barring of all outgoing international calls', value: 5 },
    {
      label:
        'Barring of all outgoing international calls except those directed to the home PLMN country',
      value: 6,
    },
    { label: 'Barring of outgoing inter-zonal calls', value: 7 },
    {
      label:
        'Barring of all outgoing inter-zonal calls except those directed to the home PLMN country barred',
      value: 8,
    },
  ],
  hplmnOdb: [
    { label: 'HPLMN specific barring type 1', value: 0 },
    { label: 'HPLMN specific barring type 2', value: 1 },
    { label: 'HPLMN specific barring type 3', value: 2 },
    { label: 'HPLMN specific barring type 4', value: 3 },
    { label: 'HPLMN specific barring type 5', value: 4 },
    { label: 'HPLMN specific barring type 6', value: 5 },
    { label: 'HPLMN specific barring type 7', value: 6 },
    { label: 'HPLMN specific barring type 8', value: 7 },
  ],
});

//新增时初始SM Data
const bigRows = ref<any[]>([
  {
    id: 0,
    sst: '',
    sd: '',
    smallRows: [
      {
        id: 0,
        dnn: '',
        smStaticIp: '',
        msIp: '',
      },
      {
        id: 1,
        dnn: 'ims',
        smStaticIp: '',
        msIp: '',
      },
    ],
  },
]);

//小数组的index
let smallRowIndexCounter = 0;

/**
 * 针对修改框的截取每位数值
 * @param num 二进制值: 10001 n:长度有几位
 */
function PrefixZero(num: any, n: any) {
  return (Array(n).join('0') + num).slice(-n);
}

/**
 * 对话框弹出显示为 批量新增,批量删除
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByBatch() {
  modalStateBatchDelFrom.resetFields(); //重置表单
  modalState.title =
    t('views.neUser.sub.batchDelText') + t('views.neUser.sub.subInfo');
  modalState.openByBatchDel = true;
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByEdit(imsi?: string) {
  if (!imsi) {
    modalStateFrom.resetFields();
    modalState.title = t('common.addText') + t('views.neUser.sub.subInfo');
    modalState.openByEdit = true;
  } else {
    if (modalState.confirmLoading) return;
    const hide = message.loading(t('common.loading'), 0);
    modalState.confirmLoading = true;
    const neId = queryParams.neId || '-';
    getUDMSub(neId, imsi)
      .then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          transformFormData(res.data.smData);
          let ardAll = parseInt(res.data.ard).toString(2).padStart(8, '0');
          let hplAll = parseInt(res.data.hplmnOdb).toString(2).padStart(8, '0');
          let odbAll = parseInt(res.data.epsOdb).toString(2).padStart(9, '0');
          const ardArray: any[] = [];
          const hplmnArray: any[] = [];
          const epsOdbArray: any[] = [];
          for (let i = 0; i < ardAll.length; i++) {
            if (PrefixZero(ardAll, ardAll.length).charAt(i) === '1') {
              ardArray.push(i);
            }
          }

          for (let i = 0; i < hplAll.length; i++) {
            if (PrefixZero(hplAll, hplAll.length).charAt(i) === '1') {
              hplmnArray.push(i);
            }
          }
          for (let i = 0; i < odbAll.length; i++) {
            if (PrefixZero(odbAll, odbAll.length).charAt(i) === '1') {
              epsOdbArray.push(i);
            }
          }
          res.data.ard = ardArray;
          res.data.hplmnOdb = hplmnArray;
          res.data.epsOdb = epsOdbArray;

          // 4G APN Context List
          const apnContextStr = res.data.apnContext;
          const apnContextArr = [];
          for (let i = 0; i < apnContextStr.length; i += 2) {
            const num = Number(`${apnContextStr[i]}${apnContextStr[i + 1]}`);
            apnContextArr.push(num);
          }

          modalState.from = Object.assign(modalState.from, res.data, {
            apnContext: apnContextArr,
          });

          modalState.title =
            t('common.editText') + t('views.neUser.sub.subInfo');
          modalState.openByEdit = true;
        } else {
          message.error(t('common.getInfoFail'), 2);
        }
      })
      .finally(() => {
        hide();
        modalState.confirmLoading = false;
      });
  }
}

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    num: [
      {
        required: true,
        message: t('views.neUser.sub.numAdd') + t('common.unableNull'),
      },
    ],
    imsi: [
      { required: true, message: 'IMSI' + t('common.unableNull') },
      { min: 15, max: 15, message: t('views.neUser.auth.imsiConfirm') },
    ],
    msisdn: [{ required: true, message: 'MSISDN' + t('common.unableNull') }],
    staticIp: [
      { required: true, message: 'static ip' + t('common.unableNull') },
    ],
  })
);

/**
 * 封装为SM Data
 */
function transformData(data: any) {
  let transformedData = data.map((item: any) => {
    if (!item.sst || !item.smallRows.every((smallRow: any) => smallRow.dnn)) {
      message.error({
        content: `${t('views.neUser.sub.smDataArrTip')}`,
        duration: 3,
      });
      throw new Error('sst, sd, and all dnn are required fields');
    }

    let sstSd = item.sd
      ? item.sst + '-' + item.sd.padStart(6, '0')
      : item.sst + '-';
    let smallRowData = item.smallRows
      .map((smallRow: any) => {
        let parts = [smallRow.dnn];
        if (smallRow.smStaticIp) {
          parts.push(smallRow.smStaticIp);
        }
        if (smallRow.msIp) {
          parts.push(smallRow.msIp);
        }
        return parts.join('-');
      })
      .join('&');

    return sstSd + '&' + smallRowData;
  });

  return transformedData;
}

/**
 * 拆解SM Data成表单数据
 */
function transformFormData(data: any) {
  let allData = data ? data.split(';') : [];
  let bigIDFlag = 0;
  let smallIDFlag = 0;

  let transformedData = allData.map((item: any) => {
    let json: any = {
      id: bigIDFlag++,
      sst: item.split('&')[0].split('-')[0],
      sd: item.split('&')[0].split('-')[1]
        ? item.split('&')[0].split('-')[1]
        : '',
      smallRows: [],
    };
    item
      .split('&')
      .slice(1)
      .forEach((single: any) => {
        let smallRowJson: any = {
          id: smallIDFlag++,
          dnn: single.split('-')[0],
          smStaticIp: '',
          msIp: '',
        };
        let smStaticIpArr: any = [];
        single
          .split('-')
          .slice(1)
          .forEach((dnnParts: any) => {
            if (dnnParts.includes('/') && dnnParts.includes(':')) {
              //IPV6 既有/ 又有:
              smStaticIpArr.push(dnnParts);
            }
            if (!dnnParts.includes('/') && !dnnParts.includes(':')) {
              const pattern = /^(\d{1,3}\.){3}\d{1,3}$/;
              if (pattern.test(dnnParts)) {
                // 验证数值范围
                const isValid = dnnParts.split('.').every((num: any) => {
                  const n = parseInt(num, 10);
                  return n >= 0 && n <= 255;
                });

                // 只有当验证通过时才添加 IP
                if (isValid) {
                  smStaticIpArr.push(dnnParts);
                }
              } else {
                //无/ 无:也有可能为dnn的字符串
                smallRowJson.dnn += '-' + dnnParts;
              }
            }

            if (dnnParts.includes('/') && !dnnParts.includes(':')) {
              //msIp  只有/ 没有：
              smallRowJson.msIp = dnnParts;
            }
          });
        smallRowJson.smStaticIp = smStaticIpArr.join('-');
        json.smallRows.push(smallRowJson);
      });
    return json;
  });
  if (transformedData.length > 0) {
    bigRows.value = transformedData;
  } else {
    bigRows.value = [
      {
        id: 0,
        sst: '',
        sd: '',
        smallRows: [
          {
            id: 0,
            dnn: '',
            smStaticIp: '',
            msIp: '',
          },
          {
            id: 1,
            dnn: 'ims',
            smStaticIp: '',
            msIp: '',
          },
        ],
      },
    ];
  }
}
/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  const from = Object.assign({}, toRaw(modalState.from));
  try {
    from.smData = transformData(bigRows.value).join(';');
  } catch (error: any) {
    console.error(error.message);
    return false;
  }

  modalStateFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      let ardArr = [0, 0, 0, 0, 0, 0, 0, 0];
      let hplmnArr = [0, 0, 0, 0, 0, 0, 0, 0];
      let odbArr = [0, 0, 0, 0, 0, 0, 0, 0, 0];

      from.ard.forEach((item: any) => {
        ardArr[item] = 1;
      });

      from.hplmnOdb.forEach((item: any) => {
        hplmnArr[item] = 1;
      });

      from.epsOdb.forEach((item: any) => {
        odbArr[item] = 1;
      });

      from.epsOdb = '' + parseInt(odbArr.join(''), 2);
      from.hplmnOdb = '' + parseInt(hplmnArr.join(''), 2);
      from.ard = '' + parseInt(ardArr.join(''), 2);

      // 4G APN Context List
      from.apnContext = from.apnContext
        .map((item: number) => `${item}`.padStart(2, '0'))
        .join('');

      from.activeTime = `${from.activeTime}`;
      from.rfspIndex = `${from.rfspIndex}`;
      from.regTimer = `${from.regTimer}`;
      from.ueUsageType = `${from.ueUsageType}`;
      from.neId = queryParams.neId || '-';
      const result = from.id
        ? updateUDMSub(from)
        : from.num === 1
        ? addUDMSub(from)
        : batchAddUDMSub(from, from.num);
      const hide = message.loading(t('common.loading'), 0);
      result
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            if (from.num === 1) {
              message.success({
                content: t('common.msgSuccess', { msg: modalState.title }),
                duration: 3,
              });
              fnGetList(1);
            } else {
              const timerS = Math.ceil(+from.num / 800) + 1;
              notification.success({
                message: modalState.title,
                description: t('common.operateOk'),
                duration: timerS,
              });
              setTimeout(() => {
                fnGetList(1);
              }, timerS * 1000);
            }
          } else {
            if (from.num === 1) {
              message.error({
                content: `${res.msg}`,
                duration: 3,
              });
            } else {
              notification.error({
                message: modalState.title,
                description: res.msg,
                duration: 3,
              });
            }
          }
        })
        .finally(() => {
          hide();
          fnModalCancel();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**对话框内批量添加表单属性和校验规则 */
const modalStateBatchDelFrom = Form.useForm(
  modalState.BatchDelForm,
  reactive({
    num: [
      {
        required: true,
        message: t('views.neUser.sub.numDel') + t('common.unableNull'),
      },
    ],
    imsi: [{ required: true, message: 'IMSI' + t('common.unableNull') }],
  })
);

/**
 * 对话框弹出 批量删除确认执行函数
 * 进行表达规则校验
 */
function fnBatchDelModalOk() {
  modalStateBatchDelFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      const from = toRaw(modalState.BatchDelForm);
      const neId = queryParams.neId || '-';
      batchDelUDMSub(neId, from.imsi, from.num).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          const timerS = Math.ceil(+from.num / 800) + 1;
          notification.success({
            message: modalState.title,
            description: t('common.operateOk'),
            duration: timerS,
          });
          setTimeout(() => {
            modalState.openByBatchDel = false;
            modalState.confirmLoading = false;
            modalStateBatchDelFrom.resetFields();
            fnGetList(1);
          }, timerS * 1000);
        } else {
          modalState.confirmLoading = false;
          notification.error({
            message: modalState.title,
            description: res.msg,
            duration: 3,
          });
        }
      });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByEdit = false;
  modalState.openByView = false;
  modalStateFrom.resetFields();
  bigRows.value = [
    {
      id: 0,
      sst: '',
      sd: '',
      smallRows: [
        {
          id: 0,
          dnn: '',
          smStaticIp: '',
          msIp: '',
        },
        {
          id: 1,
          dnn: 'ims',
          smStaticIp: '',
          msIp: '',
        },
      ],
    },
  ];
  smallRowIndexCounter = 0;
}

/**
 * 批量删除对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnBatchDelModalCancel() {
  modalState.openByBatchDel = false;
  modalState.openByView = false;
  modalStateBatchDelFrom.resetFields();
}

/**
 * UDM签约用户删除
 * @param imsi  编号imsi
 */
function fnRecordDelete(imsi: string) {
  const neId = queryParams.neId;
  if (!neId) return;
  let imsiMsg = imsi;
  if (imsi === '0') {
    imsiMsg = `${tableState.selectedRowKeys[0]}... ${t(
      'views.neUser.sub.numDel'
    )} ${tableState.selectedRowKeys.length}`;
    imsi = tableState.selectedRowKeys.join(',');
  }

  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.neUser.auth.delSure', { imsi: imsiMsg }),
    onOk() {
      modalState.loadDataLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      delUDMSub(neId, imsi)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            const msgContent = t('common.msgSuccess', {
              msg: t('common.deleteText'),
            });
            message.success({
              content: `${msgContent} : ${imsiMsg}`,
              duration: 3,
            });
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          fnGetList();
          modalState.loadDataLoading = false;
        });
    },
  });
}

/**
 * UDM签约用户导出
 */
function fnRecordExport(type: string = 'txt') {
  const selectLen = tableState.selectedRowKeys.length;
  if (selectLen <= 0) return;
  const neId = queryParams.neId;
  if (!neId) return;
  const hide = message.loading(t('common.loading'), 0);
  exportUDMSub({ type: type, neId: neId, imsis: tableState.selectedRowKeys })
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success({
          content: t('common.msgSuccess', { msg: t('common.export') }),
          duration: 2,
        });
        saveAs(res.data, `UDMSub_select_${Date.now()}.${type}`);
      } else {
        message.error({
          content: `${res.msg}`,
          duration: 2,
        });
      }
    })
    .finally(() => {
      hide();
    });
}

/**列表导出 */
function fnExportList(type: string) {
  const neId = queryParams.neId;
  if (!neId) return;
  const hide = message.loading(t('common.loading'), 0);
  exportUDMSub(Object.assign({ type: type }, queryParams))
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success({
          content: t('common.msgSuccess', { msg: t('common.export') }),
          duration: 2,
        });
        saveAs(res.data, `UDMSub_${Date.now()}.${type}`);
      } else {
        message.error({
          content: `${res.msg}`,
          duration: 2,
        });
      }
    })
    .finally(() => {
      hide();
    });
}

/**重新加载数据 */
function fnLoadData() {
  const neId = queryParams.neId;
  if (tableState.loading || !neId) return;
  modalState.loadDataLoading = true;
  tablePagination.total = 0;
  tableState.data = [];
  tableState.loading = true; // 表格loading
  resetUDMSub(neId).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      const num = res.data;
      const timerS = Math.ceil(+num / 800) + 3;
      notification.success({
        message: t('views.neUser.sub.loadData'),
        description: t('views.neUser.sub.loadDataTip', { num, timer: timerS }),
        duration: timerS,
      });
      // 延迟20s后关闭loading刷新列表
      setTimeout(() => {
        modalState.loadDataLoading = false;
        tableState.loading = false; // 表格loading
        fnQueryReset();
      }, timerS * 1000);
    } else {
      modalState.loadDataLoading = false;
      tableState.loading = false; // 表格loading
      fnQueryReset();
      message.error({
        content: t('common.getInfoFail'),
        duration: 3,
      });
    }
  });
}

/**查询网元列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
    tablePagination.current = pageNum;
  }
  listUDMSub(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }

      const { total, rows } = res.data;
      tablePagination.total = total;
      tableState.data = rows;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

/**对话框表格信息导入对象信息状态类型 */
type ModalUploadImportStateType = {
  /**是否显示 */
  open: boolean;
  /**标题 */
  title: string;
  /**是否上传中 */
  loading: boolean;
  /**上传结果信息 */
  msg: string;
  /**含失败信息 */
  hasFail: boolean;
};

/**对话框表格信息导入对象信息状态 */
let uploadImportState: ModalUploadImportStateType = reactive({
  open: false,
  title: t('components.UploadModal.uploadTitle'),
  loading: false,
  msg: '',
  hasFail: false,
});

/**对话框表格信息导入失败原因 */
function fnModalUploadImportFailReason() {
  const neId = queryParams.neId;
  if (!neId) return;
  const hide = message.loading(t('common.loading'), 0);
  getNeViewFile({
    neType: 'UDM',
    neId: neId,
    path: '/tmp',
    fileName: 'import_udmuser_err_records.txt',
  })
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success(t('common.operateOk'), 3);
        const blob = new Blob([res.data], {
          type: 'text/plain',
        });
        saveAs(blob, `import_udmuser_err_records_${Date.now()}.txt`);
      } else {
        message.error(`${res.msg}`, 3);
      }
    })
    .finally(() => {
      hide();
    });
}

/**对话框表格信息导入弹出窗口 */
function fnModalUploadImportOpen() {
  uploadImportState.msg = '';
  uploadImportState.hasFail = false;
  uploadImportState.loading = false;
  uploadImportState.open = true;
}

/**对话框表格信息导入关闭窗口 */
function fnModalUploadImportClose() {
  uploadImportState.open = false;
  fnGetList();
}

/**对话框表格信息导入上传 */
function fnModalUploadImportUpload(file: File) {
  const neId = queryParams.neId;
  if (!neId) {
    return Promise.reject('Unknown network element');
  }
  const hide = message.loading(t('common.loading'), 0);
  uploadImportState.loading = true;
  // 上传文件
  let formData = new FormData();
  formData.append('file', file);
  formData.append('subPath', 'import');
  uploadFile(formData)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        return res.data.filePath;
      } else {
        uploadImportState.msg = res.msg;
        uploadImportState.loading = false;
        return '';
      }
    })
    .then((filePath: string) => {
      if (!filePath) return;
      // 文件导入
      return importUDMSub({
        neId: neId,
        uploadPath: filePath,
      });
    })
    .then(res => {
      if (!res) return;
      uploadImportState.msg = res.msg;
      const regex = /fail num: (\d+)/;
      const match = res.msg.match(regex);
      if (match) {
        const failNum = Number(match[1]);
        uploadImportState.hasFail = failNum > 0;
      } else {
        uploadImportState.hasFail = false;
      }
    })
    .finally(() => {
      hide();
      uploadImportState.loading = false;
    });
}

function addSmallRow(bigIndex: any) {
  const newSmallRow = {
    id: ++smallRowIndexCounter,
    dnn: '',
    smStaticIp: '',
    msIp: '',
  };
  bigRows.value[bigIndex].smallRows.push(newSmallRow);
}

function addBigRow() {
  const newBigRow = {
    id: bigRows.value.length,
    sst: '',
    sd: '',
    smallRows: [
      {
        id: 0,
        dnn: '',
        smStaticIp: '',
        msIp: '',
      },
    ],
  };
  bigRows.value.push(newBigRow);
}

function delDNN(sonIndex: any, bigIndex: any) {
  bigRows.value[bigIndex].smallRows.splice(sonIndex, 1);
}

function delBigRow(bigIndex: any) {
  bigRows.value.splice(bigIndex, 1);
}

/**对话框表格信息导入模板 */
async function fnModalDownloadImportTemplate() {
  const hide = message.loading(t('common.loading'), 0);

  const baseUrl = import.meta.env.VITE_HISTORY_BASE_URL;
  const templateUrl = `${
    baseUrl.length === 1 && baseUrl.indexOf('/') === 0
      ? ''
      : baseUrl.indexOf('/') === -1
      ? '/' + baseUrl
      : baseUrl
  }/neDataImput`;
  saveAs(
    `${templateUrl}/udm_sub_template.txt`,
    `import_udmsub_template_${Date.now()}.txt`
  );

  hide();
}

onMounted(() => {
  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        if (res.data.length > 0) {
          let arr: Record<string, any>[] = [];
          res.data.forEach((v: any) => {
            if (v.neType === 'UDM') {
              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,
        });
      }
    })
    .finally(() => {
      // 获取列表数据
      fnGetList();
    });
});
</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="UDM" name="neId ">
              <a-select
                v-model:value="queryParams.neId"
                :options="neOtions"
                :placeholder="t('common.selectPlease')"
                :disabled="modalState.loadDataLoading"
                @change="fnGetList(1)"
              />
            </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
                :maxlength="15"
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item label="MSISDN" name="msisdn">
              <a-input
                v-model:value="queryParams.msisdn"
                allow-clear
                :maxlength="32"
                :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-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-flex wrap="wrap" gap="small">
          <a-button type="primary" @click.prevent="fnModalVisibleByEdit()">
            <template #icon>
              <PlusOutlined />
            </template>
            {{ t('common.addText') }}
          </a-button>

          <a-button
            type="primary"
            danger
            ghost
            @click.prevent="fnModalVisibleByBatch()"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            {{ t('views.neUser.auth.batchDelText') }}
          </a-button>

          <a-popconfirm
            :title="t('views.neUser.sub.loadDataConfirm')"
            :ok-text="t('common.ok')"
            :cancel-text="t('common.cancel')"
            :disabled="modalState.loadDataLoading"
            @confirm="fnLoadData"
          >
            <a-button
              type="dashed"
              danger
              :disabled="modalState.loadDataLoading"
              :loading="modalState.loadDataLoading"
            >
              <template #icon>
                <SyncOutlined />
              </template>
              {{ t('views.neUser.sub.loadData') }}
            </a-button>
          </a-popconfirm>

          <a-button type="dashed" @click.prevent="fnModalUploadImportOpen">
            <template #icon>
              <ImportOutlined />
            </template>
            {{ t('views.neUser.sub.import') }}
          </a-button>

          <a-popconfirm
            :title="t('views.neUser.sub.exportConfirm')"
            placement="topRight"
            ok-text="TXT"
            ok-type="default"
            @confirm="fnExportList('txt')"
          >
            <a-button type="dashed">
              <template #icon>
                <ExportOutlined />
              </template>
              {{ t('views.neUser.sub.export') }}
            </a-button>
          </a-popconfirm>

          <a-button
            type="default"
            danger
            :disabled="tableState.selectedRowKeys.length <= 0"
            :loading="modalState.loadDataLoading"
            @click.prevent="fnRecordDelete('0')"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            {{ t('views.neUser.sub.checkDel') }}
          </a-button>

          <a-popconfirm
            :title="t('views.neUser.sub.checkExportConfirm')"
            placement="topRight"
            ok-text="TXT"
            ok-type="default"
            @confirm="fnRecordExport('txt')"
            :disabled="tableState.selectedRowKeys.length <= 0"
          >
            <a-button
              type="default"
              :disabled="tableState.selectedRowKeys.length <= 0"
            >
              <template #icon>
                <ExportOutlined />
              </template>
              {{ t('views.neUser.sub.checkExport') }}
            </a-button>
          </a-popconfirm>
        </a-flex>
      </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>
          <TableColumnsDnd
            cache-id="udmSubData"
            :columns="tableColumns"
            v-model:columns-dnd="tableColumnsDnd"
          >
          </TableColumnsDnd>
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown placement="bottomRight" trigger="click">
              <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="imsi"
        :columns="tableColumnsDnd"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ y: 'calc(100vh - 480px)' }"
        @change="fnTableChange"
        @resizeColumn="(w: number, col: any) => (col.width = w)"
        :row-selection="{
          type: 'checkbox',
          selectedRowKeys: tableState.selectedRowKeys,
          onChange: fnTableSelectedRowKeys,
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cnFlag'">
            {{
              ['1', '3'].includes(record.cnType)
                ? t('views.neUser.sub.enable')
                : t('views.neUser.sub.disable')
            }}
          </template>
          <template v-if="column.key === 'epsFlag'">
            {{
              record.epsFlag === '1'
                ? t('views.neUser.sub.enable')
                : t('views.neUser.sub.disable')
            }}
          </template>
          <template v-if="column.key === 'imsi'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.editText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByEdit(record.imsi)"
                >
                  <template #icon>
                    <FormOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnRecordDelete(record.imsi)"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增框或修改框 -->
    <ProModal
      :drag="true"
      :width="800"
      :destroyOnClose="true"
      style="top: 0px"
      :body-style="{ maxHeight: '600px', 'overflow-y': 'auto' }"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :labelWrap="true"
      >
        <a-row>
          <a-col :lg="12" :md="12" :xs="24" v-show="!modalState.from.id">
            <a-form-item
              :label="t('views.neUser.sub.numAdd')"
              name="num"
              v-bind="modalStateFrom.validateInfos.num"
              :label-col="{ span: 12 }"
              :labelWrap="false"
            >
              <a-input-number
                v-model:value="modalState.from.num"
                style="width: 100%"
                :min="1"
                :max="500"
                :maxlength="3"
                placeholder="<=500"
              ></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              label="IMSI"
              name="imsi"
              v-bind="modalStateFrom.validateInfos.imsi"
            >
              <a-input
                v-model:value="modalState.from.imsi"
                allow-clear
                :maxlength="15"
                :disabled="!!modalState.from.id"
              >
                <template #prefix>
                  <a-tooltip placement="topLeft">
                    <template #title>
                      {{ t('views.neUser.sub.imsiTip') }}<br />
                      {{ t('views.neUser.sub.imsiTip1') }}<br />
                      {{ t('views.neUser.sub.imsiTip2') }}<br />
                      {{ t('views.neUser.sub.imsiTip3') }}
                    </template>
                    <InfoCircleOutlined style="opacity: 0.45; color: inherit" />
                  </a-tooltip>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              label="MSISDN"
              name="msisdn"
              v-bind="modalStateFrom.validateInfos.msisdn"
            >
              <a-input
                v-model:value="modalState.from.msisdn"
                allow-clear
                :maxlength="32"
              >
                <template #prefix>
                  <a-tooltip placement="topLeft">
                    <template #title>
                      {{ t('views.neUser.sub.msisdnTip', { num: '32' }) }}
                    </template>
                    <InfoCircleOutlined style="opacity: 0.45; color: inherit" />
                  </a-tooltip>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('common.remark')"
          :label-col="{ span: 3 }"
          :label-wrap="true"
        >
          <a-textarea
            v-model:value="modalState.from.remark"
            :auto-size="{ minRows: 1, maxRows: 6 }"
            :maxlength="500"
            :show-count="true"
            :placeholder="t('common.inputPlease')"
          />
        </a-form-item>

        <!-- SM Data ---- S -->
        <a-divider orientation="left">
          Subscribed SM Data
          <a-tooltip title="Add SM Data">
            <a-button
              shape="circle"
              @click="addBigRow"
              style="margin-left: 10px"
            >
              <template #icon><plus-outlined /></template>
            </a-button> </a-tooltip
        ></a-divider>
        <!-- 大数组布局 -->
        <div v-for="(row, index) in bigRows" :key="String(row.id)">
          <a-row>
            <a-col :lg="6" :md="6" :xs="24">
              <a-form-item
                label="SST"
                name="row.sst"
                :label-col="{ span: 12 }"
                :validateTrigger="[]"
                :required="true"
              >
                <a-input-number
                  v-model:value="row.sst"
                  :min="1"
                  :max="3"
                  :step="1"
                />
              </a-form-item>
            </a-col>

            <a-col :lg="8" :md="8" :xs="24">
              <a-form-item label="SD" name="row.sst" :label-col="{ span: 5 }">
                <a-input v-model:value="row.sd" :maxlength="6" />
              </a-form-item>
            </a-col>
            <a-col :lg="10" :md="10" :xs="24">
              <a-row>
                <a-col :span="4">
                  <a-tooltip title="Add DNN">
                    <a-button
                      shape="circle"
                      @click="addSmallRow(row.id)"
                      style="margin-left: 10px"
                    >
                      <template #icon><plus-square-outlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-col>
                <a-col :span="4">
                  <a-tooltip title="Delete SM Data" v-if="index !== 0">
                    <a-button danger shape="circle" @click="delBigRow(index)">
                      <template #icon><minus-outlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-col>
              </a-row>
            </a-col>
          </a-row>

          <!-- 小数组布局 -->
          <div
            v-for="(smallRow, smallIndex) in row.smallRows"
            :key="String(smallRow.id)"
          >
            <a-row>
              <a-col :lg="6" :md="6" :xs="24">
                <a-form-item
                  label="DNN/APN"
                  name="dnn"
                  :validateTrigger="[]"
                  :required="true"
                  :label-col="{ span: 12 }"
                >
                  <a-input v-model:value="smallRow.dnn" allow-clear></a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="8" :md="8" :xs="24">
                <a-form-item
                  label="Static IP"
                  name="smStaticIp"
                  :label-col="{ span: 5 }"
                >
                  <a-input
                    v-model:value="smallRow.smStaticIp"
                    allow-clear
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="8" :md="8" :xs="24">
                <a-form-item
                  label="Routing Behind MS IP"
                  style="margin-left: 10px"
                  name="msIp"
                >
                  <a-input v-model:value="smallRow.msIp" allow-clear></a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="2" :md="2" :xs="24" v-if="smallIndex !== 0">
                <a-tooltip title="Delete DNN">
                  <a-button
                    danger
                    shape="circle"
                    @click="delDNN(smallIndex, row.id)"
                    style="margin-left: 10px"
                  >
                    <template #icon><close-square-outlined /></template>
                  </a-button>
                </a-tooltip>
              </a-col>
            </a-row>
          </div>
        </div>
        <!-- SM Data ---- E -->

        <a-collapse :bordered="false" ghost>
          <a-collapse-panel key="5G">
            <template #header>
              <a-divider orientation="left" style="margin: -2px">5G</a-divider>
            </template>
            <a-row>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5GC Flag"
                  name="cnFlag"
                  :help="t('views.neUser.sub.cnFlag')"
                >
                  <a-select v-model:value="modalState.from.cnType">
                    <a-select-option value="3">
                      {{ t('views.neUser.sub.enable') }}
                    </a-select-option>
                    <a-select-option value="0">
                      {{ t('views.neUser.sub.disable') }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G Subscribed UE AMBR Template"
                  name="ambr"
                  v-bind="modalStateFrom.validateInfos.ambr"
                >
                  <a-input
                    v-model:value="modalState.from.ambr"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.inputTip', { num: '50' }) }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G Subscribed SNSSAIs Template"
                  name="nssai"
                  v-bind="modalStateFrom.validateInfos.nssai"
                >
                  <a-input
                    v-model:value="modalState.from.nssai"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.inputTip', { num: '50' }) }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G Subscribed SMF Selection Data Template"
                  name="smfSel"
                >
                  <a-input
                    v-model:value="modalState.from.smfSel"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.inputTip', { num: '50' }) }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item label="5G Forbidden Areas Template" name="arfb">
                  <a-input
                    v-model:value="modalState.from.arfb"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.arfbTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G CAG Template"
                  name="cag"
                  v-bind="modalStateFrom.validateInfos.cag"
                >
                  <a-input
                    v-model:value="modalState.from.cag"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.inputTip', { num: '50' }) }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G Service Area Restriction Template"
                  name="sar"
                >
                  <a-input
                    v-model:value="modalState.from.sar"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.sarTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="5G MICO Mode"
                  name="mico"
                  :help="t('views.neUser.sub.micoTip')"
                >
                  <a-select v-model:value="modalState.from.mico">
                    <a-select-option value="1">
                      {{ t('views.neUser.sub.enable') }}
                    </a-select-option>
                    <a-select-option value="0">
                      {{ t('views.neUser.sub.disable') }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item label="5G RAT Mode" name="rat">
                  <a-select v-model:value="modalState.from.rat">
                    <a-select-option value="0">VIRTUAL</a-select-option>
                    <a-select-option value="1">WLAN</a-select-option>
                    <a-select-option value="2">EUTRA</a-select-option>
                    <a-select-option value="3">NR</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item label="5G UE Usage Type" name="ueUsageType">
                  <a-input-number
                    v-model:value="modalState.from.ueUsageType"
                    style="width: 100%"
                    :min="0"
                    :max="127"
                    placeholder="0 ~ 127"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.ueTypeTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item label="5G RFSP Index" name="rfspIndex">
                  <a-input-number
                    v-model:value="modalState.from.rfspIndex"
                    style="width: 100%"
                    :min="0"
                    :max="127"
                    placeholder="0 ~ 127"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.rfspTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <a-collapse-panel key="4G">
            <template #header>
              <a-divider orientation="left" style="margin: -2px">4G</a-divider>
            </template>
            <a-row>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="4G EPS Flag"
                  name="epsFlag"
                  :help="t('views.neUser.sub.epsFlagTip')"
                >
                  <a-select v-model:value="modalState.from.epsFlag">
                    <a-select-option value="1">
                      {{ t('views.neUser.sub.enable') }}
                    </a-select-option>
                    <a-select-option value="0">
                      {{ t('views.neUser.sub.disable') }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="4G EPS User Template Name"
                  name="epstpl"
                  v-bind="modalStateFrom.validateInfos.epstpl"
                >
                  <a-input
                    v-model:value="modalState.from.epstpl"
                    allow-clear
                    :maxlength="50"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.inputTip', { num: '50' }) }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :lg="24" :md="24" :xs="24">
                <a-form-item
                  label="4G Static IP"
                  v-bind="modalStateFrom.validateInfos.staticIp"
                  name="staticIp"
                >
                  <a-input v-model:value="modalState.from.staticIp" allow-clear>
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.neUser.sub.staticIpTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="opacity: 0.45; color: inherit"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="4G Context ID" name="contextId">
              <a-input v-model:value="modalState.from.contextId" allow-clear>
                <template #prefix>
                  <a-tooltip placement="topLeft">
                    <template #title>
                      {{ t('views.neUser.sub.contextIdTip') }}
                    </template>
                    <InfoCircleOutlined style="opacity: 0.45; color: inherit" />
                  </a-tooltip>
                </template>
              </a-input>
            </a-form-item>

            <a-form-item
              label="4G APN Context List"
              name="apnContext"
              :help="t('views.neUser.sub.apnContextTip')"
            >
              <a-input-group compact>
                <a-input-number
                  v-for="(_, i) in modalState.from.apnContext"
                  :key="i"
                  :title="i"
                  style="width: 16.5%"
                  :min="0"
                  :max="99"
                  v-model:value="modalState.from.apnContext[i]"
                ></a-input-number>
              </a-input-group>
            </a-form-item>

            <a-form-item
              label="4G EPS ODB"
              name="epsOdb"
              v-bind="modalStateFrom.validateInfos.epsOdb"
            >
              <a-tooltip
                :title="t('views.neUser.sub.epsOdbTip')"
                placement="topLeft"
              >
                <a-select
                  v-model:value="modalState.from.epsOdb"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="Please select"
                  :options="modalStateFromOption.odbJson"
                  @change=""
                >
                </a-select>
              </a-tooltip>
            </a-form-item>

            <a-form-item label="4G HPLMN ODB" name="hplmnOdb">
              <a-tooltip
                :title="t('views.neUser.sub.hplmnOdbTip')"
                placement="topLeft"
              >
                <a-select
                  v-model:value="modalState.from.hplmnOdb"
                  mode="multiple"
                  style="width: 100%"
                  :options="modalStateFromOption.hplmnOdb"
                  @change=""
                >
                </a-select>
              </a-tooltip>
            </a-form-item>

            <a-form-item label="4G Access Restriction Data" name="ard">
              <a-tooltip
                :title="t('views.neUser.sub.ardTip')"
                placement="topLeft"
              >
                <a-select
                  v-model:value="modalState.from.ard"
                  mode="multiple"
                  style="width: 100%"
                  :options="modalStateFromOption.ardJson"
                  @change=""
                >
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </ProModal>

    <!-- 批量删除框 -->
    <ProModal
      :drag="true"
      :destroyOnClose="true"
      style="top: 0px"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByBatchDel"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnBatchDelModalOk"
      @cancel="fnBatchDelModalCancel"
    >
      <a-form
        name="modalStateBatchDelFrom"
        layout="horizontal"
        :label-col="{ span: 8 }"
        :labelWrap="true"
      >
        <a-row>
          <a-col :lg="24" :md="24" :xs="24">
            <a-form-item
              :label="t('views.neUser.sub.startIMSI')"
              name="imsi"
              v-bind="modalStateBatchDelFrom.validateInfos.imsi"
            >
              <a-input
                v-model:value="modalState.BatchDelForm.imsi"
                allow-clear
                :maxlength="15"
              >
                <template #prefix>
                  <a-tooltip placement="topLeft">
                    <template #title>
                      {{ t('views.neUser.sub.imsiTip') }}<br />
                      {{ t('views.neUser.sub.imsiTip1') }}<br />
                      {{ t('views.neUser.sub.imsiTip2') }}<br />
                      {{ t('views.neUser.sub.imsiTip3') }}
                    </template>
                    <InfoCircleOutlined style="opacity: 0.45; color: inherit" />
                  </a-tooltip>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="24" :md="24" :xs="24">
            <a-form-item
              :label="t('views.neUser.sub.numDel')"
              name="num"
              v-bind="modalStateBatchDelFrom.validateInfos.num"
            >
              <a-input-number
                v-model:value="modalState.BatchDelForm.num"
                style="width: 100%"
                :min="1"
                :max="500"
                :maxlength="3"
                placeholder="<=500"
              ></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ProModal>

    <!-- 上传导入表格数据文件框 -->
    <UploadModal
      :title="uploadImportState.title"
      :loading="uploadImportState.loading"
      @upload="fnModalUploadImportUpload"
      @close="fnModalUploadImportClose"
      v-model:open="uploadImportState.open"
      :ext="['.txt']"
      :size="10"
    >
      <template #default>
        <a-row justify="space-between" align="middle">
          <a-col :span="12"> </a-col>
          <a-col>
            <a-button
              type="link"
              :title="t('views.neData.common.importTemplate')"
              @click.prevent="fnModalDownloadImportTemplate"
            >
              {{ t('views.neData.common.importTemplate') }}
            </a-button>
          </a-col>
        </a-row>
        <a-alert
          :message="uploadImportState.msg"
          :type="uploadImportState.hasFail ? 'warning' : 'info'"
          v-show="uploadImportState.msg.length > 0"
        >
          <template #action>
            <a-button
              size="small"
              type="link"
              danger
              @click="fnModalUploadImportFailReason"
              v-if="uploadImportState.hasFail"
            >
              {{ t('views.neUser.auth.importFail') }}
            </a-button>
          </template>
        </a-alert>
      </template>
    </UploadModal>
  </PageContainer>
</template>

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