<template>
  <ArtTableFullScreen>
    <div class="card-detail-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 数据视图组件 -->
        <ArtDataViewer
          ref="dataViewerRef"
          :data="tableData"
          :loading="loading"
          :table-columns="columns"
          :descriptions-fields="descriptionsFields"
          :descriptions-columns="2"
          :pagination="pagination"
          :label-width="'120px'"
          :field-columns="columnChecks"
          :show-card-actions="true"
          :show-card-selection="true"
          :default-view="currentView"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @view-change="handleViewChange"
        >
          <template #header-left>
            <ElButton @click="exportExcel">导出excel</ElButton>
            <ElButton @click="cardDistribution">网卡分销</ElButton>
            <ElButton @click="batchRecharge">批量充值</ElButton>
            <ElButton @click="cardRecycle">网卡回收</ElButton>
            <ElButton @click="batchDownload">批量下载</ElButton>
            <ElButton @click="changePackage">变更套餐</ElButton>
          </template>

          <template #header-right>
            <ArtTableHeader
              :columnList="columnOptions"
              v-model:columns="columnChecks"
              v-model:currentView="currentView"
              @refresh="handleRefresh"
              @viewChange="handleViewChange"
              :show-title="false"
              :show-view-toggle="true"
            />
          </template>

          <template #card-actions="{ item }">
            <ElButton type="primary" size="small" @click="handleCardOperation(item)">
              卡务操作
            </ElButton>
            <ElButton type="success" size="small" @click="downloadCard(item)"> 下载 </ElButton>
            <ElButton type="danger" size="small" @click="deleteCard(item)"> 删除 </ElButton>
          </template>
        </ArtDataViewer>

        <!-- 右键菜单 -->
        <ArtMenuRight
          ref="contextMenuRef"
          :menu-items="contextMenuItems"
          @select="handleContextMenuSelect"
        />
      </ElCard>

      <!-- 网卡分销弹框 -->
      <CardOperationDialog
        v-model:visible="distributionDialogVisible"
        title="网卡分销"
        select-label="代理商"
        select-placeholder="请搜索并选择代理商"
        :selected-cards="selectedRows"
        :remote-search="searchAgents"
        @confirm="handleDistributionConfirm"
        @close="handleDialogClose"
      />

      <!-- 批量充值弹框 -->
      <CardOperationDialog
        v-model:visible="rechargeDialogVisible"
        title="批量充值"
        select-label="套餐"
        select-placeholder="请搜索并选择套餐"
        :show-amount="true"
        :selected-cards="selectedRows"
        :remote-search="searchPackages"
        @confirm="handleRechargeConfirm"
        @close="handleDialogClose"
      />

      <!-- 套餐变更弹框 -->
      <CardOperationDialog
        v-model:visible="packageChangeDialogVisible"
        title="套餐变更"
        select-label="新套餐"
        select-placeholder="请搜索并选择要变更的套餐"
        :selected-cards="selectedRows"
        :remote-search="searchPackages"
        @confirm="handlePackageChangeConfirm"
        @close="handleDialogClose"
      />
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElTag, ElMessage, ElMessageBox, ElButton } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { SearchChangeParams, SearchFormItem } from '@/types'
  import { RoutesAlias } from '@/router/routesAlias'
  import ArtDataViewer from '@/components/core/views/ArtDataViewer.vue'
  import CardOperationDialog from '@/components/business/CardOperationDialog.vue'
  import ArtMenuRight from '@/components/core/others/ArtMenuRight.vue'
  import type { MenuItemType } from '@/components/core/others/ArtMenuRight.vue'

  defineOptions({ name: 'CardDetail' })

  const loading = ref(false)
  const router = useRouter()

  // 当前视图模式
  const currentView = ref('table')

  // 弹框状态
  const distributionDialogVisible = ref(false)
  const rechargeDialogVisible = ref(false)
  const packageChangeDialogVisible = ref(false)

  // 右键菜单
  const contextMenuRef = ref()
  const currentContextRow = ref<any>(null)

  // 右键菜单配置
  const contextMenuItems: MenuItemType[] = [
    {
      key: 'cardOperation',
      label: '卡务操作'
    },
    {
      key: 'download',
      label: '下载'
    },
    {
      key: 'delete',
      label: '删除',
      showLine: true
    }
  ]

  // 定义表单搜索初始值
  const initialSearchState = {
    cardPackage: '',
    isDistributed: '',
    cardStatus: '',
    cardCompany: '',
    importDateRange: '',
    operatorName: '',
    distributor: '',
    importBatch: '',
    iccidRange: '',
    iccid: '',
    accessNumber: '',
    imei: '',
    virtualNumber: '',
    virtualNumberRange: '',
    isRoaming: ''
  }

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表格数据
  const tableData = ref<any[]>([])

  // 表格实例引用
  const tableRef = ref()

  // 数据视图组件引用
  const dataViewerRef = ref()

  // 选中的行数据
  const selectedRows = ref<any[]>([])

  // 模拟数据
  const mockData = [
    {
      id: 1,
      iccid: '89860621370079892035',
      accessNumber: '1440012345678',
      virtualNumber: '10655001234',
      imei: '860123456789012',
      walletBalance: '50.00',
      cardCompany: '联通2',
      operatorName: '中国联通',
      importTime: '2024-10-15 14:30:25',
      importBatch: '650',
      expireTime: '2025-12-31',
      packageName: '随意联畅玩年卡套餐（12个月）',
      distributorName: '张丽丽',
      cardStatus: '正常',
      isRoaming: '否'
    },
    {
      id: 2,
      iccid: '89860621370079892036',
      accessNumber: '1440012345679',
      virtualNumber: '10655001235',
      imei: '860123456789013',
      walletBalance: '25.50',
      cardCompany: '联通36',
      operatorName: '中国联通',
      importTime: '2024-10-10 13:45:12',
      importBatch: '649',
      expireTime: '2025-11-30',
      packageName: '如意包年3G流量包',
      distributorName: '王小明',
      cardStatus: '正常',
      isRoaming: '否'
    },
    {
      id: 3,
      iccid: '89860621370079892037',
      accessNumber: '1440012345680',
      virtualNumber: '10655001236',
      imei: '860123456789014',
      walletBalance: '75.00',
      cardCompany: 'SXKJ-NB',
      operatorName: 'GS移动',
      importTime: '2024-09-20 16:20:08',
      importBatch: '648',
      expireTime: '2025-10-31',
      packageName: 'Y-NB专享套餐',
      distributorName: 'HNSXKJ',
      cardStatus: '待激活',
      isRoaming: '是'
    },
    {
      id: 4,
      iccid: '89860621370079892038',
      accessNumber: '1440012345681',
      virtualNumber: '10655001237',
      imei: '860123456789015',
      walletBalance: '100.00',
      cardCompany: '联通1-1',
      operatorName: '中国联通',
      importTime: '2024-09-05 10:15:30',
      importBatch: '647',
      expireTime: '2026-01-31',
      packageName: '100G全国流量月卡套餐',
      distributorName: '未分销',
      cardStatus: '正常',
      isRoaming: '否'
    },
    {
      id: 5,
      iccid: '89860621370079892039',
      accessNumber: '1440012345682',
      virtualNumber: '10655001238',
      imei: '860123456789016',
      walletBalance: '0.00',
      cardCompany: '广电4',
      operatorName: 'GDWL',
      importTime: '2024-08-25 15:44:31',
      importBatch: '644',
      expireTime: '2025-08-31',
      packageName: '广电飞悦卡无预存50G（30天）',
      distributorName: '孔丽娟',
      cardStatus: '停机',
      isRoaming: '否'
    }
  ]

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    pagination.currentPage = 1
    getCardDetailList()
  }

  // 搜索处理
  const handleSearch = () => {
    console.log('搜索参数:', formFilters)
    pagination.currentPage = 1
    getCardDetailList()
  }

  // 表单项变更处理
  const handleFormChange = (params: SearchChangeParams): void => {
    console.log('表单项变更:', params)
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '网卡套餐',
      prop: 'cardPackage',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入网卡套餐'
      },
      onChange: handleFormChange
    },
    {
      label: '是否分销',
      prop: 'isDistributed',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '是', value: 'yes' },
        { label: '否', value: 'no' }
      ],
      onChange: handleFormChange
    },
    {
      label: '卡号状态',
      prop: 'cardStatus',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '正常', value: 'normal' },
        { label: '待激活', value: 'pending' },
        { label: '停机', value: 'suspended' },
        { label: '注销', value: 'cancelled' }
      ],
      onChange: handleFormChange
    },
    {
      label: '开卡公司',
      prop: 'cardCompany',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择'
      },
      options: () => [
        { label: '联通2', value: 'unicom2' },
        { label: '联通36', value: 'unicom36' },
        { label: 'SXKJ-NB', value: 'sxkj_nb' },
        { label: '联通1-1', value: 'unicom1_1' },
        { label: '联通8', value: 'unicom8' }
      ],
      onChange: handleFormChange
    },
    {
      label: '导入时间',
      prop: 'importDateRange',
      type: 'daterange',
      config: {
        type: 'daterange',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
      },
      onChange: handleFormChange
    },
    {
      label: '运营商名',
      prop: 'operatorName',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '中国移动', value: 'mobile' },
        { label: '中国联通', value: 'unicom' },
        { label: '中国电信', value: 'telecom' },
        { label: 'GS移动', value: 'gs_mobile' },
        { label: 'DC物联', value: 'dc_iot' },
        { label: 'GDWL', value: 'gdwl' }
      ],
      onChange: handleFormChange
    },
    {
      label: '卡分销商',
      prop: 'distributor',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入分销商'
      },
      onChange: handleFormChange
    },
    {
      label: '导入批次',
      prop: 'importBatch',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入导入批次'
      },
      onChange: handleFormChange
    },
    {
      label: '网卡号段',
      prop: 'iccidRange',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入网卡号段，如：8986001-8986999'
      },
      onChange: handleFormChange
    },
    {
      label: '网卡卡号',
      prop: 'iccid',
      type: 'input',
      config: {
        clearable: true,
        placeholder: 'ICCID号（精确）'
      },
      onChange: handleFormChange
    },
    {
      label: '卡接入号',
      prop: 'accessNumber',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '接入号（精确）'
      },
      onChange: handleFormChange
    },
    {
      label: 'IMEI',
      prop: 'imei',
      type: 'input',
      config: {
        clearable: true,
        placeholder: 'IMEI'
      },
      onChange: handleFormChange
    },
    {
      label: '虚拟号',
      prop: 'virtualNumber',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '虚拟号'
      },
      onChange: handleFormChange
    },
    {
      label: '虚拟号段',
      prop: 'virtualNumberRange',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入虚拟号段，如：10655001-10655999'
      },
      onChange: handleFormChange
    },
    {
      label: '是否窜卡',
      prop: 'isRoaming',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '是', value: 'yes' },
        { label: '否', value: 'no' }
      ],
      onChange: handleFormChange
    }
  ]

  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: 'ICCID号', prop: 'iccid' },
    { label: '接入号码', prop: 'accessNumber' },
    { label: '虚拟号', prop: 'virtualNumber' },
    { label: 'IMEI', prop: 'imei' },
    { label: '钱包余额', prop: 'walletBalance' },
    { label: '开卡公司', prop: 'cardCompany' },
    { label: '运营商名称', prop: 'operatorName' },
    { label: '导入时间', prop: 'importTime' },
    { label: '导入批次', prop: 'importBatch' },
    { label: '到期时间', prop: 'expireTime' },
    { label: '套餐', prop: 'packageName' },
    { label: '分销商姓名', prop: 'distributorName' },
    { label: '卡状态', prop: 'cardStatus' },
    { label: '是否窜卡', prop: 'isRoaming' },
    { label: '操作', prop: 'operation' }
  ]

  // 描述字段配置
  const descriptionsFields = [
    {
      prop: 'iccid',
      label: 'ICCID号',
      span: 2,
      formatter: (row: any) => {
        return `<span class="iccid-link" style="color: var(--el-color-primary); cursor: pointer; text-decoration: underline;" data-iccid="${row.iccid}">${row.iccid}</span>`
      }
    },
    { prop: 'accessNumber', label: '接入号码' },
    { prop: 'virtualNumber', label: '虚拟号' },
    { prop: 'imei', label: 'IMEI', span: 2 },
    {
      prop: 'walletBalance',
      label: '钱包余额',
      formatter: (row: any) => `¥${row.walletBalance}`
    },
    { prop: 'cardCompany', label: '开卡公司' },
    { prop: 'operatorName', label: '运营商名称' },
    { prop: 'importTime', label: '导入时间', span: 2 },
    { prop: 'importBatch', label: '导入批次' },
    { prop: 'expireTime', label: '到期时间' },
    { prop: 'packageName', label: '套餐', span: 2 },
    { prop: 'distributorName', label: '分销商姓名' },
    {
      prop: 'cardStatus',
      label: '卡状态',
      formatter: (row: any) => {
        const type = getCardStatusType(row.cardStatus)
        return `<el-tag type="${type}" size="small">${row.cardStatus}</el-tag>`
      }
    },
    {
      prop: 'isRoaming',
      label: '是否窜卡',
      formatter: (row: any) => {
        const type = row.isRoaming === '是' ? 'danger' : 'success'
        return `<el-tag type="${type}" size="small">${row.isRoaming}</el-tag>`
      }
    }
  ]

  // 获取卡状态标签类型
  const getCardStatusType = (status: string) => {
    switch (status) {
      case '正常':
        return 'success'
      case '待激活':
        return 'warning'
      case '停机':
      case '注销':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 处理卡务操作
  const handleCardOperation = (row: any) => {
    // 跳转到单卡信息页面进行卡务操作
    navigateToSingleCard(row.iccid)
  }

  // 导出Excel
  const exportExcel = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要导出的数据')
      return
    }
    ElMessage.success(`导出 ${selectedRows.value.length} 条Excel记录`)
  }

  // 网卡分销
  const cardDistribution = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要分销的网卡')
      return
    }
    distributionDialogVisible.value = true
  }

  // 批量充值
  const batchRecharge = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要充值的网卡')
      return
    }
    rechargeDialogVisible.value = true
  }

  // 网卡回收
  const cardRecycle = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要回收的网卡')
      return
    }

    ElMessageBox.confirm(
      `确定要回收所选的 ${selectedRows.value.length} 张网卡吗？回收后将无法恢复。`,
      '网卡回收确认',
      {
        confirmButtonText: '确认回收',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
      .then(() => {
        handleCardRecycle()
      })
      .catch(() => {
        ElMessage.info('已取消回收操作')
      })
  }

  // 批量下载
  const batchDownload = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要下载的网卡')
      return
    }
    ElMessage.info(`批量下载 ${selectedRows.value.length} 张网卡信息`)
  }

  // 变更套餐
  const changePackage = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要变更套餐的网卡')
      return
    }
    packageChangeDialogVisible.value = true
  }

  // 下载单卡信息
  const downloadCard = (row: any) => {
    ElMessage.success(`下载 ${row.iccid} 的卡片信息`)
  }

  // 删除单卡
  const deleteCard = (row: any) => {
    ElMessageBox.confirm(`确定要删除ICCID为 ${row.iccid} 的网卡吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 这里应该调用删除API
        ElMessage.success(`已删除 ${row.iccid}`)
        // 刷新列表
        getCardDetailList()
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'selection' },
    {
      prop: 'iccid',
      label: 'ICCID号',
      minWidth: 180,
      formatter: (row: any) => {
        return h(
          'span',
          {
            class: 'iccid-link',
            style: {
              color: 'var(--el-color-primary)',
              cursor: 'pointer',
              textDecoration: 'underline'
            },
            onClick: () => navigateToSingleCard(row.iccid)
          },
          row.iccid
        )
      }
    },
    {
      prop: 'accessNumber',
      label: '接入号码',
      width: 120
    },
    {
      prop: 'virtualNumber',
      label: '虚拟号',
      width: 120
    },
    {
      prop: 'imei',
      label: 'IMEI',
      width: 140
    },
    {
      prop: 'walletBalance',
      label: '钱包余额',
      width: 100,
      formatter: (row) => `¥${row.walletBalance}`
    },
    {
      prop: 'cardCompany',
      label: '开卡公司',
      width: 120
    },
    {
      prop: 'operatorName',
      label: '运营商名称',
      width: 100
    },
    {
      prop: 'importTime',
      label: '导入时间',
      width: 150
    },
    {
      prop: 'importBatch',
      label: '导入批次',
      width: 100
    },
    {
      prop: 'expireTime',
      label: '到期时间',
      width: 120
    },
    {
      prop: 'packageName',
      label: '套餐',
      minWidth: 200
    },
    {
      prop: 'distributorName',
      label: '分销商姓名',
      width: 120
    },
    {
      prop: 'cardStatus',
      label: '卡状态',
      width: 100,
      formatter: (row) => {
        return h(ElTag, { type: getCardStatusType(row.cardStatus) }, () => row.cardStatus)
      }
    },
    {
      prop: 'isRoaming',
      label: '是否窜卡',
      width: 100,
      formatter: (row) => {
        return h(
          ElTag,
          { type: row.isRoaming === '是' ? 'danger' : 'success' },
          () => row.isRoaming
        )
      }
    },
    {
      prop: 'operation',
      label: '操作',
      width: 120,
      formatter: (row: any) => {
        return h(
          'div',
          {
            style:
              'display: flex; justify-content: center; align-items: center; gap: 4px; cursor: context-menu; color: var(--el-color-primary);',
            onContextmenu: (e: MouseEvent) => {
              e.preventDefault()
              e.stopPropagation()
              handleOperationClick(row, e)
            }
          },
          [
            h('i', {
              class: 'iconfont-sys',
              innerHTML: '&#xe79c;',
              style: 'font-size: 16px;'
            }),
            h('span', { style: 'font-size: 14px;' }, '更多操作')
          ]
        )
      }
    }
  ])

  onMounted(() => {
    getCardDetailList()

    // 添加全局点击事件监听器，用于处理卡片视图中的ICCID点击
    const handleGlobalClick = (event: Event) => {
      const target = event.target as HTMLElement
      if (target && target.classList.contains('iccid-link')) {
        const iccid = target.getAttribute('data-iccid')
        if (iccid) {
          navigateToSingleCard(iccid)
        }
      }
    }

    document.addEventListener('click', handleGlobalClick)

    // 在组件卸载时移除事件监听器
    onUnmounted(() => {
      document.removeEventListener('click', handleGlobalClick)
    })
  })

  // 获取网卡明细列表
  const getCardDetailList = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 500))

      const startIndex = (pagination.currentPage - 1) * pagination.pageSize
      const endIndex = startIndex + pagination.pageSize
      const paginatedData = mockData.slice(startIndex, endIndex)

      tableData.value = paginatedData
      pagination.total = mockData.length
      loading.value = false
    } catch (error) {
      console.error('获取网卡明细列表失败:', error)
      loading.value = false
    }
  }

  const handleRefresh = () => {
    getCardDetailList()
  }

  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getCardDetailList()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getCardDetailList()
  }

  // 处理视图切换
  const handleViewChange = (view: string) => {
    console.log('视图切换到:', view)
    // 可以在这里添加视图切换的额外逻辑，比如保存用户偏好
  }

  // 跳转到单卡信息页面
  const navigateToSingleCard = (iccid: string) => {
    // 使用路由跳转到单卡信息页面，并传递 ICCID 参数
    router.push({
      path: '/asset-management/single-card',
      query: { iccid }
    })
  }

  // 远程搜索代理商
  const searchAgents = async (query: string) => {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 300))

    // 模拟代理商数据（扩展到更多数据以展示分页效果）
    const allAgents = [
      { label: '张丽丽代理商', value: 'agent_001' },
      { label: '王小明代理商', value: 'agent_002' },
      { label: 'HNSXKJ代理商', value: 'agent_003' },
      { label: '孔丽娟代理商', value: 'agent_004' },
      { label: '李四代理商', value: 'agent_005' },
      { label: '赵六代理商', value: 'agent_006' },
      { label: '刘备代理商', value: 'agent_007' },
      { label: '关羽代理商', value: 'agent_008' },
      { label: '张飞代理商', value: 'agent_009' },
      { label: '赵云代理商', value: 'agent_010' },
      { label: '黄忠代理商', value: 'agent_011' },
      { label: '马超代理商', value: 'agent_012' },
      { label: '诸葛亮代理商', value: 'agent_013' },
      { label: '周瑜代理商', value: 'agent_014' },
      { label: '孙权代理商', value: 'agent_015' }
    ]

    // 根据查询条件过滤
    let filteredAgents = allAgents
    if (query) {
      filteredAgents = allAgents.filter((agent) =>
        agent.label.toLowerCase().includes(query.toLowerCase())
      )
    }

    // 返回前10条数据
    return filteredAgents.slice(0, 10)
  }

  // 远程搜索套餐
  const searchPackages = async (query: string) => {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 300))

    // 模拟套餐数据（扩展到更多数据以展示分页效果）
    const allPackages = [
      { label: '随意联畅玩年卡套餐（12个月）', value: 'package_001' },
      { label: '如意包年3G流量包', value: 'package_002' },
      { label: 'Y-NB专享套餐', value: 'package_003' },
      { label: '100G全国流量月卡套餐', value: 'package_004' },
      { label: '广电飞悦卡无预存50G（30天）', value: 'package_005' },
      { label: '移动畅享套餐50G', value: 'package_006' },
      { label: '联通大王卡19元', value: 'package_007' },
      { label: '电信星卡29元', value: 'package_008' },
      { label: '移动无限流量卡99元', value: 'package_009' },
      { label: '联通冰淇淋套餐199元', value: 'package_010' },
      { label: '电信天翼云卡59元', value: 'package_011' },
      { label: '移动神州行卡39元', value: 'package_012' },
      { label: '联通腾讯王卡免流', value: 'package_013' },
      { label: '电信达量降速套餐', value: 'package_014' },
      { label: '广电5G畅享套餐', value: 'package_015' }
    ]

    // 根据查询条件过滤
    let filteredPackages = allPackages
    if (query) {
      filteredPackages = allPackages.filter((pkg) =>
        pkg.label.toLowerCase().includes(query.toLowerCase())
      )
    }

    // 返回前10条数据
    return filteredPackages.slice(0, 10)
  }

  // 处理网卡分销确认
  const handleDistributionConfirm = async (data: any) => {
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      ElMessage.success(`成功将 ${data.selectedCards.length} 张网卡分销给代理商`)
      distributionDialogVisible.value = false

      // 刷新列表
      getCardDetailList()
    } catch (error) {
      ElMessage.error('分销操作失败，请重试')
    }
  }

  // 处理批量充值确认
  const handleRechargeConfirm = async (data: any) => {
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      ElMessage.success(`成功为 ${data.selectedCards.length} 张网卡充值 ${data.amount} 元`)
      rechargeDialogVisible.value = false

      // 刷新列表
      getCardDetailList()
    } catch (error) {
      ElMessage.error('充值操作失败，请重试')
    }
  }

  // 处理套餐变更确认
  const handlePackageChangeConfirm = async (data: any) => {
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      ElMessage.success(`成功为 ${data.selectedCards.length} 张网卡变更套餐`)
      packageChangeDialogVisible.value = false

      // 刷新列表
      getCardDetailList()
    } catch (error) {
      ElMessage.error('套餐变更失败，请重试')
    }
  }

  // 处理网卡回收
  const handleCardRecycle = async () => {
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      ElMessage.success(`成功回收 ${selectedRows.value.length} 张网卡`)

      // 从列表中移除回收的网卡
      const recycledIds = selectedRows.value.map((row) => row.id)
      tableData.value = tableData.value.filter((item) => !recycledIds.includes(item.id))
      selectedRows.value = []
    } catch (error) {
      ElMessage.error('回收操作失败，请重试')
    }
  }

  // 处理弹框关闭
  const handleDialogClose = () => {
    // 可以在这里添加额外的关闭逻辑
  }

  // 处理操作列点击
  const handleOperationClick = (row: any, event: MouseEvent) => {
    currentContextRow.value = row
    contextMenuRef.value?.show(event)
  }

  // 处理右键菜单选择
  const handleContextMenuSelect = (item: MenuItemType) => {
    if (!currentContextRow.value) return

    switch (item.key) {
      case 'cardOperation':
        handleCardOperation(currentContextRow.value)
        break
      case 'download':
        downloadCard(currentContextRow.value)
        break
      case 'delete':
        deleteCard(currentContextRow.value)
        break
    }
  }
</script>

<style lang="scss" scoped>
  .card-detail-page {
    // 可以添加特定样式
  }

  :deep(.operation-buttons) {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;

    .el-button {
      margin: 0;
    }
  }
</style>
