<template>
  <div class="app-container token-log-page">
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="queryParams" label-width="68px">
        <el-form-item label="时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="x"
            :shortcuts="dateShortcuts"
            style="width: 360px"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="模型名称">
          <el-input
            v-model="queryParams.model_name"
            placeholder="请输入模型名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <!-- 统计卡片 -->
      <div class="stat-bar">
        <div class="stat-item">
          <div class="stat-label">
            <el-icon><Coin /></el-icon>
            <span>消费总额</span>
          </div>
          <div class="stat-value">
            ¥<span class="stat-num">{{ formatQuotaToYuan(stat.quota) }}</span>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 消费 -->
        <el-tab-pane label="消费" name="consume">
          <el-table
            v-loading="loading"
            :data="consumeList"
            :max-height="620"
            border
            stripe
          >
            <el-table-column label="时间" align="center" prop="created_at" width="180">
              <template #default="scope">
                <span>{{ formatTime(scope.row.created_at) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="模型" align="center" prop="model_name" min-width="180" />
            <el-table-column label="计费方式" align="center" width="100">
              <template #default="scope">
                <el-tag :type="getBillingType(scope.row.other) === '按次' ? 'success' : 'primary'" size="small">
                  {{ getBillingType(scope.row.other) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="输入" align="center" prop="prompt_tokens" width="120">
              <template #default="scope">
                <span>{{ scope.row.prompt_tokens || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="输出" align="center" prop="completion_tokens" width="120">
              <template #default="scope">
                <span>{{ scope.row.completion_tokens || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="花费" align="center" prop="quota" width="120">
              <template #default="scope">
                <span class="cost">¥{{ formatQuotaToYuan(scope.row.quota) }}</span>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无消费记录" />
            </template>
          </el-table>
        </el-tab-pane>

        <!-- 充值 -->
        <el-tab-pane label="充值" name="recharge">
          <el-table
            v-loading="loading"
            :data="rechargeList"
            :max-height="620"
            border
            stripe
          >
            <el-table-column label="时间" align="center" prop="created_at" width="220">
              <template #default="scope">
                <span>{{ formatTime(scope.row.created_at) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="充值金额" align="center" prop="amount" min-width="180">
              <template #default="scope">
                <span class="recharge-amount">¥{{ extractRechargeAmount(scope.row.content) }}</span>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无充值记录" />
            </template>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.p"
        v-model:limit="queryParams.page_size"
        @pagination="refresh"
      />
    </el-card>
  </div>
</template>

<script setup name="TokenLog">
import { ref, reactive, onMounted, computed } from 'vue'
import { getTokenLog, getTokenLogStat } from '@/api/console'
import { parseTime } from '@/utils/ruoyi'
import { Coin, Wallet } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const activeTab = ref('consume')
const loading = ref(false)
const consumeList = ref([])
const rechargeList = ref([])
const total = ref(0)

const stat = reactive({
  quota: 0
})

// 近30天快捷选项
const dateShortcuts = [
  {
    text: '近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 默认近30天
function getDefaultDateRange() {
  const end = Math.floor(Date.now() / 1000)
  const start = end - 3600 * 24 * 30
  return [start * 1000, end * 1000] // 毫秒，给 el-date-picker 用
}

const dateRange = ref(getDefaultDateRange())

const queryParams = reactive({
  p: 1,
  page_size: 10,
  type: 2, // 2=消费
  model_name: '',
  start_timestamp: '',
  end_timestamp: ''
})

// 当前 tab 对应的 type
const currentType = computed(() => (activeTab.value === 'consume' ? 2 : 1))

/** 构造带时间戳的请求参数 */
function buildParams() {
  return {
    ...queryParams,
    type: currentType.value,
    start_timestamp: dateRange.value && dateRange.value[0]
      ? Math.floor(dateRange.value[0] / 1000)
      : '',
    end_timestamp: dateRange.value && dateRange.value[1]
      ? Math.floor(dateRange.value[1] / 1000)
      : ''
  }
}

/** 加载统计（消费/充值总额） */
function loadStat() {
  const params = buildParams()
  getTokenLogStat(params).then((res) => {
    const data = res.data || {}
    stat.quota = Number(data.quota || 0)
    stat.rpm = Number(data.rpm || 0)
    stat.tpm = Number(data.tpm || 0)
  }).catch(() => {
    // 静默失败，保留旧值
  })
}

/** 加载列表 */
function loadList() {
  loading.value = true
  const params = buildParams()
  queryParams.type = currentType.value

  getTokenLog(params).then((res) => {
    const data = res.data || {}
    const items = data.items || []
    if (activeTab.value === 'consume') {
      consumeList.value = items
    } else {
      rechargeList.value = items
    }
    total.value = data.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 统一刷新：列表 + 统计 */
function refresh() {
  loadList()
  loadStat()
}

/** 切换 tab */
function handleTabChange(name) {
  queryParams.p = 1
  queryParams.type = name === 'consume' ? 2 : 1
  refresh()
}

/** 时间变化 */
function handleDateChange() {
  queryParams.p = 1
  refresh()
}

/** 搜索 */
function handleQuery() {
  queryParams.p = 1
  refresh()
}

/** 重置 */
function resetQuery() {
  dateRange.value = getDefaultDateRange()
  queryParams.model_name = ''
  queryParams.p = 1
  refresh()
}

/** 格式化时间戳（秒） */
function formatTime(ts) {
  if (!ts) return '-'
  return parseTime(ts * 1000, '{y}-{m}-{d} {h}:{i}:{s}')
}

/** quota 转 元（1元 = 500000 quota） */
function formatQuotaToYuan(quota) {
  if (quota === null || quota === undefined) return '0.000000'
  const num = Number(quota)
  if (isNaN(num)) return '0.000000'
  return (num / 500000).toFixed(6)
}

/** 从 content 提取充值金额
 *  示例："通过兑换码充值 ¥0.010000 额度，兑换码ID 8" -> "0.01"
 */
function extractRechargeAmount(content) {
  if (!content) return '0.00'
  const match = content.match(/¥\s*(\d+(?:\.\d+)?)/)
  if (!match) return '0.00'
  return Number(match[1]).toFixed(2)
}

/** 解析计费方式：按次(model_ratio===0 && model_price!==-1) vs 按量 */
function getBillingType(other) {
  if (!other) return '-'
  try {
    const info = typeof other === 'string' ? JSON.parse(other) : other
    const ratio = Number(info.model_ratio)
    const price = Number(info.model_price)
    if (isNaN(ratio) || isNaN(price)) return '-'
    return ratio === 0 && price !== -1 ? '按次' : '按量'
  } catch {
    return '-'
  }
}

onMounted(() => {
  refresh()
})
</script>

<style lang="scss" scoped>
.token-log-page {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
  .filter-card {
    border-radius: 8px;
    margin-bottom: 16px;

    :deep(.el-card__body) {
      padding-bottom: 0;
    }
  }

  .table-card {
    border-radius: 8px;

    :deep(.el-tabs__header) {
      margin-bottom: 16px;
    }

    :deep(.el-tabs__nav-wrap::after) {
      height: 1px;
    }
  }

  .cost {
    color: #f56c6c;
    font-weight: 500;
  }

  .recharge-amount {
    color: #67c23a;
    font-weight: 500;
  }

  .pagination-container {
    background-color: transparent;
    margin-top: 16px;
    text-align: right;
  }

  .stat-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }

  .stat-item {
    flex: 1;
    min-width: 240px;
    padding: 18px 22px;
    background: linear-gradient(135deg, #fff5f5 0%, #fff 100%);
    border: 1px solid #fde2e2;
    border-radius: 10px;
    transition: all 0.2s;
  }

  .stat-label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;

    .el-icon {
      font-size: 18px;
      color: #f56c6c;
    }
  }

  .stat-value {
    font-size: 16px;
    color: #f56c6c;
    line-height: 1.2;

    .stat-num {
      font-size: 30px;
      font-weight: 700;
      margin-left: 2px;
    }
  }
}
</style>
