<template>
  <div class="box-profit-container">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="盒子ID">
          <el-input v-model.number="searchForm.goodsId" placeholder="请输入盒子ID" clearable style="width: 120px" />
        </el-form-item>
        <el-form-item label="盒子名称">
          <el-input v-model="searchForm.title" placeholder="请输入盒子名称" clearable style="width: 160px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 100px">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="盒子类型">
          <el-select v-model="searchForm.type" placeholder="全部" clearable style="width: 120px">
            <el-option v-for="item in boxTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </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" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 汇总统计卡片 -->
    <el-card class="summary-card" shadow="never" v-loading="summaryLoading">
      <template #header>
        <div class="summary-header">
          <span>汇总统计</span>
          <el-button type="primary" link @click="loadSummary">刷新汇总</el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总抽奖次数</div>
            <div class="stat-value">{{ summary.totalCjCount.toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总收入</div>
            <div class="stat-value">¥{{ summary.totalIncome.toFixed(2) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总出货成本</div>
            <div class="stat-value">¥{{ summary.totalCost.toFixed(2) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总兑换金额</div>
            <div class="stat-value">¥{{ summary.totalReMoney.toFixed(2) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总发货金额</div>
            <div class="stat-value">¥{{ summary.totalFhMoney.toFixed(2) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-item">
            <div class="stat-label">总利润</div>
            <div class="stat-value" :class="{ 'text-danger': summary.isNegative, 'text-success': !summary.isNegative }">
              ¥{{ summary.totalProfit.toFixed(2) }}
              <span class="profit-rate">({{ summary.profitRate.toFixed(2) }}%)</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="盒子名称" min-width="180">
          <template #default="{ row }">
            <div class="goods-info">
              <el-image v-if="row.imgUrl" :src="row.imgUrl" fit="cover" class="goods-img" />
              <span class="goods-title">{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="类型" width="100" align="center" />
        <el-table-column prop="price" label="单价" width="80" align="right">
          <template #default="{ row }">¥{{ (row.price ?? 0).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="statusName" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">{{ row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cjCount" label="抽奖次数" width="100" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded">{{ row.cjCount }}</span>
            <el-button v-else type="primary" link size="small" @click="loadBoxStats(row)">加载</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="useMoney" label="消费金额" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded">¥{{ row.useMoney.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="scMoney" label="出货成本" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded">¥{{ row.scMoney.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="reMoney" label="兑换成本" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded">¥{{ row.reMoney.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="fhMoney" label="发货成本" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded">¥{{ row.fhMoney.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="利润" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded" :class="{ 'text-danger': row.isNegative, 'text-success': !row.isNegative }">
              ¥{{ row.profit.toFixed(2) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="profitRate" label="利润率" width="100" align="right">
          <template #default="{ row }">
            <span v-if="row.loaded" :class="{ 'text-danger': row.isNegative, 'text-success': !row.isNegative }">
              {{ row.profitRate.toFixed(2) }}%
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

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

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getBoxProfitList, getBoxStatistics, getSummaryStatistics, type BoxProfitItem, type BoxProfitSummary } from '@/api/business/statistics'

// 盒子类型选项
const boxTypes = [
  { value: 1, label: '一番赏' },
  { value: 2, label: '无限赏' },
  { value: 3, label: '擂台赏' },
  { value: 4, label: '抽卡机' },
  { value: 5, label: '福袋' },
  { value: 6, label: '幸运赏' },
  { value: 8, label: '盲盒' },
  { value: 9, label: '扭蛋' },
  { value: 10, label: '积分商城' },
  { value: 11, label: '转转赏' },
  { value: 12, label: '连击赏' },
  { value: 15, label: '福利屋' },
  { value: 16, label: '连抽赏' },
  { value: 17, label: '大乱斗' }
]

// 搜索表单
const searchForm = reactive({
  goodsId: undefined as number | undefined,
  title: '',
  status: undefined as number | undefined,
  type: undefined as number | undefined
})

const dateRange = ref<[string, string] | null>(null)

// 表格数据
const tableData = ref<BoxProfitItem[]>([])
const loading = ref(false)

// 汇总统计
const summaryLoading = ref(false)
const summary = reactive<BoxProfitSummary>({
  totalIncome: 0,
  totalCost: 0,
  totalProfit: 0,
  totalReMoney: 0,
  totalFhMoney: 0,
  totalCjCount: 0,
  profitRate: 0,
  isNegative: false
})

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

// 加载汇总统计
async function loadSummary() {
  summaryLoading.value = true
  try {
    const params: any = {}
    if (searchForm.goodsId) params.goodsId = searchForm.goodsId
    if (searchForm.title) params.title = searchForm.title
    if (searchForm.status !== undefined) params.status = searchForm.status
    if (searchForm.type) params.type = searchForm.type
    if (dateRange.value) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }

    const res = await getSummaryStatistics(params) as any
    if (res.code === 0 && res.data) {
      Object.assign(summary, res.data)
    }
  } catch (error) {
    console.error('加载汇总统计失败:', error)
    ElMessage.error('加载汇总统计失败')
  } finally {
    summaryLoading.value = false
  }
}

// 加载列表数据
async function loadData() {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    if (searchForm.goodsId) params.goodsId = searchForm.goodsId
    if (searchForm.title) params.title = searchForm.title
    if (searchForm.status !== undefined) params.status = searchForm.status
    if (searchForm.type) params.type = searchForm.type
    if (dateRange.value) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }

    const res = await getBoxProfitList(params) as any
    if (res.code === 0 && res.data) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
      
      // 自动加载每个盒子的统计数据
      loadAllBoxStats()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 批量加载所有盒子的统计数据
async function loadAllBoxStats() {
  const rows = tableData.value
  for (const row of rows) {
    if (!row.loaded) {
      loadBoxStats(row)
    }
  }
}

// 加载单个盒子的统计数据
async function loadBoxStats(row: BoxProfitItem) {
  try {
    const params: any = { goodsId: row.id }
    if (dateRange.value) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }

    const res = await getBoxStatistics(params) as any
    if (res.code === 0 && res.data) {
      const stats = res.data
      row.useMoney = stats.useMoney
      row.scMoney = stats.scMoney
      row.reMoney = stats.reMoney
      row.fhMoney = stats.fhMoney
      row.cjCount = stats.cjCount
      row.profit = stats.profit
      row.profitRate = stats.profitRate
      row.isNegative = stats.isNegative
      row.loaded = true
    }
  } catch (error) {
    console.error('加载盒子统计失败:', error)
    ElMessage.error('加载盒子统计失败')
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  loadData()
  loadSummary()
}

// 重置
function handleReset() {
  searchForm.goodsId = undefined
  searchForm.title = ''
  searchForm.status = undefined
  searchForm.type = undefined
  dateRange.value = null
  pagination.page = 1
  loadData()
  loadSummary()
}

// 分页大小变化
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 页码变化
function handleCurrentChange(page: number) {
  pagination.page = page
  loadData()
}

onMounted(() => {
  loadData()
  loadSummary()
})
</script>

<style scoped>
.box-profit-container {
  padding: 20px;
}

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

.summary-card {
  margin-bottom: 16px;
}

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

.stat-item {
  text-align: center;
  padding: 12px 0;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.profit-rate {
  font-size: 14px;
  font-weight: normal;
}

.table-card {
  margin-bottom: 16px;
}

.goods-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.goods-img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  flex-shrink: 0;
}

.goods-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.text-danger {
  color: #f56c6c;
}

.text-success {
  color: #67c23a;
}
</style>
