<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>盒子管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增盒子
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <GoodsSearchForm 
        :goods-types="goodsTypes"
        @search="handleSearch" 
        @reset="handleReset" 
      />

      <!-- 盒子表格 -->
      <GoodsTable
        :data="goodsList"
        :loading="loading"
        :total="total"
        :page="queryParams.page"
        :page-size="queryParams.pageSize"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
        @command="handleCommand"
        @status-change="handleStatusChange"
        @sort-change="handleSortChange"
      />
    </el-card>

    <!-- 盒子新增弹窗 -->
    <GoodsAddDialog
      v-model="addDialogVisible"
      :goods-types="goodsTypes"
      @success="fetchData"
    />

    <!-- 盒子编辑弹窗 -->
    <GoodsEditDialog
      v-model="editDialogVisible"
      :goods-id="currentGoodsId"
      :goods-types="goodsTypes"
      @success="fetchData"
    />

    <!-- 奖品列表弹窗 -->
    <PrizeListDialog
      v-model="prizeDialogVisible"
      :goods-id="currentGoodsId"
      :goods-type="currentGoodsType"
      :goods-title="currentGoodsTitle"
    />

    <!-- 扩展设置弹窗 -->
    <GoodsExtendDialog
      v-model="extendDialogVisible"
      :goods-id="currentGoodsId"
      :goods-title="currentGoodsTitle"
      @success="fetchData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import GoodsSearchForm from './components/GoodsSearchForm.vue'
import GoodsTable from './components/GoodsTable.vue'
import GoodsAddDialog from './components/GoodsAddDialog.vue'
import GoodsEditDialog from './components/GoodsEditDialog.vue'
import PrizeListDialog from './components/PrizeListDialog.vue'
import GoodsExtendDialog from './components/GoodsExtendDialog.vue'
import {
  getGoodsList,
  getGoodsTypes,
  deleteGoods,
  setGoodsStatus,
  copyGoods,
  clearGoodsLottery,
  updateGoods,
  type GoodsListQuery,
  type GoodsListItem,
  type GoodsTypeItem
} from '@/api/business/goods'

// 列表数据
const loading = ref(false)
const goodsList = ref<GoodsListItem[]>([])
const total = ref(0)
const goodsTypes = ref<GoodsTypeItem[]>([])

// 查询参数
const queryParams = reactive<GoodsListQuery>({
  page: 1,
  pageSize: 20
})

// 当前操作的盒子
const currentGoodsId = ref<number>(0)
const currentGoodsType = ref<number>(0)
const currentGoodsTitle = ref<string>('')

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const prizeDialogVisible = ref(false)
const extendDialogVisible = ref(false)

// 获取盒子列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getGoodsList(queryParams)
    goodsList.value = res.data.list
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

// 获取盒子类型列表
const fetchGoodsTypes = async () => {
  try {
    const res = await getGoodsTypes()
    goodsTypes.value = res.data.list
  } catch {
    // 忽略错误
  }
}

// 搜索
const handleSearch = (params: Partial<GoodsListQuery>) => {
  queryParams.title = undefined
  queryParams.status = undefined
  queryParams.type = undefined
  Object.assign(queryParams, params)
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.title = undefined
  queryParams.status = undefined
  queryParams.type = undefined
  queryParams.page = 1
  fetchData()
}

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

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

// 新增盒子
const handleAdd = () => {
  addDialogVisible.value = true
}

// 状态切换
const handleStatusChange = async (row: GoodsListItem, status: number) => {
  try {
    await setGoodsStatus(row.id, status)
    ElMessage.success(status === 1 ? '上架成功' : '下架成功')
    fetchData()
  } catch {
    // 恢复原状态
    fetchData()
  }
}

// 排序变更
const handleSortChange = async (row: GoodsListItem, sort: number) => {
  try {
    await updateGoods(row.id, { ...row, sort } as any)
    ElMessage.success('排序更新成功')
    fetchData()
  } catch {
    fetchData()
  }
}

// 处理操作命令
const handleCommand = async (command: string, row: GoodsListItem) => {
  currentGoodsId.value = row.id
  currentGoodsType.value = row.type
  currentGoodsTitle.value = row.title

  switch (command) {
    case 'edit':
      editDialogVisible.value = true
      break
    case 'delete':
      await handleDelete(row)
      break
    case 'copy':
      await handleCopy(row)
      break
    case 'prizes':
      prizeDialogVisible.value = true
      break
    case 'extend':
      extendDialogVisible.value = true
      break
    case 'clearLottery':
      await handleClearLottery(row)
      break
  }
}

// 删除盒子
const handleDelete = async (row: GoodsListItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除盒子 "${row.title}" 吗？删除后不可恢复！`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteGoods(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 复制盒子
const handleCopy = async (row: GoodsListItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要复制盒子 "${row.title}" 吗？将同时复制所有奖品配置。`,
      '复制确认',
      { type: 'info' }
    )
    const res = await copyGoods(row.id)
    ElMessage.success(`复制成功，新盒子ID: ${res.data.id}`)
    fetchData()
  } catch {
    // 取消操作
  }
}

// 清空抽奖记录
const handleClearLottery = async (row: GoodsListItem) => {
  try {
    await ElMessageBox.confirm(
      `⚠️ 危险操作！确定要清空盒子 "${row.title}" 的所有抽奖记录吗？此操作不可恢复！`,
      '危险操作确认',
      { 
        type: 'error',
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    await clearGoodsLottery(row.id)
    ElMessage.success('清空抽奖记录成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

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

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

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