<template>
  <div class="matchmaker-form-container">
    <h2 class="page-title">{{ isEdit ? '编辑红娘' : '添加红娘' }}</h2>
    
    <el-card shadow="never">
      <el-form ref="formRef" :model="matchMaker" :rules="rules" label-width="120px">
        <el-form-item label="红娘头像" prop="avatarUrl">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="matchMaker.avatarUrl" :src="matchMaker.avatar_url" class="avatar-preview" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式，不超过2MB</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="matchMaker.real_name" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="matchMaker.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="matchMaker.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker v-model="matchMaker.birth_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红娘类型" prop="matchmakerType">
              <el-radio-group v-model="matchMaker.matchmakerType">
                <el-radio :label="1">兼职</el-radio>
                <el-radio :label="2">全职</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级" prop="level">
              <el-select v-model="matchMaker.level" placeholder="请选择等级" style="width: 100%">
                <el-option label="青铜" :value="1" />
                <el-option label="白银" :value="2" />
                <el-option label="黄金" :value="3" />
                <el-option label="铂金" :value="4" />
                <el-option label="钻石" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="个人简介" prop="profile">
          <el-input v-model="matchMaker.profile" type="textarea" :rows="4" placeholder="请输入个人简介" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="matchMaker.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="2">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ isEdit ? '保存修改' : '添加红娘' }}
          </el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const route = useRoute()
const router = useRouter()
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

const matchMaker = reactive({
  matchmakerId: null,
  avatar_url: '',
  real_name: '',
  phone: '',
  gender: 1,
  birth_date: null,
  matchmakerType: 2,
  level: 1,
  profile: '',
  status: 1
})

const rules = {
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  matchmakerType: [{ required: true, message: '请选择红娘类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择等级', trigger: 'change' }]
}

const loadDetail = async (id) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.MATCHMAKER_DETAIL}/${id}`)
    if (response.code === 200) {
      Object.assign(matchMaker, response.data)
    }
  } catch (error) {
    console.error('加载详情失败:', error)
    ElMessage.error('加载详情失败')
  }
}

// 上传前检查
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 上传图片
const handleUpload = async (options) => {
  const formData = new FormData()
  formData.append('file', options.file)
  
  try {
    const response = await request.post(API_ENDPOINTS.UPLOAD_IMAGE, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    console.log('=== 上传图片调试信息 ===')
    console.log('完整响应:', response)
    console.log('响应数据:', response.data)
    console.log('响应code:', response.code)
    
    if (response.code === 200) {
      let imageUrl = ''
      
      // 处理不同的返回格式
      if (typeof response.data === 'string') {
        imageUrl = response.data
      } else if (response.data && response.data.url) {
        imageUrl = response.data.url
      } else if (response.data && response.data.path) {
        imageUrl = response.data.path
      } else {
        imageUrl = String(response.data)
      }
      
      console.log('解析得到的图片URL:', imageUrl)
      
      // 确保URL是完整的
      if (imageUrl && !imageUrl.startsWith('http')) {
        // 如果不是完整URL，可能需要加上前缀
        console.log('注意：URL不是完整路径，原始值:', imageUrl)
      }
      
      // 使用nextTick确保响应式更新
      matchMaker.avatarUrl = imageUrl
      
      // 强制触发视图更新
      setTimeout(() => {
        console.log('当前form.avatarUrl值:', matchMaker.avatarUrl)
      }, 100)
      
      ElMessage.success('头像上传成功')
    } else {
      console.error('上传失败，响应:', response)
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    console.error('上传异常:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const url = isEdit.value ? `${API_ENDPOINTS.MATCHMAKER_UPDATE}/${matchMaker.matchmakerId}` : API_ENDPOINTS.MATCHMAKER_CREATE
    const method = isEdit.value ? 'put' : 'post'

    console.log(matchMaker)
    const response = await request[method](url, matchMaker)
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      router.push('/matchmaker/list')
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  if (route.params.id) {
    isEdit.value = true
    loadDetail(route.params.id)
  }
})
</script>

<style scoped>
.matchmaker-form-container { padding: 0; }
.page-title { font-size: 24px; font-weight: bold; color: #333; margin: 0 0 20px 0; }

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 150px;
  height: 150px;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

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

