<template>
  <div class="electronic-report-form">
    <el-form 
      ref="formRef"
      :model="formData" 
      :rules="formRules"
      label-width="140px"
      :validate-on-rule-change="false"
      @validate="handleValidateChange"
     >
      <!-- 出具方式选择 -->
      <el-form-item label="出具方式：" prop="deliveryType">
        <el-checkbox-group v-model="formData.deliveryType" @change="handleDeliveryTypeChange">
          <el-checkbox label="miniprogram">小程序推送</el-checkbox>
          <el-checkbox label="email">邮箱推送</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 小程序推送表单 -->
      <template v-if="formData.deliveryType.includes('miniprogram')">
        <el-form-item label="小程序推送对象：" prop="miniprogramTarget">
          <el-checkbox-group v-model="formData.miniprogramTarget">
            <el-checkbox label="main">主账号管理员</el-checkbox>
            <el-checkbox label="sub">子账号管理员</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>

      <!-- 邮箱推送表单 -->
      <template v-if="formData.deliveryType.includes('email')">
        <el-form-item label="邮箱推送：" prop="emailAddress">
          <el-input
            v-model="formData.emailAddress"
            placeholder="请输入邮箱"
            class="!w-300px"
          />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const props = defineProps<{
  modelValue: any
  isPartReport: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: any]
  'validate-change': [valid: boolean]
}>()

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

// 表单数据
const formData = reactive<any>({
  deliveryType: [],
  miniprogramTarget: [],
  emailAddress: ''
})

// 表单验证规则 - 只在提交时验证，不设置实时验证触发器
const formRules = computed((): FormRules<any> => {
  const rules: FormRules<any> = {
    deliveryType: [
      { 
        type: 'array',
        required: true, 
        message: '请选择出具方式',
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error('请选择出具方式'))
          } else {
            callback()
          }
        }
      }
    ]
  }

  // 根据出具方式动态添加验证规则（不设置trigger，只在手动验证时触发）
  if (formData.deliveryType.includes('miniprogram')) {
    rules.miniprogramTarget = [
      { 
        type: 'array',
        required: true, 
        message: '请选择小程序推送对象',
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error('请选择小程序推送对象'))
          } else {
            callback()
          }
        }
      }
    ]
  }
  
  if (formData.deliveryType.includes('email')) {
    rules.emailAddress = [
      { required: true, message: '请输入邮箱地址' },
      { 
        type: 'email', 
        message: '请输入正确的邮箱地址'
      }
    ]
  }

  return rules
})

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  Object.assign(formData, newValue)
}, { immediate: true, deep: true })

// 监听formData变化，向外emit
watch(formData, (newValue) => {
  emit('update:modelValue', { ...newValue })
}, { deep: true })

// 出具方式变化处理
const handleDeliveryTypeChange = (value: string[]) => {
  // 清空相关字段
  if (!value.includes('miniprogram')) {
    formData.miniprogramTarget = []
  }
  if (!value.includes('email')) {
    formData.emailAddress = ''
  }

  // 清除验证错误
  formRef.value?.clearValidate()
}

// 表单验证状态变化
const handleValidateChange = (prop: string, isValid: boolean, message: string) => {
  // 这里可以收集所有字段的验证状态
  // 为简化，我们在validate方法中统一处理
}

// 验证表单
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  
  try {
    await formRef.value.validate()
    emit('validate-change', true)
    return true
  } catch (error) {
    emit('validate-change', false)
    return false
  }
}

// 重置表单
const resetFields = () => {
  formRef.value?.resetFields()
}

// 清除验证
const clearValidate = () => {
  formRef.value?.clearValidate()
}

// 暴露方法
defineExpose({
  validate,
  resetFields,
  clearValidate
})
</script>

<style lang="scss" scoped>
.electronic-report-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
  
  :deep(.el-radio-group) {
    .el-radio {
      margin-right: 24px;
      margin-bottom: 8px;
    }
  }

  :deep(.el-checkbox-group) {
    .el-checkbox {
      margin-right: 24px;
      margin-bottom: 8px;
    }
  }
}
</style> 