<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
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 TableColumnsDnd from '@/components/TableColumnsDnd/index.vue';
import {
  addUDMSub,
  batchAddUDMSub,
  batchDelUDMSub,
  delUDMSub,
  exportUDMSub,
  getUDMSub,
  importUDMSub,
  listUDMSub,
  resetUDMSub,
  updateUDMSub,
} from '@/api/neData/udm_sub';
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 { TENANTADMIN_ROLE_KEY } from '@/constants/admin-constants';

const { t } = useI18n();

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

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

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    imsi: '',
    msisdn: '',
    imsiMatch: 'fuzzy',
    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: 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 Data',
    dataIndex: 'smData',
    align: 'left',
    resizable: true,
    width: 500,
    minWidth: 150,
    maxWidth: 500,
  },
];

/**表格字段列排序 */
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 = {
  /**详情框是否显示 */
  visibleByView: boolean;
  /**新增框或修改框是否显示 */
  visibleByEdit: boolean;
  /**批量新增否显示 */
  visibleByBatch: boolean;
  /**批量删除否显示 */
  visibleByBatchDel: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**表单数据 */
  BatchForm: Record<string, any>;
  /**表单数据 */
  BatchDelForm: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**更新加载数据按钮 loading */
  loadDataLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByView: false,
  visibleByEdit: false,
  visibleByBatch: false,
  visibleByBatchDel: false,
  title: 'UDM签约用户',
  from: {
    id: '',
    msisdn: '',
    imsi: '',
    ambr: 'def_ambr',
    nssai: 'def_nssai',
    rat: '0',
    arfb: 'def_arfb',
    sar: 'def_sar',
    cn: '3',
    smData: '',
    smfSel: 'def_snssai',
    epsDat: '',
    neId: '',
    epsFlag: '1',
    epsOdb: [2],
    hplmnOdb: [3, 4],
    ard: [1, 7],
    epstpl: 'def_eps',
    contextId: '1',
    apnContext: [1, 2, 0, 0, 0, 0],
    staticIp: '-',
    rfsp: 1,
    ueType: 1,
  },
  BatchForm: {
    num: '',
    msisdn: '',
    imsi: '',
    ambr: 'def_ambr',
    nssai: 'def_nssai',
    rat: '0',
    arfb: 'def_arfb',
    sar: 'def_sar',
    cn: '3',
    smData: '',
    smfSel: 'def_snssai',
    epsDat: '',
    neId: '',
    epsFlag: '1',
    epsOdb: [2],
    hplmnOdb: [3, 4],
    ard: [1, 7],
    epstpl: 'def_eps',
    contextId: '1',
    apnContext: [1, 2, 0, 0, 0, 0],
    staticIp: '-',
    rfsp: 1,
    ueType: 1,
  },
  BatchDelForm: {
    num: '',
    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(batchFlag?: number) {
  if (batchFlag) {
    modalStateBatchFrom.resetFields(); //重置表单
    modalState.title =
      t('views.neUser.sub.batchAddText') + t('views.neUser.sub.subInfo');
    modalState.visibleByBatch = true;
  } else {
    modalStateBatchFrom.resetFields(); //重置表单
    modalState.title =
      t('views.neUser.sub.batchDelText') + t('views.neUser.sub.subInfo');
    modalState.visibleByBatchDel = true;
  }
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByEdit(imsi?: string) {
  if (!imsi) {
    modalStateFrom.resetFields();
    modalState.title = t('common.addText') + t('views.neUser.sub.subInfo');
    modalState.visibleByEdit = 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.visibleByEdit = true;
        } else {
          message.error(t('common.getInfoFail'), 2);
        }
      })
      .finally(() => {
        hide();
        modalState.confirmLoading = false;
      });
  }
}

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    imsi: [{ required: true, message: 'IMSI' + t('common.unableNull') }],
    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(':')) {
              //IPV4 没有/ 也没有：
              smStaticIpArr.push(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;
  }
  let validateNames = ['imsi', 'msisdn', 'staticIp'];

  if (from.id === '') {
    validateNames.push('smData');
  }
  modalStateFrom
    .validate(validateNames)
    .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.neId = queryParams.neId || '-';
      const result = from.id ? updateUDMSub(from) : addUDMSub(from);
      const hide = message.loading(t('common.loading'), 0);
      result
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 3,
            });
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          fnModalCancel();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

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

/**
 * 对话框弹出 批量新增操作确认执行函数
 * 进行表达规则校验
 */
function fnBatchModalOk() {
  const from = Object.assign({}, toRaw(modalState.BatchForm));
  try {
    from.smData = transformData(bigRows.value).join(';');
  } catch (error: any) {
    console.error(error.message);
    return false;
  }
  modalStateBatchFrom
    .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('');

      const hide = message.loading(t('common.loading'), 0);
      from.neId = queryParams.neId || '-';
      batchAddUDMSub(from, from.num)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 3,
            });
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          fnBatchModalCancel();
          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 hide = message.loading(t('common.loading'), 0);
      const neId = queryParams.neId || '-';
      batchDelUDMSub(neId, from.imsi, from.num)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 3,
            });
            modalState.visibleByBatchDel = false;
            modalStateBatchDelFrom.resetFields();
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

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

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

/**
 * 批量删除对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnBatchDelModalCancel() {
  modalState.visibleByBatchDel = false;
  modalState.visibleByView = 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;
  const imsiMatchRule: any = {
    prefix: queryParams.imsi ? `${queryParams.imsi}%` : '',
    fuzzy: queryParams.imsi ? `%${queryParams.imsi}%` : '',
  };
  const realImsi = imsiMatchRule[queryParams.imsiMatch] || '';
  if (!neID) return;
  const key = 'exportSub';
  message.loading({ content: t('common.loading'), key });
  Object.assign({ type: type }, queryParams);
  exportUDMSub({
    ...queryParams,
    imsi: realImsi,
    type: type,
  }).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      message.success({
        content: t('common.msgSuccess', { msg: t('common.export') }),
        key,
        duration: 2,
      });
      saveAs(res.data, `UDMSub_${Date.now()}.${type}`);
    } else {
      message.error({
        content: `${res.msg}`,
        key,
        duration: 2,
      });
    }
  });
}

/**重新加载数据 */
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;
      notification.success({
        message: t('views.neUser.sub.loadData'),
        description: t('views.neUser.sub.loadDataTip', { num }),
        duration: num < 10_0000 ? 10 : 30,
      });
      // 延迟20s后关闭loading刷新列表
      setTimeout(
        () => {
          modalState.loadDataLoading = false;
          tableState.loading = false; // 表格loading
          fnQueryReset();
        },
        num < 10_0000 ? 10_000 : 30_000
      );
    } else {
      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;
  }

  const imsiMatchRule: any = {
    prefix: queryParams.imsi ? `${queryParams.imsi}%` : '',
    fuzzy: queryParams.imsi ? `%${queryParams.imsi}%` : '',
  };

  const toBack: any = {
    imsi: imsiMatchRule[queryParams.imsiMatch] || '',
    msisdn: queryParams.msisdn,
    sortField: queryParams.sortField,
    sortOrder: queryParams.sortOrder,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  };

  listUDMSub({
    ...queryParams,
    ismi: imsiMatchRule[queryParams.imsiMatch],
  }).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }

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

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

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

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

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

/**对话框表格信息导入上传 */
function fnModalUploadImportUpload(file: File) {
  const neID = queryParams.neId;
  if (!neID) {
    return Promise.reject('Unknown network element');
  }
  let formData = new FormData();
  formData.append('file', file);
  formData.append('neId', neID);
  const hide = message.loading(t('common.loading'), 0);
  uploadImportState.loading = true;
  importUDMSub(formData)
    .then(res => {
      uploadImportState.msg = res.msg;
    })
    .catch((err: { code: number; msg: string }) => {
      message.error(` ${err.msg}`);
    })
    .finally(() => {
      hide();
      uploadImportState.loading = false;
    });
}

onMounted(() => {
  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
        if (res.data.length > 0) {
          let arr: Record<string, any>[] = [];
          res.data.forEach(i => {
            if (i.neType === 'UDM') {
              arr.push({ value: i.neId, label: i.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
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
      v-show="tableState.seached"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24" v-roles:has="[TENANTADMIN_ROLE_KEY]">
            <a-form-item :label="t('views.neUser.sub.neType')" name="neId ">
              <a-select
                v-model:value="queryParams.neId"
                :options="neOtions"
                :placeholder="t('common.selectPlease')"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :xs="24">
            <a-form-item label="IMSI" name="imsi">
              <a-input-group compact>
                <a-input
                  v-model:value="queryParams.imsi"
                  allow-clear
                  :maxlength="15"
                  style="width: 70%"
                  :placeholder="t('common.inputPlease')"
                ></a-input>
                <a-select
                  :label="t('views.neUser.sub.imsiMode')"
                  style="width: 30%"
                  v-model:value="queryParams.imsiMatch"
                  :options="[
                    { label: t('views.neUser.sub.fuzzyMatch'), value: 'fuzzy' },
                    {
                      label: t('views.neUser.sub.prefixMatch'),
                      value: 'prefix',
                    },
                  ]"
                ></a-select>
              </a-input-group>
            </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></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()"
            v-perms:has="['tenant:subs:add']"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            {{ t('common.addText') }}
          </a-button>

          <a-button
            type="primary"
            @click.prevent="fnModalVisibleByBatch(1)"
            v-perms:has="['tenant:subs:batchAdd']"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            {{ t('views.neUser.auth.batchAddText') }}
          </a-button>

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

          <a-button
            type="primary"
            danger
            ghost
            @click.prevent="fnModalVisibleByBatch(0)"
            v-perms:has="['tenant:subs:batchDel']"
          >
            <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"
              v-perms:has="['tenant:subs:load']"
            >
              <template #icon>
                <SyncOutlined />
              </template>
              {{ t('views.neUser.sub.loadData') }}
            </a-button>
          </a-popconfirm>

          <a-button
            type="dashed"
            @click.prevent="fnModalUploadImportOpen"
            v-perms:has="['tenant:subs:import']"
          >
            <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')"
            :show-cancel="false"
            cancel-text="CSV"
            @cancel="fnExportList('csv')"
          > -->
          <a-popconfirm
            :title="t('views.neUser.sub.exportConfirm')"
            placement="topRight"
            ok-text="TXT"
            ok-type="default"
            @confirm="fnExportList('txt')"
          >
            <a-button type="dashed" v-perms:has="['tenant:subs:export']">
              <template #icon>
                <ExportOutlined />
              </template>
              {{ t('views.neUser.sub.export') }}
            </a-button>
          </a-popconfirm>

          <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"
              v-perms:has="['tenant:subs:checkExport']"
            >
              <template #icon><ExportOutlined /></template>
              {{ t('views.neUser.sub.checkExport') }}
            </a-button>
          </a-popconfirm>
        </a-flex>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <div class="button-container">
          <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>
        </div>
      </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,
        }"
      >
      </a-table>
    </a-card>
  </PageContainer>
</template>

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