<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '编辑奖品等级' : '添加奖品等级'"
    width="600px"
    @update:model-value="$emit('update:modelValue', $event)"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="等级名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入等级名称，如：A赏、B赏" />
      </el-form-item>

      <el-form-item label="概率" prop="pro">
        <el-input-number
          v-model="formData.pro"
          :min="0"
          :max="100"
          :precision="2"
          :step="0.1"
          placeholder="请输入概率"
        />
        <span class="unit">%</span>
      </el-form-item>

      <el-form-item label="等级颜色" prop="color">
        <el-color-picker v-model="formData.color" show-alpha />
        <el-input v-model="formData.color" placeholder="#FFFFFF" style="width: 120px; margin-left: 10px" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="等级图标" prop="imgUrl">
            <ImageUpload
              v-model="formData.imgUrl"
              placeholder="点击上传图标"
              :width="80"
              :height="80"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特殊图片" prop="specialImgUrl">
            <ImageUpload
              v-model="formData.specialImgUrl"
              placeholder="点击上传特殊图片"
              :width="80"
              :height="80"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :max="9999" />
        <span class="hint">数值越小越靠前</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? '保存' : '添加' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import ImageUpload from '@/components/ImageUpload/index.vue'
import {
  getPrizeLevel,
  createPrizeLevel,
  updatePrizeLevel,
  type PrizeLevelCreateRequest
} from '@/api/business/prizelevel'

interface Props {
  modelValue: boolean
  levelId?: number | null
}

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

const formRef = ref<FormInstance>()
const loading = ref(false)
const submitting = ref(false)

const isEdit = computed(() => !!props.levelId)

const formData = reactive<PrizeLevelCreateRequest>({
  title: '',
  pro: 0,
  imgUrl: '',
  color: '',
  specialImgUrl: '',
  sort: 0
})

const rules: FormRules = {
  title: [
    { required: true, message: '请输入等级名称', trigger: 'blur' }
  ],
  pro: [
    { required: true, message: '请输入概率', trigger: 'blur' }
  ]
}

// 监听弹窗打开
watch(() => props.modelValue, async (val) => {
  if (val) {
    if (props.levelId) {
      await loadLevelData()
    } else {
      resetForm()
    }
  }
})

// 加载等级数据
const loadLevelData = async () => {
  if (!props.levelId) return
  loading.value = true
  try {
    const res = await getPrizeLevel(props.levelId)
    Object.assign(formData, {
      title: res.data.title,
      pro: res.data.pro,
      imgUrl: res.data.imgUrl || '',
      color: res.data.color || '',
      specialImgUrl: res.data.specialImgUrl || '',
      sort: res.data.sort
    })
  } catch (error) {
    console.error('获取等级详情失败:', error)
    ElMessage.error('获取等级详情失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.title = ''
  formData.pro = 0
  formData.imgUrl = ''
  formData.color = ''
  formData.specialImgUrl = ''
  formData.sort = 0
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

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

  submitting.value = true
  try {
    if (isEdit.value && props.levelId) {
      await updatePrizeLevel(props.levelId, formData)
      ElMessage.success('保存成功')
    } else {
      await createPrizeLevel(formData)
      ElMessage.success('添加成功')
    }
    emit('success')
    handleClose()
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.unit {
  margin-left: 8px;
  color: #909399;
}

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