<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑福利屋入口' : '新增福利屋入口'"
    width="550px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入名称"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="图片" prop="image">
        <ImageUpload
          v-model="formData.image"
          placeholder="点击上传图片"
          url-placeholder="或输入图片URL"
          tip="支持 jpg、png、gif、webp 格式，最大 10MB"
        />
      </el-form-item>

      <el-form-item label="跳转链接" prop="url">
        <el-input
          v-model="formData.url"
          placeholder="请输入跳转链接"
          maxlength="500"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="9999"
          placeholder="请输入排序值"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="formData.status"
          :active-value="1"
          :inactive-value="0"
          inline-prompt
          active-text="开启"
          inactive-text="关闭"
        />
      </el-form-item>
    </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 ImageUpload from '@/components/ImageUpload/index.vue'
import {
  createWelfareHouse,
  updateWelfareHouse,
  type WelfareHouseResponse,
  type WelfareHouseCreateRequest
} from '@/api/business/welfarehouse'

const props = defineProps<{
  modelValue: boolean
  welfareHouse: WelfareHouseResponse | 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
  image: string
  url: string
  sort: number
  status: number
}

const formData = reactive<FormDataType>({
  name: '',
  image: '',
  url: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请输入图片URL', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入跳转链接', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.welfareHouse) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        name: props.welfareHouse.name || '',
        image: props.welfareHouse.image || '',
        url: props.welfareHouse.url || '',
        sort: props.welfareHouse.sort || 0,
        status: props.welfareHouse.status
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    image: '',
    url: '',
    sort: 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: WelfareHouseCreateRequest = {
      name: formData.name,
      image: formData.image,
      url: formData.url,
      sort: formData.sort,
      status: formData.status
    }

    if (props.isEdit && props.welfareHouse) {
      await updateWelfareHouse(props.welfareHouse.id, {
        ...submitData,
        status: formData.status
      })
      ElMessage.success('更新成功')
    } else {
      await createWelfareHouse(submitData)
      ElMessage.success('创建成功')
    }

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

<style scoped>
/* No custom styles needed - ImageUpload component handles styling */
</style>
