<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`奖品管理 - ${goodsTitle}`"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchTitle"
          placeholder="搜索奖品标题"
          clearable
          style="width: 200px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <div class="toolbar-right">
        <el-button type="warning" @click="handleDesignatedPrize">
          <el-icon><Star /></el-icon>奖品配置
        </el-button>
        <el-button type="primary" @click="handleAdd()">
          <el-icon><Plus /></el-icon>新增奖品
        </el-button>
        <!-- 概率统计（无限赏等类型显示） -->
        <div v-if="showProbability" class="probability-stats">
          <el-tag :type="probabilityTotal > 100 ? 'danger' : probabilityTotal === 100 ? 'success' : 'warning'">
            概率总和: {{ probabilityTotal.toFixed(2) }}%
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 奖品表格 -->
    <el-table
      :data="filteredPrizeList"
      v-loading="loading"
      border
      stripe
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      max-height="500px"
      default-expand-all
    >
      <!-- ID -->
      <el-table-column prop="id" label="ID" width="70" align="center" />

      <!-- 奖品图片 -->
      <el-table-column label="图片" width="80" align="center">
        <template #default="{ row }">
          <el-image
            :src="row.imgUrl"
            :preview-src-list="[row.imgUrl]"
            fit="cover"
            style="width: 50px; height: 50px; border-radius: 4px;"
            preview-teleported
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <!-- 奖品名称 -->
      <el-table-column prop="title" label="奖品名称" min-width="150">
        <template #default="{ row }">
          <div class="prize-title">
            <el-tag v-if="row.goodsListId > 0" type="info" size="small" style="margin-right: 4px;">子</el-tag>
            {{ row.title }}
          </div>
        </template>
      </el-table-column>

      <!-- 奖品等级 -->
      <el-table-column label="等级" width="80" align="center">
        <template #default="{ row }">
          <el-tag 
            :type="getLevelTagType(row)" 
            size="small"
            :style="row.shangColor ? { backgroundColor: row.shangColor, borderColor: row.shangColor, color: '#fff' } : {}"
          >
            {{ getLevelLabel(row) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 奖品分类 -->
      <el-table-column label="分类" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getCategoryTagType(row.goodsType)" size="small">
            {{ getCategoryLabel(row.goodsType) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 售价 -->
      <el-table-column prop="price" label="售价" width="100" align="right">
        <template #default="{ row }">
          <span class="money">¥{{ row.price?.toFixed(2) || '0.00' }}</span>
        </template>
      </el-table-column>

      <!-- 回收价 -->
      <el-table-column prop="money" label="回收价" width="100" align="right">
        <template #default="{ row }">
          <span class="text-muted">¥{{ row.money?.toFixed(2) || '0.00' }}</span>
        </template>
      </el-table-column>

      <!-- 数量列（一番赏等类型显示） -->
      <el-table-column v-if="showQuantity" label="数量" width="100" align="center">
        <template #default="{ row }">
          <div class="stock-info">
            <div>总: {{ row.stock || 0 }}</div>
            <div class="text-muted">剩: {{ row.surplusStock || 0 }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- 概率列（无限赏等类型显示） -->
      <el-table-column v-if="showProbability" prop="realPro" label="概率(%)" width="100" align="center">
        <template #default="{ row }">
          <span :class="{ 'text-danger': row.realPro > 50 }">{{ row.realPro?.toFixed(2) || '0.00' }}%</span>
        </template>
      </el-table-column>

      <!-- 赠送倍率（翻倍赏显示） -->
      <el-table-column v-if="showDoubling" prop="doubling" label="赠送倍率" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.doubling > 1" type="success" size="small">x{{ row.doubling }}</el-tag>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>

      <!-- 是否领主（领主赏显示） -->
      <el-table-column v-if="showLingzhu" label="领主" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isLingzhu === 1" type="warning" size="small">领主</el-tag>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>

      <!-- 排序 -->
      <el-table-column label="排序" width="100" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.sort"
            :min="0"
            :max="9999"
            size="small"
            controls-position="right"
            @change="(val: number) => handleSortChange(row, val)"
            style="width: 80px"
          />
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <!-- 宝箱类型奖品显示"子奖品"按钮 -->
          <el-button 
            v-if="row.goodsType === PrizeCategory.BaoXiang && row.goodsListId === 0" 
            type="success" 
            link 
            @click="handleAddChildPrize(row)"
          >
            <el-icon><FolderAdd /></el-icon>子奖品
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 奖品新增弹窗 -->
    <PrizeAddDialog
      v-model="addDialogVisible"
      :goods-id="goodsId"
      :goods-type="goodsType"
      :parent-prize-id="currentParentPrizeId"
      :parent-prize-title="currentParentPrizeTitle"
      @success="handleRefresh"
    />

    <!-- 奖品编辑弹窗 -->
    <PrizeEditDialog
      v-model="editDialogVisible"
      :prize-id="currentPrizeId"
      :goods-type="goodsType"
      :prize-data="currentPrizeData"
      @success="handleRefresh"
    />

    <!-- 指定中奖配置弹窗 -->
    <DesignatedPrizeDialog
      v-model="designatedPrizeDialogVisible"
      :goods-id="goodsId"
      :goods-title="goodsTitle"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Picture, Edit, Delete, Star, FolderAdd } from '@element-plus/icons-vue'
import { 
  getGoodsPrizes, 
  updatePrize,
  deletePrize,
  PrizeCategory,
  PrizeCategoryLabels,
  type PrizeItem 
} from '@/api/business/goods'
import { getPrizeColumnConfig } from '../config/typeFieldConfig'
import PrizeAddDialog from './PrizeAddDialog.vue'
import PrizeEditDialog from './PrizeEditDialog.vue'
import DesignatedPrizeDialog from './DesignatedPrizeDialog.vue'

interface Props {
  modelValue: boolean
  goodsId: number
  goodsType: number
  goodsTitle: string
}

const props = defineProps<Props>()

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<PrizeItem[]>([])
const searchTitle = ref('')
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const designatedPrizeDialogVisible = ref(false)
const currentPrizeId = ref(0)
const currentPrizeData = ref<PrizeItem | undefined>(undefined)
const currentParentPrizeId = ref(0)  // 当前父奖品ID（添加子奖品时使用）
const currentParentPrizeTitle = ref('')  // 当前父奖品标题

// 根据盒子类型判断显示哪些列（使用统一配置）
const prizeColumnConfig = computed(() => getPrizeColumnConfig(props.goodsType))

const showQuantity = computed(() => prizeColumnConfig.value.showQuantity)
const showProbability = computed(() => prizeColumnConfig.value.showProbability)
const showDoubling = computed(() => prizeColumnConfig.value.showGiftMultiple)
const showLingzhu = computed(() => prizeColumnConfig.value.showIsLingzhu)

// 概率总和（只计算父奖品）
const probabilityTotal = computed(() => {
  return prizeList.value
    .filter(item => (item.goodsListId ?? 0) === 0)
    .reduce((sum, item) => sum + (item.realPro || 0), 0)
})

// 构建树形结构的奖品列表
const buildTreePrizeList = (prizes: PrizeItem[]): PrizeItem[] => {
  // 分离父奖品和子奖品
  const parentPrizes = prizes.filter(p => (p.goodsListId ?? 0) === 0)
  const childPrizes = prizes.filter(p => (p.goodsListId ?? 0) > 0)
  
  // 为每个父奖品添加子奖品
  return parentPrizes.map(parent => {
    const children = childPrizes.filter(child => child.goodsListId === parent.id)
    return {
      ...parent,
      children: children.length > 0 ? children : undefined
    }
  })
}

// 过滤后的奖品列表（树形结构）
const filteredPrizeList = computed(() => {
  const treeList = buildTreePrizeList(prizeList.value)
  
  if (!searchTitle.value) return treeList
  
  const keyword = searchTitle.value.toLowerCase()
  
  // 搜索时展平显示，包括匹配的子奖品
  return treeList.filter(item => {
    const parentMatch = item.title.toLowerCase().includes(keyword)
    const childMatch = item.children?.some(child => 
      child.title.toLowerCase().includes(keyword)
    )
    return parentMatch || childMatch
  }).map(item => {
    if (item.children) {
      return {
        ...item,
        children: item.children.filter(child => 
          child.title.toLowerCase().includes(keyword) || 
          item.title.toLowerCase().includes(keyword)
        )
      }
    }
    return item
  })
})

// 获取奖品列表
const fetchPrizes = async () => {
  if (!props.goodsId) return
  
  loading.value = true
  try {
    const res = await getGoodsPrizes(props.goodsId)
    prizeList.value = res.data || []
  } catch (error: any) {
    ElMessage.error(error.message || '获取奖品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索由 computed 自动处理
}

// 重置
const handleReset = () => {
  searchTitle.value = ''
}

// 新增奖品（可选父奖品ID）
const handleAdd = (parentPrizeId: number = 0, parentPrizeTitle: string = '') => {
  currentParentPrizeId.value = parentPrizeId
  currentParentPrizeTitle.value = parentPrizeTitle
  addDialogVisible.value = true
}

// 添加宝箱子奖品
const handleAddChildPrize = (parentPrize: PrizeItem) => {
  handleAdd(parentPrize.id, parentPrize.title)
}

// 指定中奖配置
const handleDesignatedPrize = () => {
  designatedPrizeDialogVisible.value = true
}

// 编辑奖品
const handleEdit = (row: PrizeItem) => {
  currentPrizeId.value = row.id
  currentPrizeData.value = row
  editDialogVisible.value = true
}

// 删除奖品
const handleDelete = async (row: PrizeItem) => {
  const hasChildren = row.children && row.children.length > 0
  const confirmMsg = hasChildren 
    ? `确定要删除宝箱奖品 "${row.title}" 及其所有子奖品吗？删除后不可恢复！`
    : `确定要删除奖品 "${row.title}" 吗？删除后不可恢复！`
  
  try {
    await ElMessageBox.confirm(confirmMsg, '删除确认', { type: 'warning' })
    await deletePrize(row.id)
    ElMessage.success('删除成功')
    fetchPrizes()
  } catch {
    // 取消操作
  }
}

// 排序变更
const handleSortChange = async (row: PrizeItem, sort: number) => {
  try {
    await updatePrize(row.id, {
      title: row.title,
      imgUrl: row.imgUrl,
      imgUrlDetail: row.imgUrlDetail || undefined,
      stock: row.stock,
      price: row.price,
      money: row.money,
      scMoney: row.scMoney,
      realPro: row.realPro,
      goodsType: row.goodsType,
      sort: sort,
      shangId: row.shangId || undefined,
      rewardNum: row.rewardNum,
      rank: row.rank,
      giveMoney: row.giveMoney,
      cardNo: row.cardNo || undefined,
      type: row.type,
      lianJiType: row.lianJiType,
      rewardId: row.rewardId || undefined,
      doubling: row.doubling,
      isLingzhu: row.isLingzhu,
    })
    ElMessage.success('排序更新成功')
  } catch (error: any) {
    ElMessage.error(error.message || '排序更新失败')
    fetchPrizes()
  }
}

// 刷新列表
const handleRefresh = () => {
  fetchPrizes()
}

// 获取等级标签
const getLevelLabel = (row: PrizeItem): string => {
  // 优先使用后端返回的等级名称
  if (row.shangTitle) {
    return row.shangTitle
  }
  // 兜底：如果没有等级信息，显示"无等级"
  return '无等级'
}

// 获取等级标签类型
const getLevelTagType = (row: PrizeItem): string => {
  // 如果有等级颜色，使用自定义样式
  if (row.shangColor) {
    return ''  // 返回空，使用自定义颜色
  }
  // 兜底
  return 'info'
}

// 获取分类标签
const getCategoryLabel = (type: number): string => {
  // 优先使用枚举映射
  const label = PrizeCategoryLabels[type]
  if (label) return label
  // 兜底处理
  const fallbackLabels: Record<number, string> = {
    0: '未分类',
    1: '现货',
    2: '预售',
    3: '货币',
    4: '宝箱',
  }
  return fallbackLabels[type] ?? '未知'
}

// 获取分类标签类型
const getCategoryTagType = (type: number): string => {
  const types: Record<number, string> = {
    [PrizeCategory.XianHuo]: 'success',
    [PrizeCategory.YuShou]: 'warning',
    [PrizeCategory.HuoBi]: 'info',
    [PrizeCategory.BaoXiang]: 'danger',
  }
  return types[type] || ''
}

// 打开弹窗时加载数据
const handleOpen = () => {
  fetchPrizes()
}

const handleClose = () => {
  searchTitle.value = ''
  prizeList.value = []
  currentParentPrizeId.value = 0
  currentParentPrizeTitle.value = ''
  emit('update:modelValue', false)
}

// 监听 goodsId 变化
watch(() => props.goodsId, (newId) => {
  if (newId && props.modelValue) {
    fetchPrizes()
  }
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.probability-stats {
  margin-left: 10px;
}

.prize-title {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.money {
  color: #e6a23c;
  font-weight: 500;
}

.stock-info {
  font-size: 12px;
  line-height: 1.6;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.text-danger {
  color: #f56c6c;
  font-weight: 500;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background: #f5f7fa;
  color: #909399;
}
</style>
