<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="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入任务标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="任务分类" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择任务分类"
          style="width: 100%"
        >
          <el-option
            v-for="(label, value) in TaskTypeLabels"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="任务次数" prop="number">
        <el-input-number
          v-model="formData.number"
          :min="1"
          :precision="0"
          placeholder="请输入完成次数要求"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="欧气值" prop="zNumber">
        <el-input-number
          v-model="formData.zNumber"
          :min="1"
          :precision="0"
          placeholder="请输入奖励欧气值"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :precision="0"
          placeholder="请输入排序值"
          style="width: 100%"
        />
      </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 {
  createTask,
  updateTask,
  TaskTypeLabels,
  type TaskResponse,
  type TaskCreateRequest,
  type TaskUpdateRequest
} from '@/api/business/task'

const props = defineProps<{
  modelValue: boolean
  task: TaskResponse | 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 | undefined
  cate: number
  number: number
  zNumber: number
  sort: number
}

const formData = reactive<FormDataType>({
  title: '',
  type: undefined,
  cate: 1,
  number: 1,
  zNumber: 1,
  sort: 0
})

// 正数验证器
const positiveNumberValidator = (_rule: any, value: any, callback: any) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('此字段为必填项'))
  } else if (typeof value !== 'number' || value <= 0) {
    callback(new Error('必须为大于0的正整数'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在1-100个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择任务分类', trigger: 'change' }
  ],
  number: [
    { required: true, validator: positiveNumberValidator, trigger: 'blur' }
  ],
  zNumber: [
    { required: true, validator: positiveNumberValidator, trigger: 'blur' }
  ],
  sort: [
    { type: 'number', min: 0, message: '排序值不能为负数', trigger: 'blur' }
  ]
}

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

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    type: undefined,
    cate: 1,
    number: 1,
    zNumber: 1,
    sort: 0
  })
  formRef.value?.resetFields()
}

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

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

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

  // 额外验证：任务次数必须大于0
  if (formData.number <= 0) {
    ElMessage.error('任务次数必须大于0')
    return
  }

  // 额外验证：欧气值必须大于0
  if (formData.zNumber <= 0) {
    ElMessage.error('欧气值必须大于0')
    return
  }

  submitLoading.value = true
  try {
    const submitData: TaskCreateRequest | TaskUpdateRequest = {
      title: formData.title,
      type: formData.type!,
      cate: formData.cate,
      number: formData.number,
      zNumber: formData.zNumber,
      sort: formData.sort
    }

    if (props.isEdit && props.task) {
      await updateTask(props.task.id, submitData as TaskUpdateRequest)
      ElMessage.success('更新成功')
    } else {
      await createTask(submitData as TaskCreateRequest)
      ElMessage.success('创建成功')
    }

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

<style scoped>
</style>
