<template>
  <div class="personnel-form">
    <el-card>
      <template #header>
        <span>{{ isEdit ? '编辑人才' : '添加人才' }}</span>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" v-loading="loading">
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="照片（2寸以内）">
              <el-upload
                class="photo-uploader-inline"
                :show-file-list="false"
                :auto-upload="false"
                accept="image/*"
                :on-change="handlePhotoChange"
              >
                <img v-if="photoPreview" :src="photoPreview" class="photo-preview-small" />
                <el-button v-else size="small" type="primary">
                  <el-icon><Upload /></el-icon>
                  选择照片
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部职别" prop="position">
              <el-input v-model="form.position" placeholder="请输入部职别" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="军衔" prop="rank">
              <el-input v-model="form.rank" placeholder="请输入军衔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="士兵证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入士兵证号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="专业岗位" prop="professionalTitle">
              <el-input v-model="form.professionalTitle" placeholder="请输入专业岗位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-select v-model="form.politicalStatus" placeholder="请选择政治面貌" style="width: 100%">
                <el-option label="中共党员" value="中共党员" />
                <el-option label="共青团员" value="共青团员" />
                <el-option label="群众" value="群众" />
                <el-option label="民主党派" value="民主党派" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文化程度" prop="educationLevel">
              <el-select v-model="form.educationLevel" placeholder="请选择文化程度" style="width: 100%">
                <el-option label="初中" value="初中" />
                <el-option label="高中" value="高中" />
                <el-option label="中专" value="中专" />
                <el-option label="大专" value="大专" />
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="form.ethnicity" placeholder="请输入民族" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="籍贯" prop="hometown">
              <el-input v-model="form.hometown" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="month"
                placeholder="选择出生年月"
                style="width: 100%"
                format="YYYY年MM月"
                value-format="YYYY-MM"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入伍年月" prop="enlistmentDate">
              <el-date-picker
                v-model="form.enlistmentDate"
                type="month"
                placeholder="选择入伍年月"
                style="width: 100%"
                format="YYYY年MM月"
                value-format="YYYY-MM"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="特长" prop="specialty">
              <el-input v-model="form.specialty" placeholder="请输入特长" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="参加培训、集训情况" prop="trainingParticipation">
          <el-input v-model="form.trainingParticipation" type="textarea" :rows="3" placeholder="请输入参加培训、集训情况" />
        </el-form-item>
        
        <el-form-item label="取得成绩（成果）" prop="achievements">
          <el-input v-model="form.achievements" type="textarea" :rows="3" placeholder="可手填取得成绩（成果）" />
          <el-upload
            class="achievement-uploader"
            :show-file-list="true"
            :auto-upload="false"
            :file-list="documentList"
            :on-change="handleDocumentChange"
            :on-remove="handleDocumentRemove"
            accept="image/*"
            multiple
            style="margin-top: 10px"
          >
            <el-button size="small">
              <el-icon><Upload /></el-icon>
              上传成绩照片
            </el-button>
            <template #tip>
              <div class="upload-tip">可上传成绩相关照片</div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules, UploadFile } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import { personnelApi } from '@/api'

const route = useRoute()
const router = useRouter()

const isEdit = computed(() => !!route.params.id)
const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)
const photoFile = ref<File | null>(null)
const photoPreview = ref('')
const documentFile = ref<File | null>(null)
const documentList = ref<UploadFile[]>([])

const form = reactive({
  name: '',
  unit: '',
  position: '',
  rank: '',
  gender: '男',
  age: 25,
  idNumber: '',
  professionalTitle: '',
  politicalStatus: '',
  educationLevel: '',
  ethnicity: '',
  hometown: '',
  birthDate: '',
  enlistmentDate: '',
  specialty: '',
  trainingParticipation: '',
  achievements: ''
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度应在2-50个字符之间', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' },
    { max: 100, message: '单位长度不能超过100个字符', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入部职别', trigger: 'blur' },
    { max: 100, message: '部职别长度不能超过100个字符', trigger: 'blur' }
  ],
  rank: [
    { required: true, message: '请输入军衔', trigger: 'blur' },
    { max: 50, message: '军衔长度不能超过50个字符', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入士兵证号', trigger: 'blur' },
    { max: 50, message: '士兵证号长度不能超过50个字符', trigger: 'blur' }
  ],
  professionalTitle: [
    { required: true, message: '请输入专业岗位', trigger: 'blur' },
    { max: 100, message: '专业岗位长度不能超过100个字符', trigger: 'blur' }
  ],
  politicalStatus: [
    { required: true, message: '请选择政治面貌', trigger: 'change' },
    { max: 50, message: '政治面貌长度不能超过50个字符', trigger: 'change' }
  ],
  educationLevel: [
    { required: true, message: '请选择文化程度', trigger: 'change' },
    { max: 50, message: '文化程度长度不能超过50个字符', trigger: 'change' }
  ],
  ethnicity: [
    { required: true, message: '请输入民族', trigger: 'blur' },
    { max: 50, message: '民族长度不能超过50个字符', trigger: 'blur' }
  ],
  hometown: [
    { required: true, message: '请输入籍贯', trigger: 'blur' },
    { max: 200, message: '籍贯长度不能超过200个字符', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生年月', trigger: 'change' },
    { max: 20, message: '出生年月格式不正确', trigger: 'change' }
  ],
  enlistmentDate: [
    { required: true, message: '请选择入伍年月', trigger: 'change' },
    { max: 20, message: '入伍年月格式不正确', trigger: 'change' }
  ],
  specialty: [
    { required: true, message: '请输入特长', trigger: 'blur' },
    { max: 200, message: '特长长度不能超过200个字符', trigger: 'blur' }
  ],
  trainingParticipation: [
    { required: false, message: '请输入参加培训、集训情况', trigger: 'blur' },
    { max: 1000, message: '参加培训、集训情况长度不能超过1000个字符', trigger: 'blur' }
  ],
  achievements: [
    { required: false, message: '请输入取得成绩', trigger: 'blur' },
    { max: 1000, message: '取得成绩长度不能超过1000个字符', trigger: 'blur' }
  ]
}

function handlePhotoChange(file: UploadFile) {
  if (file.raw) {
    photoFile.value = file.raw
    photoPreview.value = URL.createObjectURL(file.raw)
  }
}

function handleDocumentChange(file: UploadFile) {
  if (file.raw) {
    documentFile.value = file.raw
  }
}

function handleDocumentRemove() {
  documentFile.value = null
}

async function loadPersonnel() {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const person = await personnelApi.getById(Number(route.params.id))
    form.name = person.name
    form.unit = person.unit || ''
    form.position = person.position
    form.rank = person.rank
    form.gender = person.gender || '男'
    form.age = person.age || 25
    form.idNumber = person.idNumber || ''
    form.professionalTitle = person.professionalTitle || ''
    form.politicalStatus = person.politicalStatus || ''
    form.educationLevel = person.educationLevel || ''
    form.ethnicity = person.ethnicity || ''
    form.hometown = person.hometown || ''
    form.birthDate = person.birthDate || ''
    form.enlistmentDate = person.enlistmentDate || ''
    form.specialty = person.specialty || ''
    form.trainingParticipation = person.trainingParticipation || ''
    form.achievements = person.achievements || ''
    if (person.photoPath) {
      photoPreview.value = person.photoPath
    }
  } catch {
    ElMessage.error('加载人才信息失败')
  } finally {
    loading.value = false
  }
}

async function handleSubmit() {
  console.log('点击了保存按钮')
  console.log('formRef:', formRef.value)
  
  if (!formRef.value) {
    console.error('formRef 不存在')
    return
  }
  
  // 先验证照片是否已上传（新增人员时必须上传照片）
  if (!isEdit.value && !photoFile.value && !photoPreview.value) {
    console.log('照片验证失败')
    ElMessage.error('请上传照片')
    return
  }
  
  console.log('开始表单验证')
  await formRef.value.validate(async (valid) => {
    console.log('表单验证结果:', valid)
    if (!valid) {
      ElMessage.error('请填写所有必填字段')
      return
    }
    
    const formData = new FormData()
    
    // 必填字段
    formData.append('name', form.name)
    formData.append('position', form.position)
    formData.append('rank', form.rank)
    formData.append('gender', form.gender || '男')
    formData.append('age', (form.age || 25).toString())
    
    // 可选字段 - 只有非空时才添加
    if (form.unit) formData.append('unit', form.unit)
    if (form.idNumber) formData.append('idNumber', form.idNumber)
    if (form.professionalTitle) formData.append('professionalTitle', form.professionalTitle)
    if (form.politicalStatus) formData.append('politicalStatus', form.politicalStatus)
    if (form.educationLevel) formData.append('educationLevel', form.educationLevel)
    if (form.ethnicity) formData.append('ethnicity', form.ethnicity)
    if (form.hometown) formData.append('hometown', form.hometown)
    if (form.birthDate) formData.append('birthDate', form.birthDate)
    if (form.enlistmentDate) formData.append('enlistmentDate', form.enlistmentDate)
    if (form.specialty) formData.append('specialty', form.specialty)
    if (form.trainingParticipation) formData.append('trainingParticipation', form.trainingParticipation)
    if (form.achievements) formData.append('achievements', form.achievements)
    
    if (photoFile.value) {
      formData.append('photo', photoFile.value)
    }
    
    if (documentFile.value) {
      formData.append('supportingDocuments', documentFile.value)
    }
    
    // 调试：打印FormData内容
    console.log('提交的表单数据:')
    for (let pair of formData.entries()) {
      console.log(pair[0] + ': ' + pair[1])
    }
    
    saving.value = true
    try {
      if (isEdit.value) {
        await personnelApi.update(Number(route.params.id), formData)
        ElMessage.success('更新成功')
      } else {
        await personnelApi.create(formData)
        ElMessage.success('添加成功')
      }
      router.push('/personnel')
    } catch (error: any) {
      console.error('提交错误:', error)
      console.error('错误响应:', error.response?.data)
      if (error.response?.data?.errors) {
        console.error('验证错误详情:', JSON.stringify(error.response.data.errors, null, 2))
      }
      const errorMsg = error.response?.data?.message || error.response?.data?.title || '操作失败'
      ElMessage.error(errorMsg)
    } finally {
      saving.value = false
    }
  })
}

onMounted(() => {
  loadPersonnel()
})
</script>

<style scoped>
.photo-uploader-inline {
  display: inline-block;
}

.photo-preview-small {
  width: 80px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.achievement-uploader {
  width: 100%;
}

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