<script lang="ts" setup>
import { Check, CircleCheck, CircleClose, Close, Delete, DocumentCopy, Edit, Files, Hide, Key, Plus, PriceTag, Reading, Refresh, Timer, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import {
  createToken,
  deleteToken,
  disableToken,
  editToken,
  enableToken,
  getTokenList,
} from '@/api/model/index.ts';
import { isUserVip } from '@/utils/user';
import TokenFormDialog from './TokenFormDialog.vue';

interface TokenItem {
  id: string;
  name: string;
  apiKey: string;
  expireTime: string | null;
  premiumQuotaLimit: number | null;
  premiumUsedQuota: number | null;
  isDisabled: boolean;
  creationTime: string | null;
  showKey?: boolean;
}

interface TokenFormData {
  id?: string;
  name: string;
  expireTime: string;
  premiumQuotaLimit: number;
  quotaUnit: string;
}

const tokenList = ref<TokenItem[]>([]);
const loading = ref(false);
const showFormDialog = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const currentFormData = ref<TokenFormData>({
  name: '',
  expireTime: '',
  premiumQuotaLimit: 0,
  quotaUnit: '万',
});
const router = useRouter();

// 移动端检测
const isMobile = ref(false);

function checkMobile() {
  isMobile.value = window.innerWidth < 768;
}

// 防抖和节流控制
const operatingTokenId = ref<string>('');

// 分页相关
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const queryParams = ref({
  skipCount: 0,
  maxResultCount: 10,
  orderByColumn: undefined as string | undefined,
  isAsc: undefined as string | undefined,
});

// 获取Token列表
async function fetchTokenList(resetPage = false) {
  if (resetPage) {
    currentPage.value = 1;
  }

  try {
    loading.value = true;
    const params = {
      skipCount: currentPage.value,
      maxResultCount: pageSize.value,
      orderByColumn: queryParams.value.orderByColumn,
      isAsc: queryParams.value.isAsc,
    };

    const res = await getTokenList(params);
    if (res.data) {
      tokenList.value = (res.data.items || []).map((item: TokenItem) => ({
        ...item,
        showKey: false,
      }));
      totalCount.value = res.data.totalCount || 0;
    }
  }
  catch (error) {
    console.error('获取API密钥列表失败:', error);
    ElMessage.error('获取API密钥列表失败');
    tokenList.value = [];
    totalCount.value = 0;
  }
  finally {
    loading.value = false;
  }
}

// 显示新增对话框
function showCreateDialog() {
  if (!isUserVip()) {
    ElMessageBox.confirm(
      `
    <div class="text-center leading-relaxed">
      <h3 class="text-lg font-bold mb-3">成为 YiXinAI-VIP</h3>
      <p class="mb-2">
     解锁所有 AI 模型，无限加速，专属客服，尽享尊贵体验。
      </p>
 <p class="text-sm text-gray-500">点击下方按钮，立即升级为 VIP 会员！</p>
    </div>
    `,
      '会员尊享',
      {
        confirmButtonText: '前往产品页面',
        cancelButtonText: '关闭',
        dangerouslyUseHTMLString: true,
        type: 'info',
        center: true,
        roundButton: true,
      },
    )
      .then(() => {
        router.push({
          name: 'products',
          query: { from: 'user' },
        });
      })
      .catch(() => {});
    return;
  }

  formMode.value = 'create';
  currentFormData.value = {
    name: '',
    expireTime: '',
    premiumQuotaLimit: 0,
    quotaUnit: '万',
  };
  showFormDialog.value = true;
}

// 显示编辑对话框
function showEditDialog(token: TokenItem) {
  formMode.value = 'edit';
  currentFormData.value = {
    id: token.id,
    name: token.name,
    expireTime: token.expireTime,
    premiumQuotaLimit: token.premiumQuotaLimit,
    quotaUnit: '万',
  };
  showFormDialog.value = true;
}

// 处理表单提交（带防抖）
async function handleFormSubmit(data: TokenFormData) {
  if (loading.value)
    return;

  try {
    loading.value = true;
    const submitData = {
      id: data.id,
      name: data.name,
      expireTime: data.expireTime || null,
      premiumQuotaLimit: data.premiumQuotaLimit || null,
    };

    if (formMode.value === 'create') {
      await createToken(submitData);
      ElMessage.success('API密钥创建成功');
    }
    else {
      await editToken(submitData);
      ElMessage.success('API密钥更新成功');
    }

    showFormDialog.value = false;
    await fetchTokenList();
  }
  catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(formMode.value === 'create' ? '创建API密钥失败' : '编辑API密钥失败');
  }
  finally {
    loading.value = false;
  }
}

// 删除Token（带防抖）
async function handleDelete(row: TokenItem) {
  if (operatingTokenId.value === row.id)
    return;

  try {
    await ElMessageBox.confirm(
      `确定要删除 API密钥 "${row.name}" 吗？删除后将无法恢复`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
      },
    );

    operatingTokenId.value = row.id;
    await deleteToken(row.id);
    ElMessage.success('API密钥已删除');
    await fetchTokenList();
  }
  catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
  finally {
    operatingTokenId.value = '';
  }
}

// 启用/禁用Token（带防抖）
async function handleToggle(row: TokenItem) {
  if (operatingTokenId.value === row.id)
    return;

  try {
    operatingTokenId.value = row.id;
    if (row.isDisabled) {
      await enableToken(row.id);
      ElMessage.success(`API密钥 "${row.name}" 已启用`);
    }
    else {
      await disableToken(row.id);
      ElMessage.success(`API密钥 "${row.name}" 已禁用`);
    }
    await fetchTokenList();
  }
  catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
  finally {
    operatingTokenId.value = '';
  }
}

// 切换密钥显示状态
function toggleKeyVisibility(row: TokenItem) {
  row.showKey = !row.showKey;
}

// 复制API密钥
function copyApiKey(apiKey: string, name: string) {
  navigator.clipboard.writeText(apiKey)
    .then(() => ElMessage.success(`已复制 "${name}" 的API密钥`))
    .catch(() => ElMessage.error('复制失败'));
}

// 格式化日期
function formatDateTime(dateStr: string | null | undefined) {
  if (!dateStr)
    return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

// 格式化配额数字
function formatQuota(num: number | null | undefined): string {
  if (num == null || num === 0)
    return '0';
  if (num >= 100000000) {
    return `${(num / 100000000).toFixed(2).replace(/\.?0+$/, '')} 亿`;
  }
  if (num >= 10000) {
    return `${(num / 10000).toFixed(2).replace(/\.?0+$/, '')} 万`;
  }
  if (num >= 1000) {
    return `${(num / 1000).toFixed(2).replace(/\.?0+$/, '')} 千`;
  }
  return num.toString();
}

// 计算配额使用百分比
function getQuotaPercentage(used: number | null | undefined, limit: number | null | undefined) {
  if (limit == null || limit === 0 || used == null)
    return 0;
  return Math.min((used / limit) * 100, 100);
}

// 获取配额状态颜色
function getQuotaColor(percentage: number) {
  if (percentage >= 90)
    return '#f56c6c';
  if (percentage >= 70)
    return '#e6a23c';
  return '#67c23a';
}

// 处理排序
function handleSortChange({ prop, order }: { prop: string; order: string | null }) {
  console.log('排序变化:', { prop, order });
  if (order) {
    queryParams.value.orderByColumn = prop;
    queryParams.value.isAsc = order === 'ascending' ? 'ascending' : 'descending';
  }
  else {
    queryParams.value.orderByColumn = undefined;
    queryParams.value.isAsc = undefined;
  }
  fetchTokenList(true);
}

// 处理分页
function handlePageChange(page: number) {
  console.log('切换页码:', page);
  currentPage.value = page;
  fetchTokenList();
}

// 处理每页大小变化
function handleSizeChange(size: number) {
  console.log('修改每页大小:', size);
  pageSize.value = size;
  queryParams.value.maxResultCount = size;
  currentPage.value = 1;
  fetchTokenList();
}

// 是否有Token
const hasTokens = computed(() => tokenList.value.length > 0);

// 检查按钮是否正在操作
function isOperating(tokenId: string) {
  return operatingTokenId.value === tokenId;
}

onMounted(async () => {
  checkMobile();
  window.addEventListener('resize', checkMobile);
  await fetchTokenList();
});

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);
});
</script>

<template>
  <el-card v-loading="loading" class="token-management-card" shadow="never">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <div class="header-icon-wrapper">
            <el-icon class="header-icon">
              <Key />
            </el-icon>
          </div>
          <div class="header-text">
            <span class="header-title">API密钥管理中心</span>
            <span class="header-subtitle">管理您的 API 访问密钥，每个 API密钥 拥有独立的配额和使用统计</span>
          </div>
        </div>
        <div class="header-right">
          <el-tag v-if="totalCount > 0" type="primary" size="large" class="count-tag" effect="light">
            <el-icon><Files /></el-icon>
            共 <span class="count-number">{{ totalCount }}</span> 个
          </el-tag>
        </div>
      </div>
    </template>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" size="default" @click="showCreateDialog">
          新增 API密钥
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" size="default" @click="fetchTokenList">
          刷新列表
        </el-button>
      </div>
    </div>

    <!-- Token列表 -->
    <div v-if="hasTokens">
      <!-- 桌面端表格 -->
      <div v-if="!isMobile" class="token-table-wrapper">
        <el-table
        :data="tokenList"
        stripe
        border
        class="token-table"
        empty-text="暂无数据"
        :header-cell-style="{ background: '#fafafa', color: '#262626', fontWeight: '600' }"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="name"
          label="API密钥 名称"
          min-width="180"
          sortable
          show-overflow-tooltip
          align="left"
          header-align="left"
          resizable
        >
          <template #default="{ row }">
            <div class="name-cell">
              <div class="name-icon-bg">
                <el-icon class="name-icon">
                  <PriceTag />
                </el-icon>
              </div>
              <span class="name-text">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="API 密钥"
          min-width="200"
          align="left"
          header-align="left"
          resizable
        >
          <template #default="{ row }">
            <div class="key-cell">
              <div class="key-content">
                <span class="key-text">
                  {{ row.showKey ? row.apiKey : '•••••••••••••••••••••' }}
                </span>
              </div>
              <div class="key-actions">
                <el-button
                  :icon="row.showKey ? Hide : View"
                  size="small"
                  text
                  @click="toggleKeyVisibility(row)"
                >
                  {{ row.showKey ? '隐藏' : '查看' }}
                </el-button>
                <el-button
                  :icon="DocumentCopy"
                  size="small"
                  type="primary"
                  text
                  @click="copyApiKey(row.apiKey, row.name)"
                >
                  复制
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="配额使用情况"
          min-width="220"
          align="center"
          header-align="center"
          resizable
        >
          <template #default="{ row }">
            <div class="quota-cell">
              <div class="quota-info">
                <span class="quota-used">{{ formatQuota(row.premiumUsedQuota) }}</span>
                <span class="quota-separator">/</span>
                <span class="quota-total">
                  {{ (row.premiumQuotaLimit == null || row.premiumQuotaLimit === 0) ? '∞ 无限' : formatQuota(row.premiumQuotaLimit) }}
                </span>
              </div>
              <el-progress
                v-if="row.premiumQuotaLimit != null && row.premiumQuotaLimit > 0"
                :percentage="getQuotaPercentage(row.premiumUsedQuota, row.premiumQuotaLimit)"
                :color="getQuotaColor(getQuotaPercentage(row.premiumUsedQuota, row.premiumQuotaLimit))"
                :stroke-width="6"
                :show-text="true"
                class="quota-progress"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="过期时间"
          min-width="180"
          prop="expireTime"
          sortable
          align="center"
          header-align="center"
          resizable
        >
          <template #default="{ row }">
            <div v-if="row.expireTime" class="time-cell">
              <el-icon class="time-icon">
                <Timer />
              </el-icon>
              <span>{{ formatDateTime(row.expireTime) }}</span>
            </div>
            <el-tag v-else type="success" size="default" effect="light" class="never-expire-tag">
              <el-icon><CircleCheck /></el-icon>
              永不过期
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="状态"
          width="110"
          prop="isDisabled"
          sortable
          align="center"
          header-align="center"
          resizable
        >
          <template #default="{ row }">
            <el-tag
              :type="row.isDisabled ? 'danger' : 'success'"
              effect="light"
              size="default"
              class="status-tag"
            >
              <el-icon>
                <CircleClose v-if="row.isDisabled" />

                <CircleCheck v-else />
              </el-icon>
              {{ row.isDisabled ? '已禁用' : '已启用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          min-width="160"
          prop="creationTime"
          sortable
          align="center"
          header-align="center"
          resizable
        >
          <template #default="{ row }">
            <div class="time-cell">
              <span>{{ formatDateTime(row.creationTime) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="80"
          fixed="right"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                :icon="Edit"
                @click="showEditDialog(row)"
              >
                编辑
              </el-button>
              <el-button
                style="margin-left: 0px"
                size="small"
                :type="row.isDisabled ? 'success' : 'warning'"
                :icon="row.isDisabled ? Check : Close"
                :loading="isOperating(row.id)"
                @click="handleToggle(row)"
              >
                {{ row.isDisabled ? '启用' : '禁用' }}
              </el-button>
              <el-button
                style="margin-left: 0px"
                size="small"
                type="danger"
                :icon="Delete"
                :loading="isOperating(row.id)"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      </div>

      <!-- 移动端卡片列表 -->
      <div v-else class="mobile-token-list">
        <div v-for="token in tokenList" :key="token.id" class="mobile-token-card">
          <div class="mobile-card-header">
            <div class="mobile-card-title">
              <el-icon class="title-icon"><PriceTag /></el-icon>
              <span>{{ token.name }}</span>
            </div>
            <el-tag :type="token.isDisabled ? 'danger' : 'success'" size="small">
              {{ token.isDisabled ? '已禁用' : '启用中' }}
            </el-tag>
          </div>

          <div class="mobile-card-body">
            <!-- API密钥 -->
            <div class="mobile-info-item">
              <div class="mobile-info-label">API密钥</div>
              <div class="mobile-key-row">
                <span class="mobile-key-text">
                  {{ token.showKey ? token.apiKey : '•••••••••••••••••••••' }}
                </span>
                <div class="mobile-key-actions">
                  <el-button
                    :icon="token.showKey ? Hide : View"
                    size="small"
                    text
                    @click="toggleKeyVisibility(token)"
                  />
                  <el-button
                    :icon="DocumentCopy"
                    size="small"
                    type="primary"
                    text
                    @click="copyApiKey(token.apiKey, token.name)"
                  />
                </div>
              </div>
            </div>

            <!-- 配额信息 -->
            <div v-if="token.premiumQuotaLimit" class="mobile-info-item">
              <div class="mobile-info-label">配额使用</div>
              <div class="mobile-quota-info">
                <el-progress
                  :percentage="getQuotaPercentage(token.premiumUsedQuota, token.premiumQuotaLimit)"
                  :color="getQuotaColor(getQuotaPercentage(token.premiumUsedQuota, token.premiumQuotaLimit))"
                  :stroke-width="8"
                />
                <div class="mobile-quota-text">
                  {{ formatQuota(token.premiumUsedQuota) }} / {{ formatQuota(token.premiumQuotaLimit) }}
                </div>
              </div>
            </div>

            <!-- 过期时间 -->
            <div v-if="token.expireTime" class="mobile-info-item">
              <div class="mobile-info-label">过期时间</div>
              <div class="mobile-info-value">{{ formatDateTime(token.expireTime) }}</div>
            </div>

            <!-- 创建时间 -->
            <div class="mobile-info-item">
              <div class="mobile-info-label">创建时间</div>
              <div class="mobile-info-value">{{ formatDateTime(token.creationTime) }}</div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="mobile-card-actions">
            <el-button size="small" :icon="Edit" @click="showEditDialog(token)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="token.isDisabled ? 'success' : 'warning'"
              :icon="token.isDisabled ? Check : Close"
              :loading="isOperating(token.id)"
              @click="handleToggle(token)"
            >
              {{ token.isDisabled ? '启用' : '禁用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              :loading="isOperating(token.id)"
              @click="handleDelete(token)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalCount > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading" class="empty-container">
      <el-empty description="暂无API密钥，点击下方按钮创建您的第一个 API密钥">
        <el-button type="primary" size="large" :icon="Plus" @click="showCreateDialog">
          创建第一个 API密钥
        </el-button>
      </el-empty>
    </div>
  </el-card>

  <!-- 使用说明 -->
  <el-card v-if="hasTokens" class="usage-guide-card" shadow="never">
    <template #header>
      <div class="guide-header">
        <div class="guide-icon-wrapper">
          <el-icon class="guide-icon">
            <Reading />
          </el-icon>
        </div>
        <span class="guide-title">使用说明</span>
      </div>
    </template>

    <div class="guide-content">
      <h1 class="guide-main-title">
        <a
          href="https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde"
          target="_blank"
          class="guide-link"
        >
          点击前往文档：【意心Ai】AI工具玩法指南
          <el-icon class="link-icon"><i-ep-top-right /></el-icon>
        </a>
      </h1>
    </div>
  </el-card>

  <!-- Token表单对话框 -->
  <TokenFormDialog
    v-model:visible="showFormDialog"
    :mode="formMode"
    :form-data="currentFormData"
    @confirm="handleFormSubmit"
  />
</template>

<style scoped lang="scss">
/* 卡片样式 - 现代化设计 */
.token-management-card {
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  margin-bottom: 10px;

  overflow: hidden;

  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  }

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border-bottom: 1px solid #e8e8e8;
    padding: 24px 28px;
  }

  :deep(.el-card__body) {
    padding: 15px;
  }
}

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

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.header-icon {
  font-size: 24px;
  color: #ffffff;
}

.header-text {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.header-title {
  font-size: 20px;
  font-weight: 700;
  color: #262626;
  letter-spacing: -0.5px;
}

.header-subtitle {
  font-size: 13px;
  color: #8c8c8c;
  line-height: 1.5;
}

.header-right {
  display: flex;
  align-items: center;
}

.count-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 20px;
  font-weight: 600;
  font-size: 14px;
  border-radius: 24px;
  border: 2px solid #e6f4ff;

  .el-icon {
    font-size: 16px;
  }

  .count-number {
    font-size: 18px;
    font-weight: 700;
    color: #1890ff;
  }
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 12px;
}

/* 表格样式 */
.token-table-wrapper {
  margin-bottom: 0;
  border-radius: 8px;
  overflow: hidden;
}

.token-table {
  width: 100%;

  :deep(.el-table__body) {
    tr {
      transition: all 0.2s;

      &:hover {
        background-color: #fafafa !important;
      }
    }
  }
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.name-icon-bg {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: linear-gradient(135deg, #e6f4ff 0%, #bae0ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.name-icon {
  font-size: 16px;
  color: #1890ff;
}

.name-text {
  font-weight: 600;
  color: #262626;
  font-size: 14px;
}

.key-cell {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 0;
}

.key-content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.key-icon {
  font-size: 16px;
  color: #8c8c8c;
  flex-shrink: 0;
}

.key-text {
  flex: 1;
  font-family: 'SF Mono', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', monospace;
  font-size: 13px;
  color: #595959;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background: #fafafa;
  padding: 6px 12px;
  border-radius: 6px;
}

.key-actions {
  display: flex;
  flex-shrink: 0;
  justify-content: center;
}

.quota-cell {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 8px 0;
}

.quota-info {
  display: flex;
  align-items: baseline;
  gap: 6px;
  justify-content: center;
  font-size: 14px;
}

.quota-used {
  font-weight: 700;
  color: #1890ff;
  font-size: 15px;
}

.quota-separator {
  color: #bfbfbf;
}

.quota-total {
  color: #595959;
  font-weight: 500;
}

.quota-progress {
  width: 100%;

  :deep(.el-progress__text) {
    font-size: 12px !important;
    font-weight: 700;
  }
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  color: #595959;
  font-size: 13px;
}

.time-icon {
  font-size: 14px;
  color: #8c8c8c;
  flex-shrink: 0;
}

.never-expire-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
}

.status-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
  padding: 4px 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 空状态 */
.empty-container {
  padding: 80px 0;
  text-align: center;

  :deep(.el-empty__description) {
    color: #8c8c8c;
    font-size: 14px;
  }
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  padding: 20px 0;
  display: flex;
  justify-content: center;
  border-top: 2px solid #f0f2f5;

  :deep(.el-pagination) {
    gap: 8px;

    .btn-prev,
    .btn-next {
      border-radius: 8px;
      padding: 0 16px;
      border: 1px solid #dcdfe6;
      background: #fff;
      font-weight: 500;

      &:hover {
        color: #667eea;
        border-color: #667eea;
        background: #f5f7fa;
      }
    }

    .el-pager li {
      border-radius: 8px;
      min-width: 36px;
      height: 36px;
      line-height: 36px;
      border: 1px solid transparent;
      transition: all 0.3s;

      &:hover {
        color: #667eea;
        background: #f5f7fa;
      }

      &.is-active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        border-color: transparent;
      }
    }

    .el-pagination__sizes {
      .el-select {
        .el-input__wrapper {
          border-radius: 8px;
        }
      }
    }

    .el-pagination__jump {
      .el-input__wrapper {
        border-radius: 8px;
      }
    }
  }
}

/* 使用说明卡片 */
.usage-guide-card {
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;

  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  }

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #fff7e6 0%, #ffffff 100%);
    border-bottom: 1px solid #e8e8e8;
    padding: 20px 28px;
  }

  :deep(.el-card__body) {
    padding: 24px 28px;
  }
}

.guide-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.guide-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(135deg, #ffc069 0%, #fa8c16 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(250, 140, 22, 0.3);
}

.guide-icon {
  font-size: 20px;
  color: #ffffff;
}

.guide-title {
  font-size: 17px;
  font-weight: 700;
  color: #262626;
}

.guide-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.guide-main-title {
  margin: 0;
}

.guide-link {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 700;
  color: #fa8c16;
  text-decoration: none;
  transition: all 0.3s;
  padding: 8px 0;

  &:hover {
    color: #fa541c;

    .link-icon {
      transform: translate(3px, -3px);
    }
  }
}

.link-icon {
  font-size: 18px;
  transition: transform 0.3s;
}

.iframe-container {
  position: relative;
  width: 100%;
  overflow: hidden;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.guide-iframe {
  width: 100%;
  height: 60vh;
  min-height: 400px;
  max-height: 800px;
  border: none;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-right {
    width: 100%;
  }

  .count-tag {
    width: 100%;
    justify-content: center;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;

    .el-button {
      flex: 1;
    }
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }

  /* 移动端分页 */
  .pagination-container {
    padding: 16px 0;
  }

  .pagination-container :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
    gap: 6px;

    .btn-prev,
    .btn-next {
      padding: 0 12px;
      font-size: 13px;
    }

    .el-pager li {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      font-size: 13px;
    }
  }

  /* 移动端卡片列表 */
  .mobile-token-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .mobile-token-card {
    background: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    padding: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  }

  .mobile-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
  }

  .mobile-card-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 15px;
    font-weight: 600;
    color: #333;

    .title-icon {
      color: #409eff;
    }
  }

  .mobile-card-body {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .mobile-info-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .mobile-info-label {
    font-size: 12px;
    color: #999;
    font-weight: 500;
  }

  .mobile-info-value {
    font-size: 14px;
    color: #333;
  }

  .mobile-key-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    background: #f5f7fa;
    padding: 8px;
    border-radius: 4px;
  }

  .mobile-key-text {
    flex: 1;
    font-size: 12px;
    color: #333;
    font-family: monospace;
    word-break: break-all;
  }

  .mobile-key-actions {
    display: flex;
    gap: 4px;
    flex-shrink: 0;
  }

  .mobile-quota-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .mobile-quota-text {
    font-size: 13px;
    color: #666;
    text-align: center;
  }

  .mobile-card-actions {
    display: flex;
    gap: 8px;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;

    .el-button {
      flex: 1;
      font-size: 13px;
    }
  }
}
</style>
