<template>
  <div class="group-buy-type-container">
    <el-card class="header-card">
      <div class="header-actions">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增类型</el-button>
        <el-select v-model="searchTag" placeholder="请选择标签" style="width: 180px; margin-left: 12px" @change="handleTagChange">
          <el-option v-for="tag in tagList" :key="tag" :label="tag" :value="tag" />
        </el-select>
        <el-input v-model="searchKey" placeholder="关键词搜索" style="width: 200px; margin-left: 12px" clearable :disabled="!searchTag" @keyup.enter="fetchList" />
        <el-button type="info" icon="Refresh" @click="fetchList" :loading="loading" :disabled="!searchTag" style="margin-left: 12px">刷新</el-button>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-empty v-if="!searchTag" description="请先选择标签" />
      <template v-else>
      <el-table :data="tableData" v-loading="loading" stripe border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="价格" width="120">
          <template #default="{ row }">¥{{ (row.price / 100).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column label="续费价格" width="120">
          <template #default="{ row }">¥{{ (row.renewPrice / 100).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="maxPerson" label="拼团人数" width="100" align="center" />
        <el-table-column prop="tag" label="标签" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.tag" type="info">{{ row.tag }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="180">
          <template #default="{ row }">{{ row.expireTime ? formatTime(row.expireTime) : '永久' }}</template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" @size-change="fetchList" @current-change="fetchList" />
      </div>
      </template>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑拼团类型' : '新增拼团类型'" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <div class="unit-input-row">
            <el-input-number v-model="form.price" :min="0" style="flex:1" />
            <span class="unit-text">分</span>
          </div>
        </el-form-item>
        <el-form-item label="续费价格" prop="renewPrice">
          <div class="unit-input-row">
            <el-input-number v-model="form.renewPrice" :min="0" style="flex:1" />
            <span class="unit-text">分</span>
          </div>
        </el-form-item>
        <el-form-item label="拼团人数" prop="maxPerson">
          <el-input-number v-model="form.maxPerson" :min="2" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-select v-model="form.tag" placeholder="选择标签" filterable allow-create style="width: 100%">
            <el-option v-for="tag in tagList" :key="tag" :label="tag" :value="tag" />
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker v-model="form.expireTime" type="datetime" placeholder="选择过期时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注字段">
          <div class="note-fields-container">
            <el-button type="primary" size="small" @click="addNoteField" style="margin-bottom: 10px">+ 添加字段</el-button>
            <el-table :data="form.noteFields" border size="small" v-if="form.noteFields.length">
              <el-table-column label="名称" min-width="120">
                <template #default="{ row }">
                  <el-input v-model="row.label" placeholder="如：内存" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="默认值" min-width="120">
                <template #default="{ row }">
                  <el-input v-model="row.defaultValue" placeholder="如：20GB" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="60" align="center">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" link @click="removeNoteField($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGroupBuyTypeList, getGroupBuyTypeTags, addGroupBuyType, updateGroupBuyType, deleteGroupBuyType } from '@/api/groupBuy'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const searchKey = ref('')
const searchTag = ref('')
const tagList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

const form = reactive({ id: '', name: '', price: 0, renewPrice: 0, maxPerson: 5, tag: '', expireTime: null, noteFields: [] })
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  renewPrice: [{ required: true, message: '请输入续费价格', trigger: 'blur' }],
  maxPerson: [{ required: true, message: '请输入拼团人数', trigger: 'blur' }],
  tag: [{ required: true, message: '请选择标签', trigger: 'change' }],
  expireTime: [{ required: true, message: '请选择过期时间', trigger: 'change' }]
}

// 添加备注字段
const addNoteField = () => {
  form.noteFields.push({ label: '', defaultValue: '' })
}

// 删除备注字段
const removeNoteField = (index) => {
  form.noteFields.splice(index, 1)
}

const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await getGroupBuyTypeList({ page: page.value, count: pageSize.value, key: searchKey.value || undefined, tag: searchTag.value || undefined })
    console.log("获取拼团类型列表数据：",res)
    if (res.code === 200) {
      tableData.value = res.data?.data || []
      total.value = res.data?.all_count || 0
    } else {
      ElMessage.error(res.data.message || '获取列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('网络错误')
  } finally {
    loading.value = false
  }
}

const fetchTags = async () => {
  try {
    const res = await getGroupBuyTypeTags()
    if (res.code === 200) tagList.value = res.data || []
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 标签变化时重新获取列表
const handleTagChange = (tag) => {
  page.value = 1
  searchKey.value = ''
  tableData.value = []
  total.value = 0
  if (tag) {
    fetchList()
  }
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(form, { id: '', name: '', price: 0, renewPrice: 0, maxPerson: 5, tag: '', expireTime: null, noteFields: [] })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  let noteFields = []
  try {
    noteFields = row.note ? JSON.parse(row.note) : []
  } catch { noteFields = [] }
  Object.assign(form, { id: row.id, name: row.name, price: row.price, renewPrice: row.renewPrice, maxPerson: row.maxPerson, tag: row.tag || '', expireTime: row.expireTime || null, noteFields })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const noteJson = JSON.stringify(form.noteFields.filter(f => f.label))
      const data = {
        name: form.name,
        price: String(form.price),
        renew_price: String(form.renewPrice),
        max_person: String(form.maxPerson),
        tag: form.tag,
        expire_time: form.expireTime ? Math.floor(new Date(form.expireTime).getTime() / 1000) : 0,
        note: noteJson
      }
      if (isEdit.value) data.id = String(form.id)
      const res = isEdit.value ? await updateGroupBuyType(data) : await addGroupBuyType(data)
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
        dialogVisible.value = false
        fetchList()
        fetchTags()
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('网络错误')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该拼团类型吗？', '确认删除', { type: 'warning' })
    const res = await deleteGroupBuyType(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchList()
      fetchTags()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  } catch { /* 取消 */ }
}

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

<style scoped>
.group-buy-type-container { padding: 20px; }
.header-card { margin-bottom: 20px; }
.header-actions { display: flex; align-items: center; }
.table-card { box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); }
.pagination-wrapper { margin-top: 20px; display: flex; justify-content: flex-end; }
.note-fields-container { width: 100%; }
.unit-input-row { display: flex; align-items: center; gap: 6px; width: 100%; }
.unit-text { font-size: 13px; color: #606266; flex-shrink: 0; white-space: nowrap; }
</style>
