<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="100px"
    >
      <el-form-item label="广告类型" prop="typeId">
        <el-select v-model="formData.typeId" placeholder="请选择广告类型" style="width: 100%">
          <el-option
            v-for="item in types"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跳转类型" prop="jumpType">
        <el-select v-model="formData.jumpType" placeholder="请选择跳转类型" style="width: 100%">
          <el-option
            v-for="(label, value) in AdvertJumpTypeLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>

      <!-- 条件显示：优惠券ID -->
      <el-form-item
        v-if="formData.jumpType === AdvertJumpType.Coupon"
        label="优惠券ID"
        prop="couponId"
      >
        <el-input-number
          v-model="formData.couponId"
          :min="1"
          placeholder="请输入优惠券ID"
          style="width: 100%"
          controls-position="right"
        />
      </el-form-item>

      <!-- 条件显示：盒子ID -->
      <el-form-item
        v-if="isBoxJumpType"
        label="盒子ID"
        prop="goodsId"
      >
        <el-input-number
          v-model="formData.goodsId"
          :min="1"
          placeholder="请输入盒子ID"
          style="width: 100%"
          controls-position="right"
        />
      </el-form-item>

      <!-- 条件显示：自定义URL -->
      <el-form-item
        v-if="formData.jumpType === AdvertJumpType.CustomUrl"
        label="跳转链接"
        prop="urlLink"
      >
        <el-input
          v-model="formData.urlLink"
          placeholder="请输入跳转链接"
          maxlength="500"
        />
      </el-form-item>

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

      <el-form-item label="排序值" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="9999"
          placeholder="请输入排序值"
          style="width: 100%"
          controls-position="right"
        />
        <div class="form-tip">数值越小排序越靠前</div>
      </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 {
  createAdvert,
  updateAdvert,
  AdvertJumpType,
  AdvertJumpTypeLabels,
  type AdvertResponse,
  type AdvertTypeResponse,
  type AdvertCreateRequest
} from '@/api/business/advert'

const props = defineProps<{
  modelValue: boolean
  advert: AdvertResponse | null
  isEdit: boolean
  types: AdvertTypeResponse[]
}>()

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 {
  typeId: number | undefined
  imageUrl: string
  sort: number
  jumpType: number
  couponId: number | undefined
  goodsId: number | undefined
  urlLink: string
}

const formData = reactive<FormDataType>({
  typeId: undefined,
  imageUrl: '',
  sort: 0,
  jumpType: AdvertJumpType.None,
  couponId: undefined,
  goodsId: undefined,
  urlLink: ''
})

// 是否为盒子跳转类型
const isBoxJumpType = computed(() => {
  return [
    AdvertJumpType.YiFanShang,
    AdvertJumpType.WuXianShang,
    AdvertJumpType.LianJiShang
  ].includes(formData.jumpType)
})

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  typeId: [
    { required: true, message: '请选择广告类型', trigger: 'change' }
  ],
  jumpType: [
    { required: true, message: '请选择跳转类型', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请输入广告图片URL', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  couponId: formData.jumpType === AdvertJumpType.Coupon
    ? [{ required: true, message: '请输入优惠券ID', trigger: 'blur' }]
    : [],
  goodsId: isBoxJumpType.value
    ? [{ required: true, message: '请输入盒子ID', trigger: 'blur' }]
    : [],
  urlLink: formData.jumpType === AdvertJumpType.CustomUrl
    ? [{ required: true, message: '请输入跳转链接', trigger: 'blur' }]
    : []
}))

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.advert) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        typeId: props.advert.typeId,
        imageUrl: props.advert.imageUrl,
        sort: props.advert.sort,
        jumpType: props.advert.jumpType,
        couponId: props.advert.couponId,
        goodsId: props.advert.goodsId,
        urlLink: props.advert.urlLink || ''
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 监听跳转类型变化，清空不相关字段
watch(() => formData.jumpType, (newType) => {
  if (newType !== AdvertJumpType.Coupon) {
    formData.couponId = undefined
  }
  if (![AdvertJumpType.YiFanShang, AdvertJumpType.WuXianShang, AdvertJumpType.LianJiShang].includes(newType)) {
    formData.goodsId = undefined
  }
  if (newType !== AdvertJumpType.CustomUrl) {
    formData.urlLink = ''
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    typeId: undefined,
    imageUrl: '',
    sort: 0,
    jumpType: AdvertJumpType.None,
    couponId: undefined,
    goodsId: undefined,
    urlLink: ''
  })
  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: AdvertCreateRequest = {
      typeId: formData.typeId!,
      imageUrl: formData.imageUrl,
      sort: formData.sort,
      jumpType: formData.jumpType,
      couponId: formData.jumpType === AdvertJumpType.Coupon ? formData.couponId : undefined,
      goodsId: isBoxJumpType.value ? formData.goodsId : undefined,
      urlLink: formData.jumpType === AdvertJumpType.CustomUrl ? formData.urlLink : undefined
    }

    if (props.isEdit && props.advert) {
      await updateAdvert(props.advert.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createAdvert(submitData)
      ElMessage.success('创建成功')
    }

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

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
