<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`${level?.title || '权益等级'} - 奖品管理`"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增奖品
      </el-button>
    </div>

    <!-- 奖品列表 -->
    <el-table :data="prizeList" v-loading="loading" border stripe max-height="400">
      <el-table-column prop="id" label="ID" width="60" align="center" />
      
      <el-table-column label="优惠券名称" min-width="150">
        <template #default="{ row }">
          {{ row.coupon?.title || row.title || '-' }}
        </template>
      </el-table-column>
      
      <el-table-column label="数量" width="80" align="center">
        <template #default="{ row }">
          {{ row.quantity ?? 1 }}张
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="130" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>

    <!-- 奖品表单弹窗 -->
    <QyLevelPrizeFormDialog
      v-model="prizeFormVisible"
      :level-id="level?.id"
      :prize="currentPrize"
      :is-edit="isEdit"
      @success="fetchPrizes"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import QyLevelPrizeFormDialog from './QyLevelPrizeFormDialog.vue'
import {
  getQyLevelPrizes,
  deleteQyLevelPrize,
  type QyLevelResponse,
  type QyLevelPrizeResponse,
  type QyLevelPrizeListRequest
} from '@/api/business/qylevel'

const props = defineProps<{
  modelValue: boolean
  level: QyLevelResponse | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 列表数据
const loading = ref(false)
const prizeList = ref<QyLevelPrizeResponse[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<QyLevelPrizeListRequest>({
  page: 1,
  pageSize: 10,
  type: undefined,
  keyword: undefined
})

// 奖品表单弹窗控制
const prizeFormVisible = ref(false)
const isEdit = ref(false)
const currentPrize = ref<QyLevelPrizeResponse | null>(null)

// 获取奖品列表
const fetchPrizes = async () => {
  if (!props.level?.id) return
  
  loading.value = true
  try {
    const res = await getQyLevelPrizes(props.level.id, queryParams)
    prizeList.value = res.data.list
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

// 监听弹窗打开
watch(() => props.modelValue, (visible) => {
  if (visible && props.level) {
    // 重置查询参数
    queryParams.page = 1
    queryParams.type = undefined
    queryParams.keyword = undefined
    fetchPrizes()
  }
})

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

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

// 新增奖品
const handleAdd = () => {
  isEdit.value = false
  currentPrize.value = null
  prizeFormVisible.value = true
}

// 编辑奖品
const handleEdit = (row: QyLevelPrizeResponse) => {
  isEdit.value = true
  currentPrize.value = { ...row }
  prizeFormVisible.value = true
}

// 删除奖品
const handleDelete = async (row: QyLevelPrizeResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除该奖品吗？删除后不可恢复！`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteQyLevelPrize(row.id)
    ElMessage.success('删除成功')
    fetchPrizes()
  } catch {
    // 取消操作
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
}

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