<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户盈亏统计</span>
          <el-button type="primary" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" inline class="search-form">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userIdStr" placeholder="请输入用户ID" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="UID">
          <el-input v-model="queryParams.uid" placeholder="请输入UID" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 盈亏列表表格 -->
      <el-table :data="dataList" v-loading="loading" border stripe>
        <el-table-column label="用户信息" min-width="180">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.headimg" :size="40">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="user-detail">
                <div class="nickname">{{ row.nickname || '-' }}</div>
                <div class="uid">UID: {{ row.uid || '-' }}</div>
                <div class="mobile">{{ row.mobile || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="账户余额" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.money?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="积分" align="right" width="80">
          <template #default="{ row }">{{ row.integral || 0 }}</template>
        </el-table-column>
        <el-table-column label="钻石" align="right" width="80">
          <template #default="{ row }">{{ row.money2 || 0 }}</template>
        </el-table-column>
        <el-table-column label="订单数" align="center" width="80">
          <template #default="{ row }">{{ row.orderCount || 0 }}</template>
        </el-table-column>
        <el-table-column label="订单总额" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.orderZheTotal?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="RMB支付" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.money1?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="钻石支付" align="right" width="100">
          <template #default="{ row }">{{ row.money2Pay || 0 }}</template>
        </el-table-column>
        <el-table-column label="用户支付" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.useMoney?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发货金额" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.fhMoney?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="背包金额" align="right" width="100">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.bbMoney?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余达达券" align="right" width="100">
          <template #default="{ row }">{{ row.syMoney || 0 }}</template>
        </el-table-column>
        <el-table-column label="盈亏金额" align="right" width="120">
          <template #default="{ row }">
            <span :class="getProfitClass(row.yueMoney)">
              {{ row.yueMoney >= 0 ? '+' : '' }}¥{{ row.yueMoney?.toFixed(2) || '0.00' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="盈亏状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.profitStatus === '盈利' ? 'success' : 'danger'">
              {{ row.profitStatus || '-' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, User } from '@element-plus/icons-vue'
import { getProfitLossList, type ProfitLossListQuery, type ProfitLossItem } from '@/api/business/user'

// 列表数据
const loading = ref(false)
const dataList = ref<ProfitLossItem[]>([])
const total = ref(0)
const exportLoading = ref(false)

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 查询参数
const queryParams = reactive<ProfitLossListQuery>({
  userIdStr: undefined,
  uid: undefined,
  startTime: undefined,
  endTime: undefined,
  page: 1,
  pageSize: 20
})

// 获取盈亏状态样式类
const getProfitClass = (amount: number) => {
  if (amount > 0) return 'profit-positive'
  if (amount < 0) return 'profit-negative'
  return ''
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    const res = await getProfitLossList(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取盈亏列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.userIdStr = undefined
  queryParams.uid = undefined
  dateRange.value = null
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  queryParams.page = 1
  fetchData()
}

// 分页
const handlePageChange = (page: number) => {
  queryParams.page = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.page = 1
  fetchData()
}

// 导出Excel
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 构建导出数据
    const exportData = dataList.value.map(item => ({
      '用户ID': item.userId,
      'UID': item.uid || '',
      '昵称': item.nickname || '',
      '手机号': item.mobile || '',
      '账户余额': item.money?.toFixed(2) || '0.00',
      '积分': item.integral || 0,
      '钻石': item.money2 || 0,
      '订单数': item.orderCount || 0,
      '订单总额': item.orderZheTotal?.toFixed(2) || '0.00',
      'RMB支付': item.money1?.toFixed(2) || '0.00',
      '钻石支付': item.money2Pay || 0,
      '用户支付': item.useMoney?.toFixed(2) || '0.00',
      '发货金额': item.fhMoney?.toFixed(2) || '0.00',
      '背包金额': item.bbMoney?.toFixed(2) || '0.00',
      '剩余达达券': item.syMoney || 0,
      '盈亏金额': item.yueMoney?.toFixed(2) || '0.00',
      '盈亏状态': item.profitStatus || ''
    }))

    // 转换为CSV格式
    const headers = Object.keys(exportData[0] || {})
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(h => `"${row[h as keyof typeof row]}"`).join(','))
    ].join('\n')

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `用户盈亏统计_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    URL.revokeObjectURL(link.href)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

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

.search-form {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.nickname {
  font-weight: 500;
  color: var(--text-primary);
}

.uid, .mobile {
  font-size: 12px;
  color: var(--text-secondary);
}

.money-text {
  font-family: 'Roboto Mono', monospace;
}

.profit-positive {
  color: var(--success-color, #67c23a);
  font-weight: 600;
}

.profit-negative {
  color: var(--danger-color, #f56c6c);
  font-weight: 600;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
