<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑悬浮球' : '新增悬浮球'"
    width="650px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题（可选）"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio :value="FloatBallType.ShowImage">展示图片</el-radio>
          <el-radio :value="FloatBallType.JumpPage">跳转页面</el-radio>
        </el-radio-group>
      </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="imageBj">
        <ImageUpload
          v-model="formData.imageBj"
          placeholder="点击上传背景图片"
          url-placeholder="或输入背景图片URL（可选）"
        />
      </el-form-item>

      <el-form-item label="详情图片" prop="imageDetails">
        <ImageUpload
          v-model="formData.imageDetails"
          placeholder="点击上传详情图片"
          url-placeholder="或输入详情图片URL（可选）"
        />
      </el-form-item>

      <!-- 条件显示：跳转链接（类型为跳转页面时显示） -->
      <el-form-item
        v-if="formData.type === FloatBallType.JumpPage"
        label="跳转链接"
        prop="linkUrl"
      >
        <el-input
          v-model="formData.linkUrl"
          placeholder="请输入跳转链接"
          maxlength="500"
        />
      </el-form-item>

      <el-divider content-position="left">位置设置</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="X轴位置" prop="positionX">
            <el-input
              v-model="formData.positionX"
              placeholder="请输入X轴位置"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Y轴位置" prop="positionY">
            <el-input
              v-model="formData.positionY"
              placeholder="请输入Y轴位置"
            />
          </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="width">
            <el-input
              v-model="formData.width"
              placeholder="请输入宽度"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="高度" prop="height">
            <el-input
              v-model="formData.height"
              placeholder="请输入高度"
            />
          </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="详情图X偏移" prop="imageDetailsX">
            <el-input
              v-model="formData.imageDetailsX"
              placeholder="请输入X偏移"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详情图Y偏移" prop="imageDetailsY">
            <el-input
              v-model="formData.imageDetailsY"
              placeholder="请输入Y偏移"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="详情图宽度" prop="imageDetailsW">
            <el-input
              v-model="formData.imageDetailsW"
              placeholder="请输入宽度"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详情图高度" prop="imageDetailsH">
            <el-input
              v-model="formData.imageDetailsH"
              placeholder="请输入高度"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">其他设置</el-divider>

      <el-form-item label="特效" prop="effect">
        <el-select v-model="formData.effect" placeholder="请选择特效" style="width: 100%">
          <el-option
            v-for="(label, value) in FloatBallEffectLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </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 {
  createFloatBall,
  updateFloatBall,
  FloatBallType,
  FloatBallEffect,
  FloatBallEffectLabels,
  type FloatBallResponse,
  type FloatBallCreateRequest
} from '@/api/business/floatball'

const props = defineProps<{
  modelValue: boolean
  floatBall: FloatBallResponse | 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 {
  title: string
  type: number
  image: string
  imageBj: string
  imageDetails: string
  linkUrl: string
  positionX: string
  positionY: string
  width: string
  height: string
  imageDetailsX: string
  imageDetailsY: string
  imageDetailsW: string
  imageDetailsH: string
  effect: number
  status: number
}

const formData = reactive<FormDataType>({
  title: '',
  type: FloatBallType.ShowImage,
  image: '',
  imageBj: '',
  imageDetails: '',
  linkUrl: '',
  positionX: '',
  positionY: '',
  width: '',
  height: '',
  imageDetailsX: '',
  imageDetailsY: '',
  imageDetailsW: '',
  imageDetailsH: '',
  effect: FloatBallEffect.None,
  status: 1
})

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  image: [
    { required: true, message: '请输入悬浮球图片URL', trigger: 'blur' }
  ],
  positionX: [
    { required: true, message: '请输入X轴位置', trigger: 'blur' }
  ],
  positionY: [
    { required: true, message: '请输入Y轴位置', trigger: 'blur' }
  ],
  width: [
    { required: true, message: '请输入宽度', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入高度', trigger: 'blur' }
  ],
  effect: [
    { required: true, message: '请选择特效', trigger: 'change' }
  ],
  linkUrl: formData.type === FloatBallType.JumpPage
    ? [{ required: true, message: '请输入跳转链接', trigger: 'blur' }]
    : []
}))

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.floatBall) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        title: props.floatBall.title || '',
        type: props.floatBall.type,
        image: props.floatBall.image,
        imageBj: props.floatBall.imageBj || '',
        imageDetails: props.floatBall.imageDetails || '',
        linkUrl: props.floatBall.linkUrl || '',
        positionX: props.floatBall.positionX,
        positionY: props.floatBall.positionY,
        width: props.floatBall.width,
        height: props.floatBall.height,
        imageDetailsX: props.floatBall.imageDetailsX || '',
        imageDetailsY: props.floatBall.imageDetailsY || '',
        imageDetailsW: props.floatBall.imageDetailsW || '',
        imageDetailsH: props.floatBall.imageDetailsH || '',
        effect: props.floatBall.effect,
        status: props.floatBall.status
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 监听类型变化，清空跳转链接
watch(() => formData.type, (newType) => {
  if (newType !== FloatBallType.JumpPage) {
    formData.linkUrl = ''
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    type: FloatBallType.ShowImage,
    image: '',
    imageBj: '',
    imageDetails: '',
    linkUrl: '',
    positionX: '',
    positionY: '',
    width: '',
    height: '',
    imageDetailsX: '',
    imageDetailsY: '',
    imageDetailsW: '',
    imageDetailsH: '',
    effect: FloatBallEffect.None,
    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: FloatBallCreateRequest = {
      title: formData.title || undefined,
      type: formData.type,
      image: formData.image,
      imageBj: formData.imageBj || undefined,
      imageDetails: formData.imageDetails || undefined,
      linkUrl: formData.type === FloatBallType.JumpPage ? formData.linkUrl : undefined,
      positionX: formData.positionX,
      positionY: formData.positionY,
      width: formData.width,
      height: formData.height,
      imageDetailsX: formData.imageDetailsX || undefined,
      imageDetailsY: formData.imageDetailsY || undefined,
      imageDetailsW: formData.imageDetailsW || undefined,
      imageDetailsH: formData.imageDetailsH || undefined,
      effect: formData.effect,
      status: formData.status
    }

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

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

<style scoped>
:deep(.el-divider__text) {
  font-size: 13px;
  color: #606266;
}
</style>
