<template>
  <el-dialog
    v-model="visible"
    title="赠送卡牌"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.id }}</div>
      </div>
    </div>

    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <!-- 盒子选择 -->
      <el-form-item label="选择盒子" prop="goodsId">
        <el-select
          v-model="formData.goodsId"
          placeholder="请选择盒子"
          style="width: 100%"
          filterable
          :loading="goodsLoading"
          @change="handleGoodsChange"
        >
          <el-option
            v-for="goods in goodsList"
            :key="goods.id"
            :label="goods.title"
            :value="goods.id"
          >
            <div class="goods-option">
              <el-image
                :src="goods.imgUrl"
                style="width: 30px; height: 30px; margin-right: 8px"
                fit="cover"
              />
              <span>{{ goods.title }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 奖品选择 -->
      <el-form-item label="选择奖品" prop="goodsListId">
        <el-select
          v-model="formData.goodsListId"
          placeholder="请先选择盒子"
          style="width: 100%"
          filterable
          :loading="prizeLoading"
          :disabled="!formData.goodsId"
        >
          <el-option
            v-for="prize in prizeList"
            :key="prize.id"
            :label="prize.title"
            :value="prize.id"
          >
            <div class="prize-option">
              <el-image
                :src="prize.imgUrl"
                style="width: 30px; height: 30px; margin-right: 8px"
                fit="cover"
              />
              <span class="prize-title">{{ prize.title }}</span>
              <el-tag :type="getPrizeLevelType(prize.level)" size="small" class="prize-level">
                {{ prize.levelText }}
              </el-tag>
              <span class="prize-price">¥{{ prize.price?.toFixed(2) }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 选中奖品详情 -->
      <el-form-item label="奖品详情" v-if="selectedPrize">
        <div class="prize-detail">
          <el-image
            :src="selectedPrize.imgUrl"
            style="width: 80px; height: 80px"
            fit="cover"
          />
          <el-descriptions :column="2" border size="small" class="prize-desc">
            <el-descriptions-item label="奖品名称">{{ selectedPrize.title }}</el-descriptions-item>
            <el-descriptions-item label="奖品等级">
              <el-tag :type="getPrizeLevelType(selectedPrize.level)" size="small">
                {{ selectedPrize.levelText }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="奖品价值">¥{{ selectedPrize.price?.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="剩余库存">{{ selectedPrize.stock ?? '不限' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form-item>

      <!-- 赠送数量 -->
      <el-form-item label="赠送数量" prop="quantity">
        <el-input-number
          v-model="formData.quantity"
          :min="1"
          :max="maxQuantity"
          style="width: 200px"
        />
        <span class="quantity-tip" v-if="selectedPrize?.stock">
          （最多可赠送 {{ selectedPrize.stock }} 个）
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定赠送</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { User } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { giftCard, type UserListItem, type GiftCardRequest } from '@/api/business/user'
import { request, type ApiResponse } from '@/utils/request'

// 盒子类型定义
interface GoodsItem {
  id: number
  title: string
  imgUrl: string | null
  status: number
}

// 奖品类型定义
interface PrizeItem {
  id: number
  title: string
  imgUrl: string | null
  price: number
  level: number
  levelText: string
  stock: number | null
}

interface Props {
  modelValue: boolean
  user: UserListItem | null
}

const props = defineProps<Props>()

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

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const goodsLoading = ref(false)
const prizeLoading = ref(false)
const goodsList = ref<GoodsItem[]>([])
const prizeList = ref<PrizeItem[]>([])

const formData = reactive<GiftCardRequest>({
  goodsId: 0,
  goodsListId: 0,
  quantity: 1
})

// 表单验证规则
const formRules: FormRules = {
  goodsId: [{ required: true, message: '请选择盒子', trigger: 'change' }],
  goodsListId: [{ required: true, message: '请选择奖品', trigger: 'change' }],
  quantity: [
    { required: true, message: '请输入赠送数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}

// 选中的奖品
const selectedPrize = computed(() => {
  return prizeList.value.find(p => p.id === formData.goodsListId)
})

// 最大可赠送数量
const maxQuantity = computed(() => {
  if (selectedPrize.value?.stock) {
    return selectedPrize.value.stock
  }
  return 999
})

// 获取奖品等级标签类型
const getPrizeLevelType = (level: number) => {
  const types: Record<number, string> = {
    1: 'danger',   // 特等奖
    2: 'warning',  // 一等奖
    3: 'success',  // 二等奖
    4: 'info',     // 三等奖
    5: ''          // 普通奖
  }
  return types[level] || ''
}

// 加载盒子列表
const loadGoodsList = async () => {
  goodsLoading.value = true
  try {
    const res: ApiResponse<{ list: GoodsItem[] }> = await request({
      url: '/admin/business/goods',
      method: 'get',
      params: { status: 1, page: 1, pageSize: 1000 }
    })
    goodsList.value = res.data?.list || []
  } catch (error) {
    console.error('加载盒子列表失败', error)
    goodsList.value = []
  } finally {
    goodsLoading.value = false
  }
}

// 加载奖品列表
const loadPrizeList = async (goodsId: number) => {
  if (!goodsId) {
    prizeList.value = []
    return
  }

  prizeLoading.value = true
  try {
    const res: ApiResponse<{ list: PrizeItem[] }> = await request({
      url: `/admin/business/goods/${goodsId}/prizes`,
      method: 'get',
      params: { page: 1, pageSize: 1000 }
    })
    prizeList.value = res.data?.list || []
  } catch (error) {
    console.error('加载奖品列表失败', error)
    prizeList.value = []
  } finally {
    prizeLoading.value = false
  }
}

// 盒子选择变化
const handleGoodsChange = (goodsId: number) => {
  formData.goodsListId = 0
  formData.quantity = 1
  loadPrizeList(goodsId)
}

// 对话框打开时
const handleOpen = () => {
  formData.goodsId = 0
  formData.goodsListId = 0
  formData.quantity = 1
  prizeList.value = []
  formRef.value?.resetFields()
  loadGoodsList()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!props.user) {
    ElMessage.warning('用户信息不存在')
    return
  }

  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    await giftCard(props.user.id, formData)
    ElMessage.success('赠送成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '赠送失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听奖品选择变化，重置数量
watch(() => formData.goodsListId, () => {
  formData.quantity = 1
})
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

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

.goods-option {
  display: flex;
  align-items: center;
}

.prize-option {
  display: flex;
  align-items: center;
  width: 100%;
}

.prize-title {
  flex: 1;
}

.prize-level {
  margin: 0 8px;
}

.prize-price {
  color: #e6a23c;
  font-size: 12px;
}

.prize-detail {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.prize-desc {
  flex: 1;
}

.quantity-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
}
</style>
