<template>
  <div class="group-buy-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>拼团管理</span>
          <el-button type="primary" @click="showCreateDialog">创建拼团</el-button>
        </div>
      </template>

      <!-- 拼团列表 -->
      <el-table :data="groupBuyList" style="width: 100%">
        <el-table-column prop="group_buy_id" label="拼团ID" width="180" />
        <el-table-column prop="name" label="拼团名称" width="150" />
        <el-table-column prop="maxPerson" label="最大人数" width="100" />
        <el-table-column label="当前人数" width="100">
          <template #default="{ row }">
            {{ row.users?.length || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="checkGroupBuy(row.group_buy_id)">
              检查
            </el-button>
            <el-button link type="primary" @click="viewDetail(row)">
              详情
            </el-button>
            <el-button link type="danger" @click="deleteGroupBuy(row.group_buy_id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建拼团对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建拼团" width="500px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="拼团名称">
          <el-input v-model="createForm.name" placeholder="请输入拼团名称" />
        </el-form-item>
        <el-form-item label="最大人数">
          <el-input-number v-model="createForm.maxPerson" :min="2" :max="100" />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input v-model="createForm.cover" placeholder="请输入封面图片URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 拼团详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="拼团详情" width="600px">
      <el-descriptions :column="2" border v-if="currentGroupBuy">
        <el-descriptions-item label="拼团ID">
          {{ currentGroupBuy.group_buy_id }}
        </el-descriptions-item>
        <el-descriptions-item label="拼团名称">
          {{ currentGroupBuy.name }}
        </el-descriptions-item>
        <el-descriptions-item label="最大人数">
          {{ currentGroupBuy.maxPerson }}
        </el-descriptions-item>
        <el-descriptions-item label="当前人数">
          {{ currentGroupBuy.users?.length || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ currentGroupBuy.createTime }}
        </el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px">
        <h4>参与用户</h4>
        <el-table :data="currentGroupBuy?.users || []" style="width: 100%">
          <el-table-column prop="user_id" label="用户ID" width="100" />
          <el-table-column prop="user_name" label="用户名" />
          <el-table-column label="团长" width="80">
            <template #default="{ row }">
              <el-tag v-if="row.team_leader" type="success">是</el-tag>
              <el-tag v-else type="info">否</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  createGroupBuy as createGroupBuyApi,
  checkGroupBuy as checkGroupBuyApi,
  getGroupBuyList,
  getGroupBuyDetail,
  deleteGroupBuy as deleteGroupBuyApi
} from '@/api/groupBuy.js'

// 拼团列表
const groupBuyList = ref([])

// 创建对话框
const createDialogVisible = ref(false)
const creating = ref(false)
const createForm = ref({
  name: '',
  maxPerson: 5,
  cover: ''
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentGroupBuy = ref(null)

// 加载拼团列表
const loadGroupBuyList = async () => {
  try {
    const resp = await getGroupBuyList({ page: 1, pageSize: 10 })
    if (resp && resp.code === 200) {
      groupBuyList.value = resp.data || []
    }
  } catch (error) {
    console.error('加载拼团列表失败:', error)
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  createForm.value = {
    name: '',
    maxPerson: 5,
    cover: ''
  }
  createDialogVisible.value = true
}

// 创建拼团
const handleCreate = async () => {
  if (!createForm.value.name) {
    ElMessage.warning('请输入拼团名称')
    return
  }
  
  creating.value = true
  try {
    const resp = await createGroupBuyApi(createForm.value)
    console.log('创建拼团响应:', resp)
    
    if (resp && resp.code === 200) {
      ElMessage.success('创建成功')
      createDialogVisible.value = false
      
      // 将新创建的拼团添加到列表
      if (resp.data && resp.data.group_buy_id) {
        groupBuyList.value.unshift(resp.data)
      } else {
        // 如果返回的不是完整数据，重新加载列表
        await loadGroupBuyList()
      }
    } else {
      ElMessage.error(resp?.message || '创建失败')
    }
  } catch (error) {
    console.error('创建拼团失败:', error)
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

// 检查拼团
const checkGroupBuy = async (groupBuyId) => {
  try {
    const resp = await checkGroupBuyApi(groupBuyId)
    console.log('检查拼团响应:', resp)
    
    if (resp && resp.code === 200) {
      ElMessage.success(`检查结果: ${resp.data}`)
    } else {
      ElMessage.error(resp?.message || '检查失败')
    }
  } catch (error) {
    console.error('检查拼团失败:', error)
    ElMessage.error('检查失败')
  }
}

// 查看详情
const viewDetail = async (row) => {
  try {
    const resp = await getGroupBuyDetail(row.group_buy_id)
    if (resp && resp.code === 200) {
      currentGroupBuy.value = resp.data
      detailDialogVisible.value = true
    } else {
      // 如果获取详情失败，使用列表中的数据
      currentGroupBuy.value = row
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    // 使用列表中的数据
    currentGroupBuy.value = row
    detailDialogVisible.value = true
  }
}

// 删除拼团
const deleteGroupBuy = async (groupBuyId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个拼团吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const resp = await deleteGroupBuyApi(groupBuyId)
    if (resp && resp.code === 200) {
      ElMessage.success('删除成功')
      await loadGroupBuyList()
    } else {
      ElMessage.error(resp?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除拼团失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

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

<style scoped>
.group-buy-manage {
  padding: 20px;
}

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