<template>
  <ArtTableFullScreen>
    <div class="enterprise-cards-page" id="table-full-screen">
      <!-- 企业信息卡片 -->
      <ElCard shadow="never" class="enterprise-info-card">
        <template #header>
          <div class="card-header">
            <span>企业信息</span>
            <ElButton @click="goBack">返回</ElButton>
          </div>
        </template>
        <ElDescriptions :column="3" border v-if="enterpriseInfo">
          <ElDescriptionsItem label="企业名称">{{
            enterpriseInfo.enterprise_name
          }}</ElDescriptionsItem>
          <ElDescriptionsItem label="企业编号">{{
            enterpriseInfo.enterprise_code
          }}</ElDescriptionsItem>
          <ElDescriptionsItem label="联系人">{{ enterpriseInfo.contact_name }}</ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton
              type="primary"
              @click="showAllocateDialog"
              v-permission="'enterprise_cards:allocate'"
            >
              授权卡
            </ElButton>
            <ElButton
              type="warning"
              :disabled="selectedCards.length === 0"
              @click="showRecallDialog"
              v-permission="'enterprise_cards:batch_recall'"
            >
              批量回收
            </ElButton>
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="cardList"
          :currentPage="pagination.page"
          :pageSize="pagination.pageSize"
          :total="pagination.total"
          :marginTop="10"
          :row-class-name="getRowClassName"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
          @row-contextmenu="handleRowContextMenu"
          @cell-mouse-enter="handleCellMouseEnter"
          @cell-mouse-leave="handleCellMouseLeave"
        >
          <template #default>
            <ElTableColumn type="selection" width="55" />
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>

        <!-- 鼠标悬浮提示 -->
        <TableContextMenuHint :visible="showContextMenuHint" :position="hintPosition" />

        <!-- 授权卡对话框 -->
        <ElDialog
          v-model="allocateDialogVisible"
          title="授权卡给企业"
          width="75%"
          @close="handleAllocateDialogClose"
        >
          <!-- 搜索过滤条件 -->
          <ArtSearchBar
            v-model:filter="cardSearchForm"
            :items="cardSearchFormItems"
            label-width="85"
            @reset="handleCardSearchReset"
            @search="handleCardSearch"
          ></ArtSearchBar>

          <!-- 卡列表 -->
          <div class="card-selection-info"> 已选择 {{ selectedAvailableCards.length }} 张卡 </div>
          <ArtTable
            ref="availableCardsTableRef"
            row-key="id"
            :loading="availableCardsLoading"
            :data="availableCardsList"
            :currentPage="cardPagination.page"
            :pageSize="cardPagination.pageSize"
            :total="cardPagination.total"
            :marginTop="10"
            @size-change="handleCardPageSizeChange"
            @current-change="handleCardPageChange"
            @selection-change="handleAvailableCardsSelectionChange"
          >
            <template #default>
              <ElTableColumn type="selection" width="55" :selectable="checkCardSelectable" />
              <ElTableColumn
                v-for="col in availableCardColumns"
                :key="col.prop || col.type"
                v-bind="col"
              />
            </template>
          </ArtTable>

          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="allocateDialogVisible = false">取消</ElButton>
              <ElButton
                type="primary"
                @click="handleAllocate"
                :loading="allocateLoading"
                :disabled="selectedAvailableCards.length === 0"
              >
                确认授权
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 批量回收对话框 -->
        <ElDialog
          v-model="recallDialogVisible"
          title="批量回收卡授权"
          width="600px"
          @close="handleRecallDialogClose"
        >
          <ElForm ref="recallFormRef" :model="recallForm" :rules="recallRules">
            <ElFormItem label="回收卡数">
              <div>已选择 {{ selectedCards.length }} 张卡</div>
            </ElFormItem>
            <ElFormItem label="回收原因">
              <ElInput
                v-model="recallForm.reason"
                type="textarea"
                :rows="3"
                placeholder="请输入回收原因(可选)"
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="recallDialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleRecall" :loading="recallLoading">
                确认回收
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 结果对话框 -->
        <ElDialog
          v-model="resultDialogVisible"
          :title="resultTitle"
          width="700px"
          @close="handleResultDialogClose"
        >
          <ElDescriptions :column="2" border>
            <ElDescriptionsItem label="成功数">
              <ElTag type="success">{{ operationResult.success_count }}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="失败数">
              <ElTag type="danger">{{ operationResult.fail_count }}</ElTag>
            </ElDescriptionsItem>
          </ElDescriptions>

          <div
            v-if="operationResult.failed_items && operationResult.failed_items.length > 0"
            class="result-section"
          >
            <ElDivider content-position="left">失败项详情</ElDivider>
            <ElTable :data="operationResult.failed_items" border max-height="300">
              <ElTableColumn prop="iccid" label="ICCID" width="200" />
              <ElTableColumn prop="reason" label="失败原因" />
            </ElTable>
          </div>

          <!-- 显示授权的设备 -->
          <div
            v-if="operationResult.allocated_devices && operationResult.allocated_devices.length > 0"
            class="result-section"
          >
            <ElDivider content-position="left">已授权设备</ElDivider>
            <ElTable :data="operationResult.allocated_devices" border max-height="200">
              <ElTableColumn prop="device_imei" label="设备IMEI" width="180" />
              <ElTableColumn label="绑定卡数">
                <template #default="{ row }">
                  {{ row.iccids?.length || 0 }}
                </template>
              </ElTableColumn>
            </ElTable>
          </div>

          <template #footer>
            <div class="dialog-footer">
              <ElButton type="primary" @click="resultDialogVisible = false">确定</ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 表格行操作右键菜单 -->
        <ArtMenuRight
          ref="cardOperationMenuRef"
          :menu-items="cardOperationMenuItems"
          :menu-width="140"
          @select="handleCardOperationMenuSelect"
        />
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { EnterpriseService, CardService } from '@/api/modules'
  import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  import { useTableContextMenu } from '@/composables/useTableContextMenu'
  import { formatDateTime } from '@/utils/business/format'
  import ArtMenuRight from '@/components/core/others/ArtMenuRight.vue'
  import TableContextMenuHint from '@/components/core/others/TableContextMenuHint.vue'
  import type { MenuItemType } from '@/components/core/others/ArtMenuRight.vue'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { BgColorEnum } from '@/enums/appEnum'
  import type {
    EnterpriseCardItem,
    AllocateCardsResponse,
    RecallCardsResponse
  } from '@/types/api/enterpriseCard'
  import type { EnterpriseItem } from '@/types/api'
  import type { StandaloneIotCard } from '@/types/api/card'

  defineOptions({ name: 'EnterpriseCards' })

  const { hasAuth } = useAuth()

  const route = useRoute()
  const router = useRouter()

  // 使用表格右键菜单功能
  const {
    showContextMenuHint,
    hintPosition,
    getRowClassName,
    handleCellMouseEnter,
    handleCellMouseLeave
  } = useTableContextMenu()

  const loading = ref(false)
  const allocateDialogVisible = ref(false)
  const allocateLoading = ref(false)
  const recallDialogVisible = ref(false)
  const recallLoading = ref(false)
  const resultDialogVisible = ref(false)
  const resultTitle = ref('')
  const tableRef = ref()
  const recallFormRef = ref<FormInstance>()
  const selectedCards = ref<EnterpriseCardItem[]>([])
  const enterpriseId = ref<number>(0)
  const enterpriseInfo = ref<EnterpriseItem | null>(null)
  const operationResult = ref<AllocateCardsResponse | RecallCardsResponse>({
    success_count: 0,
    fail_count: 0,
    failed_items: null,
    allocated_devices: null
  })

  // 可用卡列表相关
  const availableCardsTableRef = ref()
  const availableCardsLoading = ref(false)
  const availableCardsList = ref<StandaloneIotCard[]>([])
  const selectedAvailableCards = ref<StandaloneIotCard[]>([])
  const allocatedCardIccids = ref<Set<string>>(new Set())

  // 右键菜单相关
  const cardOperationMenuRef = ref<InstanceType<typeof ArtMenuRight>>()
  const currentOperatingCard = ref<EnterpriseCardItem | null>(null)

  // 卡搜索表单初始值
  const initialCardSearchState = {
    status: undefined,
    carrier_id: undefined,
    iccid: '',
    msisdn: '',
    is_distributed: undefined
  }

  const cardSearchForm = reactive({ ...initialCardSearchState })
  const cardPagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索表单初始值
  const initialSearchState = {
    iccid: '',
    virtual_no: '',
    carrier_id: undefined as number | undefined,
    status: undefined as number | undefined
  }

  // 搜索表单
  const searchForm = reactive({ ...initialSearchState })

  // 回收表单
  const recallForm = reactive({
    reason: ''
  })

  // 回收表单验证规则
  const recallRules = reactive<FormRules>({})

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: 'ICCID',
      prop: 'iccid',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID'
      }
    },
    {
      label: '设备号',
      prop: 'virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入设备号'
      }
    },
    {
      label: '运营商',
      prop: 'carrier_id',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '中国移动', value: 1 },
        { label: '中国联通', value: 2 },
        { label: '中国电信', value: 3 }
      ]
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '在库', value: 1 },
        { label: '已分销', value: 2 },
        { label: '已激活', value: 3 },
        { label: '已停用', value: 4 }
      ]
    }
  ]

  // 卡列表搜索表单配置
  const cardSearchFormItems: SearchFormItem[] = [
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '在库', value: 1 },
        { label: '已分销', value: 2 },
        { label: '已激活', value: 3 },
        { label: '已停用', value: 4 }
      ]
    },
    {
      label: '运营商',
      prop: 'carrier_id',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '中国移动', value: 1 },
        { label: '中国联通', value: 2 },
        { label: '中国电信', value: 3 }
      ]
    },
    {
      label: 'ICCID',
      prop: 'iccid',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID'
      }
    },
    {
      label: '卡接入号',
      prop: 'msisdn',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入卡接入号'
      }
    },
    {
      label: '是否已分销',
      prop: 'is_distributed',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '是', value: true },
        { label: '否', value: false }
      ]
    }
  ]

  // 列配置
  const columnOptions = [
    { label: 'ICCID', prop: 'iccid' },
    { label: '卡接入号', prop: 'msisdn' },
    { label: '设备号', prop: 'virtual_no' },
    { label: '运营商ID', prop: 'carrier_id' },
    { label: '运营商', prop: 'carrier_name' },
    { label: '套餐名称', prop: 'package_name' },
    { label: '状态', prop: 'status' },
    { label: '状态名称', prop: 'status_name' },
    { label: '网络状态', prop: 'network_status' },
    { label: '网络状态名称', prop: 'network_status_name' }
  ]

  const cardList = ref<EnterpriseCardItem[]>([])

  // 获取卡状态标签类型
  const getCardStatusTag = (status: number) => {
    switch (status) {
      case 1:
        return 'info'
      case 2:
        return 'warning'
      case 3:
        return 'success'
      case 4:
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取卡状态文本 - 使用API返回的status_name
  const getCardStatusText = (status: number) => {
    switch (status) {
      case 1:
        return '在库'
      case 2:
        return '已分销'
      case 3:
        return '已激活'
      case 4:
        return '已停用'
      default:
        return '未知'
    }
  }

  // 获取网络状态标签类型
  const getNetworkStatusTag = (status: number) => {
    return status === 1 ? 'success' : 'danger'
  }

  // 获取网络状态文本 - 使用API返回的network_status_name
  const getNetworkStatusText = (status: number) => {
    return status === 1 ? '开机' : '停机'
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'iccid',
      label: 'ICCID',
      minWidth: 200
    },
    {
      prop: 'msisdn',
      label: '卡接入号',
      width: 130
    },
    {
      prop: 'virtual_no',
      label: '设备号',
      width: 150
    },
    {
      prop: 'carrier_id',
      label: '运营商ID',
      width: 100
    },
    {
      prop: 'carrier_name',
      label: '运营商',
      width: 120
    },
    {
      prop: 'package_name',
      label: '套餐名称',
      width: 150
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: EnterpriseCardItem) => {
        return h(ElTag, { type: getCardStatusTag(row.status) }, () => getCardStatusText(row.status))
      }
    },
    {
      prop: 'status_name',
      label: '状态名称',
      width: 100
    },
    {
      prop: 'network_status',
      label: '网络状态',
      width: 100,
      formatter: (row: EnterpriseCardItem) => {
        return h(ElTag, { type: getNetworkStatusTag(row.network_status) }, () =>
          getNetworkStatusText(row.network_status)
        )
      }
    },
    {
      prop: 'network_status_name',
      label: '网络状态名称',
      width: 130
    }
  ])

  onMounted(() => {
    const id = route.query.id
    if (id) {
      enterpriseId.value = Number(id)
      getEnterpriseInfo()
      getTableData()
    } else {
      console.log('缺少企业ID')
      goBack()
    }
  })

  // 获取企业信息
  const getEnterpriseInfo = async () => {
    try {
      const res = await EnterpriseService.getEnterprises({
        page: 1,
        page_size: 1,
        id: enterpriseId.value
      })
      if (res.code === 0 && res.data.items && res.data.items.length > 0) {
        enterpriseInfo.value = res.data.items[0]
      }
    } catch (error) {
      console.error('获取企业信息失败:', error)
    }
  }

  // 获取企业卡列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        page_size: pagination.pageSize,
        iccid: searchForm.iccid || undefined,
        virtual_no: searchForm.virtual_no || undefined,
        carrier_id: searchForm.carrier_id,
        status: searchForm.status
      }

      // 清理空值
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })

      const res = await EnterpriseService.getEnterpriseCards(enterpriseId.value, params)
      if (res.code === 0) {
        cardList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      console.log('获取企业卡列表失败')
    } finally {
      loading.value = false
    }
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    getTableData()
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  // 刷新表格
  const handleRefresh = () => {
    getTableData()
  }

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

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.page = newCurrentPage
    getTableData()
  }

  // 表格选择变化
  const handleSelectionChange = (selection: EnterpriseCardItem[]) => {
    selectedCards.value = selection
  }

  // 返回
  const goBack = () => {
    router.back()
  }

  // 获取可用卡状态类型
  const getAvailableCardStatusType = (status: number) => {
    switch (status) {
      case 1:
        return 'info'
      case 2:
        return 'warning'
      case 3:
        return 'success'
      case 4:
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取可用卡状态文本
  const getAvailableCardStatusText = (status: number) => {
    switch (status) {
      case 1:
        return '在库'
      case 2:
        return '已分销'
      case 3:
        return '已激活'
      case 4:
        return '已停用'
      default:
        return '未知'
    }
  }

  // 可用卡列表列配置
  const availableCardColumns = computed(() => [
    {
      prop: 'iccid',
      label: 'ICCID',
      minWidth: 180
    },
    {
      prop: 'msisdn',
      label: '卡接入号',
      width: 130
    },
    {
      prop: 'carrier_name',
      label: '运营商',
      width: 100
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: StandaloneIotCard) => {
        return h(ElTag, { type: getAvailableCardStatusType(row.status) }, () =>
          getAvailableCardStatusText(row.status)
        )
      }
    },
    {
      prop: 'activation_status',
      label: '激活状态',
      width: 100,
      formatter: (row: StandaloneIotCard) => {
        const type = row.activation_status === 1 ? 'success' : 'info'
        const text = row.activation_status === 1 ? '已激活' : '未激活'
        return h(ElTag, { type }, () => text)
      }
    },
    {
      prop: 'network_status',
      label: '网络状态',
      width: 100,
      formatter: (row: StandaloneIotCard) => {
        const type = row.network_status === 1 ? 'success' : 'danger'
        const text = row.network_status === 1 ? '正常' : '停机'
        return h(ElTag, { type }, () => text)
      }
    },
    {
      prop: 'real_name_status',
      label: '实名状态',
      width: 100,
      formatter: (row: StandaloneIotCard) => {
        const type = row.real_name_status === 1 ? 'success' : 'warning'
        const text = row.real_name_status === 1 ? '已实名' : '未实名'
        return h(ElTag, { type }, () => text)
      }
    },
    {
      prop: 'data_usage_mb',
      label: '累计流量(MB)',
      width: 120
    },
    {
      prop: 'first_commission_paid',
      label: '首次佣金',
      width: 100,
      formatter: (row: StandaloneIotCard) => {
        const type = row.first_commission_paid ? 'success' : 'info'
        const text = row.first_commission_paid ? '已支付' : '未支付'
        return h(ElTag, { type, size: 'small' }, () => text)
      }
    },
    {
      prop: 'accumulated_recharge',
      label: '累计充值',
      width: 100,
      formatter: (row: StandaloneIotCard) => `¥${(row.accumulated_recharge / 100).toFixed(2)}`
    }
  ])

  // 获取可用卡列表
  const getAvailableCardsList = async () => {
    availableCardsLoading.value = true
    try {
      const params: any = {
        page: cardPagination.page,
        page_size: cardPagination.pageSize,
        ...cardSearchForm
      }
      // 清理空值
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })

      const res = await CardService.getStandaloneIotCards(params)
      if (res.code === 0) {
        availableCardsList.value = res.data.items || []
        cardPagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      console.log('获取卡列表失败')
    } finally {
      availableCardsLoading.value = false
    }
  }

  // 处理卡列表选择变化
  const handleAvailableCardsSelectionChange = (selection: StandaloneIotCard[]) => {
    selectedAvailableCards.value = selection
  }

  // 卡列表搜索
  const handleCardSearch = () => {
    cardPagination.page = 1
    getAvailableCardsList()
  }

  // 卡列表重置
  const handleCardSearchReset = () => {
    Object.assign(cardSearchForm, { ...initialCardSearchState })
    cardPagination.page = 1
    getAvailableCardsList()
  }

  // 卡列表分页大小变化
  const handleCardPageSizeChange = (newPageSize: number) => {
    cardPagination.pageSize = newPageSize
    getAvailableCardsList()
  }

  // 卡列表页码变化
  const handleCardPageChange = (newPage: number) => {
    cardPagination.page = newPage
    getAvailableCardsList()
  }

  // 检查卡是否可选（已授权的卡不可选）
  const checkCardSelectable = (row: StandaloneIotCard) => {
    return !allocatedCardIccids.value.has(row.iccid)
  }

  // 显示授权对话框
  const showAllocateDialog = () => {
    allocateDialogVisible.value = true
    selectedAvailableCards.value = []
    // 收集已授权的卡的ICCID
    allocatedCardIccids.value = new Set(cardList.value.map((card) => card.iccid))
    // 重置搜索条件
    Object.assign(cardSearchForm, { ...initialCardSearchState })
    cardPagination.page = 1
    cardPagination.pageSize = 20
    // 加载可用卡列表
    getAvailableCardsList()
  }

  // 执行授权
  const handleAllocate = async () => {
    if (selectedAvailableCards.value.length === 0) {
      ElMessage.warning('请选择要授权的卡')
      return
    }

    allocateLoading.value = true
    try {
      const iccids = selectedAvailableCards.value.map((card) => card.iccid)
      const res = await EnterpriseService.allocateCards(enterpriseId.value, {
        iccids
      })

      if (res.code === 0) {
        operationResult.value = res.data
        resultTitle.value = '授权结果'
        allocateDialogVisible.value = false
        resultDialogVisible.value = true
        getTableData()
      }
    } catch (error) {
      console.error(error)
      console.log('授权失败')
    } finally {
      allocateLoading.value = false
    }
  }

  // 关闭授权对话框
  const handleAllocateDialogClose = () => {
    selectedAvailableCards.value = []
  }

  // 显示批量回收对话框
  const showRecallDialog = () => {
    if (selectedCards.value.length === 0) {
      ElMessage.warning('请先选择要回收的卡')
      return
    }
    recallDialogVisible.value = true
    recallForm.reason = ''
    if (recallFormRef.value) {
      recallFormRef.value.resetFields()
    }
  }

  // 执行批量回收
  const handleRecall = async () => {
    if (!recallFormRef.value) return

    await recallFormRef.value.validate(async (valid) => {
      if (valid) {
        recallLoading.value = true
        try {
          const res = await EnterpriseService.recallCards(enterpriseId.value, {
            iccids: selectedCards.value.map((card) => card.iccid)
          })

          if (res.code === 0) {
            operationResult.value = res.data
            resultTitle.value = '回收结果'
            recallDialogVisible.value = false
            resultDialogVisible.value = true
            // 清空选择
            if (tableRef.value) {
              tableRef.value.clearSelection()
            }
            selectedCards.value = []
            getTableData()
          }
        } catch (error) {
          console.error(error)
          console.log('回收失败')
        } finally {
          recallLoading.value = false
        }
      }
    })
  }

  // 关闭批量回收对话框
  const handleRecallDialogClose = () => {
    if (recallFormRef.value) {
      recallFormRef.value.resetFields()
    }
  }

  // 关闭结果对话框
  const handleResultDialogClose = () => {
    getTableData()
  }

  // 右键菜单项配置
  const cardOperationMenuItems = computed((): MenuItemType[] => {
    const items: MenuItemType[] = []

    if (!currentOperatingCard.value) return items

    if (currentOperatingCard.value.network_status === 0) {
      // 停机状态 - 显示复机
      if (hasAuth('enterprise_cards:resume')) {
        items.push({
          key: 'resume',
          label: '复机'
        })
      }
    } else {
      // 开机状态 - 显示停机
      if (hasAuth('enterprise_cards:suspend')) {
        items.push({
          key: 'suspend',
          label: '停机'
        })
      }
    }

    return items
  })

  // 处理右键菜单
  const handleRowContextMenu = (row: EnterpriseCardItem, column: any, event: MouseEvent) => {
    event.preventDefault()
    currentOperatingCard.value = row
    nextTick(() => {
      cardOperationMenuRef.value?.show(event)
    })
  }

  // 处理菜单选择
  const handleCardOperationMenuSelect = (item: MenuItemType) => {
    if (!currentOperatingCard.value) return

    switch (item.key) {
      case 'suspend':
        handleSuspend(currentOperatingCard.value)
        break
      case 'resume':
        handleResume(currentOperatingCard.value)
        break
    }
  }

  // 停机卡
  const handleSuspend = (row: EnterpriseCardItem) => {
    ElMessageBox.confirm('确定要停机该卡吗？', '停机卡', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          await EnterpriseService.suspendCard(enterpriseId.value, row.id)
          ElMessage.success('停机成功')
          getTableData()
        } catch (error) {
          console.error(error)
          console.log('停机失败')
        }
      })
      .catch(() => {})
  }

  // 复机卡
  const handleResume = (row: EnterpriseCardItem) => {
    ElMessageBox.confirm('确定要复机该卡吗？', '复机卡', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
      .then(async () => {
        try {
          await EnterpriseService.resumeCard(enterpriseId.value, row.id)
          ElMessage.success('复机成功')
          getTableData()
        } catch (error) {
          console.error(error)
          console.log('复机失败')
        }
      })
      .catch(() => {})
  }
</script>

<style lang="scss" scoped>
  .enterprise-cards-page {
    .enterprise-info-card {
      margin-bottom: 16px;
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .card-selection-info {
      margin-top: 10px;
      margin-bottom: 12px;
      font-size: 14px;
      color: var(--el-color-info);
    }

    .card-pagination {
      margin-top: 16px;
      text-align: right;
    }

    .result-section {
      margin-top: 20px;
    }

    .mt-20 {
      margin-top: 20px;
    }
  }

  :deep(.el-table__row.table-row-with-context-menu) {
    cursor: pointer;
  }
</style>
