<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑培训计划' : '新增培训计划'"
    width="800px"
    :confirm-loading="loading"
    :ok-button-props="{ disabled: !isFormValid }"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      auto-label-width
    >
      <a-form-item label="计划名称" field="planName">
        <a-input
          v-model="formData.planName"
          placeholder="请输入计划名称"
          :disabled="isView"
          show-word-limit
          :max-length="100"
        />
      </a-form-item>

      <a-form-item label="培训类型" field="trainingType">
        <a-select
          v-model="formData.trainingType"
          :options="trainingTypeOptions"
          placeholder="请选择培训类型"
          :disabled="isView"
        />
      </a-form-item>

      <a-form-item label="培训级别" field="trainingLevel">
        <a-select
          v-model="formData.trainingLevel"
          :options="trainingLevelOptions"
          placeholder="请选择培训级别"
          :disabled="isView"
        />
      </a-form-item>

      <a-form-item label="培训内容" field="trainingContent">
        <a-textarea
          v-model="formData.trainingContent"
          placeholder="请输入培训内容"
          :rows="4"
          :disabled="isView"
          show-word-limit
          :max-length="500"
        />
      </a-form-item>

      <a-form-item label="培训讲师" field="trainer">
        <a-input
          v-model="formData.trainer"
          placeholder="请输入培训讲师"
          :disabled="isView"
        />
      </a-form-item>

      <a-form-item label="培训地点" field="trainingLocation">
        <a-input
          v-model="formData.trainingLocation"
          placeholder="请输入培训地点"
          :disabled="isView"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="开始时间" field="startTime">
            <a-date-picker
              v-model="formData.startTime"
              show-time
              placeholder="请选择开始时间"
              style="width: 100%"
              :disabled="isView"
              :disabled-date="(current) => current && current < dayjs().startOf('day')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结束时间" field="endTime">
            <a-date-picker
              v-model="formData.endTime"
              show-time
              placeholder="请选择结束时间"
              style="width: 100%"
              :disabled="isView"
              :disabled-date="(current) => current && current < dayjs().startOf('day')"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="最大参训人数" field="maxParticipants">
        <a-input-number
          v-model="formData.maxParticipants"
          placeholder="请输入最大参训人数"
          :min="1"
          :max="1000"
          style="width: 100%"
          :disabled="isView"
        />
      </a-form-item>

      <a-form-item label="培训要求" field="requirements">
        <a-textarea
          v-model="formData.requirements"
          placeholder="请输入培训要求"
          :rows="3"
          :disabled="isView"
          show-word-limit
          :max-length="300"
        />
      </a-form-item>

      <a-form-item label="备注" field="remark">
        <a-textarea
          v-model="formData.remark"
          placeholder="请输入备注"
          :rows="3"
          :disabled="isView"
          show-word-limit
          :max-length="200"
        />
      </a-form-item>

      <!-- 调试按钮 - 仅在开发环境显示 -->
      <a-form-item v-if="isDev" label="调试">
        <a-space>
          <a-button type="dashed" size="small" @click="testFormData">
            测试表单数据绑定
          </a-button>
          <a-button type="dashed" size="small" @click="fillTestData">
            填充测试数据
          </a-button>
          <a-button size="small" type="dashed" @click="clearFormData">
            清空表单数据
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { createTrainingPlan, updateTrainingPlan } from '@/apis/training'
import type { TrainingPlanReq, TrainingPlanResp } from '@/types/training.d'

defineOptions({ name: 'TrainingPlanModal' })

const props = defineProps<Props>()

const emit = defineEmits<Emits>()

interface Props {
  visible: boolean
  planData?: TrainingPlanResp | null
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 开发环境标识
const isDev = import.meta.env.DEV

// 是否为编辑模式
const isEdit = computed(() => !!props.planData?.planId)
// 是否为查看模式
const isView = computed(() => !!props.planData?.planId && !isEdit.value)

// 表单数据类型定义
interface FormDataType {
  planName: string
  trainingType: string
  trainingLevel: string
  trainingContent: string
  trainer: string
  trainingLocation: string
  startTime: any // dayjs对象或null
  endTime: any // dayjs对象或null
  maxParticipants?: number
  requirements: string
  remark: string
  status?: string
}

// 表单数据
const formData = reactive<FormDataType>({
  planName: '',
  trainingType: '',
  trainingLevel: '',
  trainingContent: '',
  trainer: '',
  trainingLocation: '',
  startTime: null,
  endTime: null,
  maxParticipants: undefined,
  requirements: '',
  remark: '',
  status: 'DRAFT',
})

// 表单验证规则
const rules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 2, max: 100, message: '计划名称长度应在2-100个字符之间', trigger: 'blur' },
  ],
  trainingType: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
  trainingLevel: [{ required: true, message: '请选择培训级别', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (value: any, callback: any) => {
        if (value && formData.startTime && dayjs(value).isBefore(dayjs(formData.startTime))) {
          callback('结束时间不能早于开始时间')
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
  maxParticipants: [
    {
      validator: (value: any, callback: any) => {
        if (value !== undefined && value !== null) {
          if (value < 1) {
            callback('最大参训人数不能小于1')
          } else if (value > 1000) {
            callback('最大参训人数不能超过1000')
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  trainingContent: [
    { max: 500, message: '培训内容长度不能超过500个字符', trigger: 'blur' },
  ],
  requirements: [
    { max: 300, message: '培训要求长度不能超过300个字符', trigger: 'blur' },
  ],
  remark: [
    { max: 200, message: '备注长度不能超过200个字符', trigger: 'blur' },
  ],
}

// 培训类型选项
const trainingTypeOptions = [
  { label: '安全教育', value: 'SAFETY' },
  { label: '技能培训', value: 'SKILL' },
  { label: '企业文化', value: 'CULTURE' },
]
// 培训级别选项
const trainingLevelOptions = [
  { label: '现场级', value: 'SITE' },
  { label: '部门级', value: 'DEPARTMENT' },
  { label: '公司级', value: 'COMPANY' },
]

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      // eslint-disable-next-line ts/no-use-before-define
      initFormData()
    }
  },
)

// 监听计划数据变化
watch(
  () => props.planData,
  () => {
    if (props.visible) {
      // eslint-disable-next-line ts/no-use-before-define
      initFormData()
    }
  },
)

// 监听表单数据变化（调试用）
watch(
  formData,
  (newData) => {
    console.log('表单数据变化:', newData)
    console.log('表单数据详情:', {
      planName: newData.planName,
      trainingType: newData.trainingType,
      trainingLevel: newData.trainingLevel,
      startTime: newData.startTime,
      endTime: newData.endTime,
      maxParticipants: newData.maxParticipants,
      trainer: newData.trainer,
      trainingLocation: newData.trainingLocation,
      trainingContent: newData.trainingContent,
      requirements: newData.requirements,
      remark: newData.remark,
    })
  },
  { deep: true },
)

// 监听开始时间变化，自动调整结束时间
watch(
  () => formData.startTime,
  (newStartTime) => {
    console.log('开始时间变化:', newStartTime)
    if (newStartTime && formData.endTime && dayjs(formData.endTime).isBefore(dayjs(newStartTime))) {
      // 如果结束时间早于开始时间，清空结束时间
      formData.endTime = null
    }
  },
)

// 监听结束时间变化
watch(
  () => formData.endTime,
  (newEndTime) => {
    console.log('结束时间变化:', newEndTime)
  },
)

// 计算表单是否有效
const isFormValid = computed(() => {
  return formData.planName.trim()
    && formData.trainingType
    && formData.trainingLevel
    && formData.startTime
    && formData.endTime
})

// 初始化表单数据
const initFormData = () => {
  console.log('初始化表单数据，props.planData:', props.planData)

  if (props.planData) {
    // 编辑模式：填充现有数据
    Object.assign(formData, {
      planName: props.planData.planName || '',
      trainingType: props.planData.trainingType || '',
      trainingLevel: props.planData.trainingLevel || '',
      trainingContent: props.planData.trainingContent || '',
      trainer: props.planData.trainer || '',
      trainingLocation: props.planData.trainingLocation || '',
      startTime: props.planData.startTime ? dayjs(props.planData.startTime) : null,
      endTime: props.planData.endTime ? dayjs(props.planData.endTime) : null,
      maxParticipants: props.planData.maxParticipants,
      requirements: props.planData.requirements || '',
      remark: props.planData.remark || '',
      status: props.planData.status || 'DRAFT',
    })
  } else {
    // 新增模式：重置为空值
    // eslint-disable-next-line ts/no-use-before-define
    resetFormData()
  }

  console.log('初始化后的表单数据:', formData)
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    planName: '',
    trainingType: '',
    trainingLevel: '',
    trainingContent: '',
    trainer: '',
    trainingLocation: '',
    startTime: null,
    endTime: null,
    maxParticipants: undefined,
    requirements: '',
    remark: '',
    status: 'DRAFT',
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log('开始提交表单，表单数据:', formData)
    console.log('表单数据原始值:', {
      planName: formData.planName,
      trainingType: formData.trainingType,
      trainingLevel: formData.trainingLevel,
      startTime: formData.startTime,
      endTime: formData.endTime,
      maxParticipants: formData.maxParticipants,
      trainer: formData.trainer,
      trainingLocation: formData.trainingLocation,
      trainingContent: formData.trainingContent,
      requirements: formData.requirements,
      remark: formData.remark,
    })

    // 表单验证
    await formRef.value?.validate()
    loading.value = true

    // 数据验证 - 确保关键字段不为空
    if (!formData.planName?.trim()) {
      throw new Error('计划名称不能为空')
    }
    if (!formData.trainingType) {
      throw new Error('培训类型不能为空')
    }
    if (!formData.trainingLevel) {
      throw new Error('培训级别不能为空')
    }
    if (!formData.startTime) {
      throw new Error('开始时间不能为空')
    }
    if (!formData.endTime) {
      throw new Error('结束时间不能为空')
    }

    // 准备提交数据，确保字段名和格式正确
    const submitData: TrainingPlanReq = {
      planName: formData.planName.trim(),
      trainingType: formData.trainingType,
      trainingLevel: formData.trainingLevel,
      trainingContent: formData.trainingContent?.trim() || '',
      trainer: formData.trainer?.trim() || '',
      trainingLocation: formData.trainingLocation?.trim() || '',
      startTime: formData.startTime ? dayjs(formData.startTime).format('YYYY-MM-DD HH:mm:ss') : '',
      endTime: formData.endTime ? dayjs(formData.endTime).format('YYYY-MM-DD HH:mm:ss') : '',
      status: formData.status || 'DRAFT',
      maxParticipants: formData.maxParticipants || undefined,
      requirements: formData.requirements?.trim() || '',
      remark: formData.remark?.trim() || '',
    }

    console.log('提交的数据:', submitData)
    console.log('提交的数据JSON:', JSON.stringify(submitData, null, 2))

    if (isEdit.value && props.planData) {
      console.log('执行更新操作')
      await updateTrainingPlan(props.planData.planId, submitData)
      Message.success('培训计划更新成功')
    } else {
      console.log('执行创建操作')
      await createTrainingPlan(submitData)
      Message.success('培训计划创建成功')
    }

    emit('success')
    emit('update:visible', false)
  } catch (error: any) {
    console.error('提交失败:', error)

    // 更详细的错误处理
    if (error?.response?.data?.message) {
      Message.error(error.response.data.message)
    } else if (error?.message) {
      Message.error(error.message)
    } else if (typeof error === 'string') {
      Message.error(error)
    } else {
      Message.error('操作失败，请检查表单数据或稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  // 重置表单
  formRef.value?.resetFields()
  resetFormData()
  emit('update:visible', false)
}

// 测试表单数据绑定
const testFormData = () => {
  console.log('=== 表单数据绑定测试 ===')
  console.log('当前表单数据:', formData)
  console.log('当前表单数据详情:', {
    planName: formData.planName,
    trainingType: formData.trainingType,
    trainingLevel: formData.trainingLevel,
    startTime: formData.startTime,
    endTime: formData.endTime,
    maxParticipants: formData.maxParticipants,
    trainer: formData.trainer,
    trainingLocation: formData.trainingLocation,
    trainingContent: formData.trainingContent,
    requirements: formData.requirements,
    remark: formData.remark,
  })

  // 测试表单验证
  formRef.value?.validate().then(() => {
    console.log('✅ 表单验证通过')
  }).catch((errors) => {
    console.log('❌ 表单验证失败:', errors)
  })

  // 测试表单字段值
  console.log('表单字段值测试:')
  console.log('- planName:', formData.planName, typeof formData.planName)
  console.log('- trainingType:', formData.trainingType, typeof formData.trainingType)
  console.log('- trainingLevel:', formData.trainingLevel, typeof formData.trainingLevel)
  console.log('- startTime:', formData.startTime, typeof formData.startTime)
  console.log('- endTime:', formData.endTime, typeof formData.endTime)
}

// 填充测试数据
const fillTestData = () => {
  Object.assign(formData, {
    planName: '测试计划名称',
    trainingType: 'SAFETY',
    trainingLevel: 'SITE',
    trainingContent: '测试培训内容',
    trainer: '测试讲师',
    trainingLocation: '测试地点',
    startTime: dayjs('2023-10-27 10:00'),
    endTime: dayjs('2023-10-27 12:00'),
    maxParticipants: 50,
    requirements: '测试培训要求',
    remark: '测试备注',
    status: 'DRAFT',
  })
  console.log('已填充测试数据')
}

// 清空表单数据
const clearFormData = () => {
  resetFormData()
  console.log('已清空表单数据')
}

// 监听表单字段变化
const watchFormField = (fieldName: string) => {
  watch(() => formData[fieldName as keyof typeof formData], (newValue, oldValue) => {
    console.log(`字段 ${fieldName} 变化:`, { oldValue, newValue })
  })
}

// 监听所有表单字段
Object.keys(formData).forEach((fieldName) => {
  watchFormField(fieldName)
})
</script>

<style lang="scss" scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style>
