<script lang="ts" setup>
import type { PremiumTokenUsageDto, PremiumTokenUsageQueryParams } from '@/api/user';
import { Clock, Refresh } from '@element-plus/icons-vue';
import { getPremiumTokenUsageList } from '@/api/user';

// 额度明细列表
const usageList = ref<PremiumTokenUsageDto[]>([]);
const listLoading = ref(false);
const totalCount = ref(0);

// 查询参数
const queryParams = ref<PremiumTokenUsageQueryParams>({
  skipCount: 0,
  maxResultCount: 10,
});

// 当前页码
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const dateRange = ref<[Date, Date] | null>(null);
const freeFilter = ref<boolean | null>(null);

// 快捷时间选择
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 格式化数字 - 转换为万为单位
function formatNumber(num: number): string {
  if (num === 0)
    return '0';
  const wan = num / 10000;
  return wan.toFixed(2).replace(/\.?0+$/, '');
}

// 格式化日期时间
function formatDateTime(dateTime: string): string {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

// 获取使用率颜色
function getUsageColor(used: number, total: number): string {
  if (total === 0)
    return '#e4e7ed';
  const percent = (used / total) * 100;
  if (percent >= 90)
    return '#f56c6c'; // 红色
  if (percent >= 70)
    return '#e6a23c'; // 橙色
  return '#409eff'; // 蓝色
}

// 获取额度明细列表
async function fetchUsageList(resetPage = false) {
  if (resetPage) {
    currentPage.value = 1;
  }

  listLoading.value = true;
  try {
    const params: PremiumTokenUsageQueryParams = {
      skipCount: currentPage.value,
      maxResultCount: queryParams.value.maxResultCount,
      startTime: queryParams.value.startTime,
      endTime: queryParams.value.endTime,
      orderByColumn: queryParams.value.orderByColumn,
      isAsc: queryParams.value.isAsc,
      isFree: queryParams.value.isFree,
    };

    console.log('发送到后端的参数:', params);

    const res = await getPremiumTokenUsageList(params);
    console.log('后端返回结果:', res);

    if (res.data) {
      usageList.value = res.data.items || [];
      totalCount.value = res.data.totalCount || 0;
    }
  }
  catch (error) {
    console.error('获取额度明细列表失败:', error);
    ElMessage.error('获取额度明细列表失败');
    usageList.value = [];
    totalCount.value = 0;
  }
  finally {
    listLoading.value = false;
  }
}

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

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

// 处理排序（使用 OrderByColumn 和 IsAsc）
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;
  }
  fetchUsageList(true);
}

// 处理时间筛选
function handleDateChange(value: [Date, Date] | null) {
  console.log('时间筛选变化:', value);
  if (value && value.length === 2) {
    // 设置开始时间为当天00:00:00
    const startDate = new Date(value[0]);
    startDate.setHours(0, 0, 0, 0);

    // 设置结束时间为当天23:59:59
    const endDate = new Date(value[1]);
    endDate.setHours(23, 59, 59, 999);

    queryParams.value.startTime = startDate.toISOString();
    queryParams.value.endTime = endDate.toISOString();
    console.log('时间范围:', {
      start: queryParams.value.startTime,
      end: queryParams.value.endTime,
    });
  }
  else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  fetchUsageList(true); // 重置到第一页并获取数据
}

// 重置筛选
function resetFilters() {
  console.log('重置所有筛选条件');
  dateRange.value = null;
  freeFilter.value = null;

  // 重置后端查询参数
  queryParams.value = {
    maxResultCount: pageSize.value,
    orderByColumn: undefined,
    isAsc: undefined,
    startTime: undefined,
    endTime: undefined,
    isFree: undefined,
  };

  fetchUsageList(true);
}

// 处理是否免费筛选
function handleFreeFilterChange(value: boolean | null) {
  console.log('是否免费筛选:', value);
  queryParams.value.isFree = value === null ? undefined : value;
  fetchUsageList(true);
}

// 判断是否有活动的筛选条件
const hasActiveFilters = computed(() => {
  return !!dateRange.value || freeFilter.value !== null;
});

// 对外暴露刷新方法
defineExpose({
  refresh: fetchUsageList,
});

onMounted(() => {
  fetchUsageList();
});
</script>

<template>
  <el-card v-loading="listLoading" class="usage-list-card" shadow="hover">
    <template #header>
      <div class="list-header">
        <div class="header-left">
          <el-icon class="header-icon">
            <i-ep-document />
          </el-icon>
          <div class="header-text">
            <span class="header-title">尊享包额度明细</span>
            <!--            <span class="header-subtitle">Premium Package Usage Details</span> -->
          </div>
        </div>
        <div class="header-right">
          <el-tag v-if="totalCount > 0" type="primary" size="default" class="count-tag" effect="plain">
            <el-icon><i-ep-data-line /></el-icon>
            共 {{ totalCount }} 条记录
          </el-tag>
        </div>
      </div>
    </template>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-row">
        <div class="filter-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="default"
            :shortcuts="shortcuts"
            class="date-picker"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :editable="false"
            @change="handleDateChange"
          />
        </div>

        <div class="filter-item">
          <el-select
            v-model="freeFilter"
            placeholder="全部类型"
            clearable
            size="default"
            class="free-select"
            @change="handleFreeFilterChange"
          >
            <el-option label="免费" :value="true" />
            <el-option label="付费" :value="false" />
          </el-select>
        </div>

        <div class="filter-actions">
          <el-button
            v-if="hasActiveFilters"
            size="default"
            @click="resetFilters"
          >
            <el-icon><i-ep-refresh-left /></el-icon>
            重置
          </el-button>
          <el-button
            type="primary"
            size="default"
            :icon="Refresh"
            @click="fetchUsageList"
          >
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="usageList"
      stripe
      class="usage-table"
      empty-text="暂无数据"
      border
      @sort-change="handleSortChange"
    >
      <el-table-column prop="packageName" label="包名称" min-width="200" sortable show-overflow-tooltip align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div class="package-name-cell">
            <el-icon class="package-icon" color="#409eff">
              <i-ep-box />
            </el-icon>
            <span>{{ row.packageName }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="总额度" min-width="130" prop="totalTokens" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div class="token-cell">
            <span class="token-value">{{ formatNumber(row.totalTokens) }}</span>
            <span class="token-unit">万</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="已使用" min-width="130" prop="usedTokens" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div class="token-cell used">
            <span class="token-value">{{ formatNumber(row.usedTokens) }}</span>
            <span class="token-unit">万</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="剩余" min-width="130" prop="remainingTokens" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div class="token-cell remaining">
            <span
              class="token-value"
              :style="{ color: row.remainingTokens > 0 ? '#67c23a' : '#f56c6c', fontWeight: '600' }"
            >
              {{ formatNumber(row.remainingTokens) }}
            </span>
            <span class="token-unit">万</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="使用率" min-width="130" align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div class="usage-progress-cell">
            <el-progress
              :percentage="row.totalTokens > 0 ? Number(((row.usedTokens / row.totalTokens) * 100).toFixed(1)) : 0"
              :color="getUsageColor(row.usedTokens, row.totalTokens)"
              :stroke-width="8"
              :show-text="true"
              :text-inside="false"
            >
              <template #default="{ percentage }">
                <span class="percentage-text">{{ percentage }}%</span>
              </template>
            </el-progress>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="购买金额" min-width="110" prop="purchaseAmount" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <span class="amount-cell">¥{{ row.purchaseAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" min-width="90" prop="isActive" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'info'" size="small" effect="dark">
            {{ row.isActive ? '激活' : '未激活' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" min-width="170" prop="creationTime" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div v-if="row.creationTime" class="creation-cell">
            <el-icon class="creation-icon">
              <Clock />
            </el-icon>
            <span>{{ formatDateTime(row.creationTime) }}</span>
          </div>
          <span v-else class="no-data">-</span>
        </template>
      </el-table-column>

      <el-table-column label="到期时间" min-width="170" prop="expireDateTime" sortable align="center" header-align="center" resizable>
        <template #default="{ row }">
          <div v-if="row.expireDateTime" class="expire-cell">
            <el-icon class="expire-icon">
              <Clock />
            </el-icon>
            <span>{{ formatDateTime(row.expireDateTime) }}</span>
          </div>
          <span v-else class="no-data">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip align="center" header-align="center" resizable>
        <template #default="{ row }">
          <span class="remark-cell">{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="!usageList.length && !listLoading" class="empty-container">
      <el-empty :description="hasActiveFilters ? '当前筛选条件下无数据' : '暂无明细记录'">
        <el-button v-if="hasActiveFilters" type="primary" @click="resetFilters">
          清除筛选
        </el-button>
      </el-empty>
    </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>
  </el-card>
</template>

<style scoped lang="scss">
/* 额度明细列表卡片 */
.usage-list-card {
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f2f5;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.12);
    border-color: #667eea;
  }

  :deep(.el-card__header) {
    background: linear-gradient(to bottom, #fafbfc 0%, #ffffff 100%);
    border-bottom: 2px solid #f0f2f5;
  }
}

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

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

.header-icon {
  font-size: 24px;
  color: #f59e0b;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  padding: 8px;
  border-radius: 8px;
}

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

.header-title {
  font-size: 18px;
  font-weight: 700;
  color: #1a1a1a;
}

.header-subtitle {
  font-size: 13px;
  color: #909399;
}

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

.count-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  font-weight: 600;
  border-radius: 20px;

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

/* 筛选工具栏 */
.filter-toolbar {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e8eaed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 12px;
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  border-left: 3px solid #409eff;
}

.filter-item {
  flex: 0 0 auto;
}

.date-picker {
  width: 320px;
}

.free-select {
  width: 140px;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.usage-table {
  width: 100%;
}

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

.package-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.usage-progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 12px;
}

.usage-progress-cell :deep(.el-progress) {
  flex: 1;
}

.usage-progress-cell :deep(.el-progress__text) {
  font-size: 13px !important;
  font-weight: 600;
  min-width: 45px;
  text-align: right;
}

.percentage-text {
  font-size: 13px;
  font-weight: 600;
}

.token-cell {
  display: flex;
  align-items: baseline;
  gap: 4px;
  justify-content: center;
}

.token-value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.token-unit {
  font-size: 12px;
  color: #909399;
}

.amount-cell {
  font-weight: 600;
  color: #f56c6c;
}

.creation-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.creation-icon {
  font-size: 14px;
  color: #67c23a;
}

.expire-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.expire-icon {
  font-size: 14px;
  color: #909399;
}

.remark-cell {
  color: #606266;
  font-size: 13px;
}

.no-data {
  color: #c0c4cc;
}

/* 空状态 */
.empty-container {
  padding: 40px 0;
}

/* 分页容器 */
.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;
      }
    }
  }
}

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

  .header-icon {
    font-size: 20px;
    padding: 6px;
  }

  .header-title {
    font-size: 16px;
  }

  .header-subtitle {
    font-size: 12px;
  }

  .header-right {
    width: 100%;
  }

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

  /* 移动端筛选工具栏 */
  .filter-toolbar {
    padding: 16px;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .filter-item {
    width: 100%;
  }

  .date-picker,
  .free-select {
    width: 100%;
  }

  .filter-actions {
    margin-left: 0;
    display: flex;
    gap: 8px;
  }

  .filter-actions .el-button {
    flex: 1;
  }

  /* 移动端分页 */
  .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;
    }
  }
}

/* 平板适配 */
@media (min-width: 769px) and (max-width: 1024px) {
  .filter-row {
    gap: 10px;
  }

  .search-input {
    width: 180px;
  }

  .date-picker {
    width: 280px;
  }
}
</style>
