<template>
  <el-dialog v-model="dialogVisible" :title="title" width="600px" append-to-body :close-on-click-modal="false" destroy-on-close>
    <el-form
      ref="formRef"
      :model="dataForm"
      :rules="dataRules"
      label-width="120px"
    >
      <el-form-item label="荣誉" prop="honor">
        <el-input v-model="dataForm.honor" placeholder="请输入荣誉" clearable />
      </el-form-item>
      
      <el-form-item label="表彰单位" prop="honorCompany">
        <el-input v-model="dataForm.honorCompany" placeholder="请输入表彰单位" clearable />
      </el-form-item>
      
      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="dataForm.year"
          type="year"
          placeholder="请选择年份"
          format="YYYY"
          value-format="YYYY"
        />
      </el-form-item>
      
      <el-form-item label="证明材料" prop="attachment" required>
        <el-upload
          ref="uploadRef"
          :headers="headers"
          :limit="1"
          :action="url"
          :before-upload="beforeUpload"
          :on-success="materiaUploadSuccess"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :accept="'.jpg,.jpeg,.png,.pdf'"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
            <div style="margin-top: 8px;">
              <el-tag>仅支持jpg,jpeg,png,pdf后缀的文件上传</el-tag>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="dialogSubmit" type="primary" :loading="submitLoading">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { Session } from '/@/utils/storage'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/professional/professionaluser/professionalteacherhonor'
import { checkLocked } from '/@/api/professional/professionalstatuslock'

// Emits
const emit = defineEmits<{
  (e: 'refreshData'): void
}>()

// 消息提示
const message = useMessage()

// 表单引用
const formRef = ref()
const uploadRef = ref()
const submitLoading = ref(false)

// 对话框显示状态（内部管理）
const dialogVisible = ref(false)

// 表单数据
const dataForm = reactive({
  honor: '',
  honorCompany: '',
  year: '',
  materialA: '',
  attachment: '',
  state: '',
  teacherName: '',
  id: ''
})

// 表单验证规则
const dataRules = {
  honor: [
    { required: true, message: '请填写荣誉', trigger: 'blur' }
  ],
  honorCompany: [
    { required: true, message: '请填写表彰单位', trigger: 'blur' }
  ],
      year: [
        { required: true, message: '请选择年份', trigger: 'change' }
      ],
      attachment: [
    { required: true, message: '请上传证明材料', trigger: 'change' }
  ]
}

// 基础信息（简化，只保留需要的）

// 上传相关
const url = ref('')
const fileList = ref<any[]>([])

// 请求头
const headers = computed(() => {
  return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})

// 显示表单标志
const showForm = ref(false)

// 标题
const title = ref('')

// 初始化字典数据（简化，不需要加载字典数据）
const initDicData = async () => {
  // 综合表彰不需要额外的字典数据
}

// 上传前的处理
const beforeUpload = () => {
  return true
}

// 文件超出限制时的处理（当 limit=1 且已有文件时，用户上传新文件会触发此事件）
// 根据 Element Plus 官方文档，在 on-exceed 中清空文件列表并添加新文件
const handleExceed = (files: File[]) => {
  // 清空当前文件列表
  uploadRef.value?.clearFiles()
  fileList.value = []
  dataForm.attachment = ''
  
  // 等待 DOM 更新后，手动触发新文件的上传
  nextTick(() => {
    const newFile = files[0]
    if (newFile && uploadRef.value) {
      // 通过 input 元素手动触发文件上传
      const input = uploadRef.value.$el?.querySelector('input[type="file"]')
      if (input) {
        // 创建新的 DataTransfer 对象并添加新文件
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(newFile)
        input.files = dataTransfer.files
        
        // 触发 change 事件，让 Element Plus 自动处理上传
        const changeEvent = new Event('change', { bubbles: true })
        input.dispatchEvent(changeEvent)
      }
    }
  })
}

// 文件上传成功
const materiaUploadSuccess = (response: any, file: any) => {
  if (response.data && response.data.code === "-1") {
    message.error("当前不允许上传文件")
    // 上传失败，移除文件
    fileList.value = []
    uploadRef.value?.clearFiles()
    return
  }
  if (response.data && response.data.url) {
    dataForm.attachment = response.data.url
    // 更新文件列表，确保显示新上传的文件（替换旧文件）
    fileList.value = [{ 
      name: file.name || '证明材料', 
      url: response.data.url,
      uid: file.uid || Date.now(),
      status: 'success'
    }]
    formRef.value?.clearValidate('attachment')
  }
}

// 文件删除处理
const handleRemove = () => {
  dataForm.attachment = ''
  fileList.value = []
  formRef.value?.clearValidate('attachment')
}

// 打开对话框
const openDialog = async (row?: any) => {
  // 新增模式：先检查是否锁定
  if (!row || !row.id) {
    try {
      const lockResponse = await checkLocked('remix')
      if (lockResponse.data) {
        message.warning("新增功能已锁定，暂不允许操作")
        return
      }
    } catch (error) {
      // 错误处理已在数据请求层统一处理，此处不需要提示
      return
    }
  }
  
  // 根据是否有 row 设置不同的表单数据
  if (row && row.id) {
    // 编辑模式：使用传入的数据
    title.value = row.teacherName || ''
    Object.assign(dataForm, {
      honor: row.honor || '',
      honorCompany: row.honorCompany || '',
      year: row.year ? String(row.year) : '',
      materialA: row.materialA || '',
      attachment: row.attachment || '',
      state: row.state || '',
      teacherName: row.teacherName || '',
      id: row.id || ''
    })
    // 回显已上传的证明材料
    fileList.value = dataForm.attachment
      ? [{ name: '证明材料', url: dataForm.attachment }]
      : []
  } else {
    // 新增模式：重置为空
    title.value = '新增综合表彰'
    Object.assign(dataForm, {
      honor: '',
      honorCompany: '',
      year: '',
      attachment: '',
      state: '',
      teacherName: '',
      id: ''
    })
    fileList.value = []
  }
  
  // 公共设置：每次打开都重置上传地址
  url.value = `/professional/file/teacherAboutInfoUpload?type=4`
  
  // 公共操作：加载字典数据并显示对话框
  await initDicData()
  showForm.value = true
  dialogVisible.value = true
}

// 提交表单
const dialogSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 统一使用 addObj 接口（新增和编辑都使用同一个接口）
        await addObj(dataForm)
        message.success(dataForm.id ? "修改成功" : "提交成功")
        dialogVisible.value = false
        emit('refreshData')
      } catch (error: any) {
        // 错误处理已在数据请求层统一处理，此处不需要提示
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 初始化方法（保持兼容性）
const init = () => {
  // 新版本不再需要初始化配置
}

// 暴露方法
defineExpose({
  openDialog,
  init
})
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style>
