<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑钻石商品' : '新增钻石商品'"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商品名称" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品编号" prop="productsId">
            <el-input v-model="formData.productsId" placeholder="请输入商品编号" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品类型" prop="productsType">
            <el-input v-model="formData.productsType" placeholder="请输入商品类型" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格" prop="price">
            <el-input-number
              v-model="formData.price"
              :min="0.01"
              :max="999999"
              :precision="2"
              placeholder="请输入价格"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 赠送货币配置 -->
      <el-divider content-position="left">赠送货币配置</el-divider>
      
      <el-form-item label="基础赠送" prop="baseReward">
        <RewardConfigInput v-model="formData.baseReward" />
      </el-form-item>

      <!-- 图片配置 -->
      <el-divider content-position="left">图片配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="展示图" prop="normalImage">
            <ImageUpload
              v-model="formData.normalImage"
              placeholder="点击上传展示图"
              tip="支持 jpg、png、gif、webp 格式，最大10MB"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选中图" prop="normalSelectImage">
            <ImageUpload
              v-model="formData.normalSelectImage"
              placeholder="点击上传选中图"
              tip="支持 jpg、png、gif、webp 格式，最大10MB"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 首充配置 -->
      <el-divider content-position="left">首充配置</el-divider>
      
      <el-form-item label="是否首充" prop="isFirst">
        <el-radio-group v-model="formData.isFirst">
          <el-radio :value="0">否</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 首充相关字段（条件显示） -->
      <template v-if="formData.isFirst === 1">
        <el-form-item label="首充额外赠送" prop="firstBonusReward">
          <RewardConfigInput v-model="formData.firstBonusReward" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="首充展示图" prop="firstChargeImage">
              <ImageUpload
                v-model="formData.firstChargeImage"
                placeholder="点击上传首充展示图"
                tip="支持 jpg、png、gif、webp 格式，最大10MB"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首充选中图" prop="firstSelectChargeImage">
              <ImageUpload
                v-model="formData.firstSelectChargeImage"
                placeholder="点击上传首充选中图"
                tip="支持 jpg、png、gif、webp 格式，最大10MB"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 其他配置 -->
      <el-divider content-position="left">其他配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number
              v-model="formData.sortOrder"
              :min="0"
              :max="9999"
              placeholder="请输入排序值"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

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

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import RewardConfigInput from './RewardConfigInput.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import {
  createDiamondProduct,
  updateDiamondProduct,
  getDiamondMaxSort,
  type DiamondProductResponse,
  type DiamondProductCreateRequest
} from '@/api/business/diamond'

const props = defineProps<{
  modelValue: boolean
  product: DiamondProductResponse | null
  isEdit: boolean
}>()

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 formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据 - 使用内部类型确保所有字段都有值
interface FormDataType {
  name: string
  productsId: string
  productsType: string
  baseReward: string
  price: number
  isFirst: number
  firstBonusReward: string
  firstChargeImage: string
  firstSelectChargeImage: string
  normalImage: string
  normalSelectImage: string
  sortOrder: number
  status: number
}

const formData = reactive<FormDataType>({
  name: '',
  productsId: '',
  productsType: '',
  baseReward: '',
  price: 0,
  isFirst: 0,
  firstBonusReward: '',
  firstChargeImage: '',
  firstSelectChargeImage: '',
  normalImage: '',
  normalSelectImage: '',
  sortOrder: 0,
  status: 1
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '商品名称长度在1-50个字符', trigger: 'blur' }
  ],
  productsId: [
    { required: true, message: '请输入商品编号', trigger: 'blur' }
  ],
  productsType: [
    { required: true, message: '请输入商品类型', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  baseReward: [
    { required: true, message: '请配置基础赠送货币', trigger: 'change' }
  ]
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, async (visible) => {
  if (visible) {
    if (props.isEdit && props.product) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        name: props.product.name,
        productsId: props.product.productsId,
        productsType: props.product.productsType,
        baseReward: props.product.baseReward || '',
        price: props.product.price,
        isFirst: props.product.isFirst,
        firstBonusReward: props.product.firstBonusReward || '',
        firstChargeImage: props.product.firstChargeImage || '',
        firstSelectChargeImage: props.product.firstSelectChargeImage || '',
        normalImage: props.product.normalImage || '',
        normalSelectImage: props.product.normalSelectImage || '',
        sortOrder: props.product.sortOrder,
        status: props.product.status
      })
    } else {
      // 新增模式：重置数据并获取最大排序值
      resetForm()
      try {
        const res = await getDiamondMaxSort()
        formData.sortOrder = (res.data.maxSort || 0) + 1
      } catch {
        formData.sortOrder = 1
      }
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    productsId: '',
    productsType: '',
    baseReward: '',
    price: 0,
    isFirst: 0,
    firstBonusReward: '',
    firstChargeImage: '',
    firstSelectChargeImage: '',
    normalImage: '',
    normalSelectImage: '',
    sortOrder: 0,
    status: 1
  })
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

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

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitLoading.value = true
  try {
    const submitData: DiamondProductCreateRequest = {
      ...formData,
      // 非首充时清空首充相关字段
      firstBonusReward: formData.isFirst === 1 ? formData.firstBonusReward : undefined,
      firstChargeImage: formData.isFirst === 1 ? formData.firstChargeImage : undefined,
      firstSelectChargeImage: formData.isFirst === 1 ? formData.firstSelectChargeImage : undefined
    }

    if (props.isEdit && props.product) {
      await updateDiamondProduct(props.product.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createDiamondProduct(submitData)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
/* 样式已移至 ImageUpload 组件 */
</style>
