<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="prize-form"
    >
      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="奖品名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入奖品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="奖品分类" prop="type">
            <el-select v-model="formData.type" placeholder="请选择分类" style="width: 100%">
              <el-option
                v-for="(label, value) in PrizeCategoryLabels"
                :key="value"
                :label="label"
                :value="Number(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="奖品等级" prop="shangId">
            <el-select v-model="formData.shangId" placeholder="请选择等级" style="width: 100%">
              <el-option
                v-for="level in prizeLevelOptions"
                :key="level.id"
                :label="level.title"
                :value="level.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序值" prop="sort">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="9999"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 价格信息 -->
      <el-divider content-position="left">价格信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="售价" prop="price">
            <el-input-number
              v-model="formData.price"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="回收价" prop="money">
            <el-input-number
              v-model="formData.money"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="市场回收价" prop="scMoney">
            <el-input-number
              v-model="formData.scMoney"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 数量/概率配置（根据盒子类型显示） -->
      <el-divider content-position="left">{{ showQuantity ? '数量配置' : '概率配置' }}</el-divider>
      
      <el-row :gutter="20">
        <!-- 数量（一番赏等类型） -->
        <el-col :span="12" v-if="showQuantity">
          <el-form-item label="奖品数量" prop="stock">
            <el-input-number
              v-model="formData.stock"
              :min="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <!-- 概率（无限赏等类型） -->
        <el-col :span="12" v-if="showProbability">
          <el-form-item label="真实概率(%)" prop="realPro">
            <el-input-number
              v-model="formData.realPro"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <!-- 赠送倍率（翻倍赏） -->
        <el-col :span="12" v-if="showDoubling">
          <el-form-item label="赠送倍率" prop="doubling">
            <el-input-number
              v-model="formData.doubling"
              :min="1"
              :max="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <!-- 是否领主（领主赏） -->
        <el-col :span="12" v-if="showLingzhu">
          <el-form-item label="是否领主">
            <el-switch
              v-model="formData.isLingzhu"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 预售时间（预售类型显示） -->
      <el-form-item v-if="formData.type === PrizeCategory.YuShou" label="预售时间">
        <el-date-picker
          v-model="formData.preSaleTime"
          type="datetime"
          placeholder="选择预售时间"
          style="width: 100%"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <!-- 赠送货币配置 -->
      <el-divider content-position="left">赠送配置</el-divider>
      
      <el-form-item label="赠送奖励">
        <PrizeRewardConfig v-model="formData.rewards" />
      </el-form-item>

      <!-- 连击赏配置 -->
      <el-row :gutter="20" v-if="showLianji">
        <el-col :span="12">
          <el-form-item label="连击类型">
            <el-select v-model="formData.lianJiType" placeholder="请选择" style="width: 100%">
              <el-option label="普通" :value="0" />
              <el-option label="连击奖品" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 图片上传 -->
      <el-divider content-position="left">图片上传</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="奖品图片" prop="imgUrl">
            <ImageUpload
              v-model="formData.imgUrl"
              placeholder="点击上传奖品图"
              tip="支持 jpg、png、gif、webp 格式，最大 10MB"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详情图片">
            <ImageUpload
              v-model="formData.imgUrlDetail"
              placeholder="点击上传详情图"
              tip="支持 jpg、png、gif、webp 格式，最大 10MB"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { 
  addPrize, 
  GoodsType, 
  PrizeCategory, 
  PrizeCategoryLabels,
  type PrizeCreateRequest 
} from '@/api/business/goods'
import { getPrizeLevelOptionsByType, type PrizeLevelOptionResponse } from '@/api/business/prizelevel'
import ImageUpload from '@/components/ImageUpload/index.vue'
import PrizeRewardConfig from './PrizeRewardConfig.vue'

interface RewardItem {
  type: number
  amount: number
}

interface Props {
  modelValue: boolean
  goodsId: number
  goodsType: number
  parentPrizeId?: number  // 父奖品ID（添加宝箱子奖品时使用）
  parentPrizeTitle?: string  // 父奖品标题
}

const props = withDefaults(defineProps<Props>(), {
  parentPrizeId: 0,
  parentPrizeTitle: ''
})

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

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

// 是否是添加子奖品模式
const isChildPrizeMode = computed(() => props.parentPrizeId > 0)

// 弹窗标题
const dialogTitle = computed(() => {
  return isChildPrizeMode.value 
    ? `新增子奖品 - ${props.parentPrizeTitle}` 
    : '新增奖品'
})

const formRef = ref<FormInstance>()
const submitting = ref(false)
const prizeLevelOptions = ref<PrizeLevelOptionResponse[]>([])

// 根据盒子类型判断显示哪些字段
const showQuantity = computed(() => {
  // 一番赏、商城赏、福利屋显示数量
  return [
    GoodsType.YiFanShang, 
    GoodsType.ShangChengShang, 
    GoodsType.FuLiWu
  ].includes(props.goodsType)
})

const showProbability = computed(() => {
  // 无限赏显示概率
  return [GoodsType.WuXianShang].includes(props.goodsType)
})

const showDoubling = computed(() => {
  // 暂无类型显示翻倍
  return false
})

const showLingzhu = computed(() => {
  // 暂无类型显示领主
  return false
})

const showLianji = computed(() => {
  // 暂无类型显示连击
  return false
})

// 表单数据
const formData = reactive({
  title: '',
  type: PrizeCategory.XianHuo,
  rank: 1,
  sort: 0,
  price: 0,
  money: 0,
  scMoney: 0,
  stock: 1,
  realPro: 0,
  doubling: 1,
  isLingzhu: 0,
  giveMoney: 0,
  rewardNum: 0,
  imgUrl: '',
  imgUrlDetail: '',
  preSaleTime: '',
  goodsType: 1,
  shangId: undefined as number | undefined,
  cardNo: '',
  lianJiType: 0,
  rewardId: '',
  rewards: [] as RewardItem[],
})

// 表单验证规则
const formRules = reactive<FormRules>({
  title: [{ required: true, message: '请输入奖品名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择奖品分类', trigger: 'change' }],
  shangId: [{ required: true, message: '请选择奖品等级', trigger: 'change' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '请上传奖品图片', trigger: 'change' }],
  stock: [{ required: true, message: '请输入奖品数量', trigger: 'blur' }],
  realPro: [{ required: true, message: '请输入概率', trigger: 'blur' }],
})

// 重置表单
const resetForm = () => {
  formData.title = ''
  formData.type = PrizeCategory.XianHuo
  formData.rank = 1
  formData.sort = 0
  formData.price = 0
  formData.money = 0
  formData.scMoney = 0
  formData.stock = 1
  formData.realPro = 0
  formData.doubling = 1
  formData.isLingzhu = 0
  formData.giveMoney = 0
  formData.rewardNum = 0
  formData.imgUrl = ''
  formData.imgUrlDetail = ''
  formData.preSaleTime = ''
  formData.goodsType = 1
  formData.shangId = undefined
  formData.cardNo = ''
  formData.lianJiType = 0
  formData.rewardId = ''
  formData.rewards = []
  formRef.value?.resetFields()
}

const handleOpen = async () => {
  resetForm()
  // 根据盒子类型加载对应的奖品等级选项
  try {
    const res = await getPrizeLevelOptionsByType(props.goodsType)
    prizeLevelOptions.value = res.data || []
  } catch (error) {
    console.error('加载奖品等级失败', error)
    prizeLevelOptions.value = []
  }
}

const handleClose = () => {
  emit('update:modelValue', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    const requestData: PrizeCreateRequest = {
      title: formData.title,
      imgUrl: formData.imgUrl,
      imgUrlDetail: formData.imgUrlDetail || undefined,
      stock: formData.stock,
      price: formData.price,
      money: formData.money,
      scMoney: formData.scMoney,
      realPro: formData.realPro,
      goodsType: formData.type,  // 奖品分类：1现货 2预售 3货币 4宝箱
      sort: formData.sort,
      shangId: formData.shangId,
      rewardNum: formData.rewardNum,
      rank: formData.rank,
      giveMoney: formData.giveMoney,
      cardNo: formData.cardNo || undefined,
      type: formData.type,  // 保持与 goodsType 一致
      lianJiType: formData.lianJiType,
      rewardId: formData.rewardId || undefined,
      doubling: formData.doubling,
      isLingzhu: formData.isLingzhu,
      goodsListId: props.parentPrizeId,  // 父奖品ID
      rewards: formData.rewards.length > 0 ? formData.rewards : undefined,
    }

    await addPrize(props.goodsId, requestData)
    ElMessage.success('创建成功')
    emit('success')
    dialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '创建失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.prize-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.el-divider__text) {
  font-weight: 500;
  color: #303133;
}
</style>
