<template>
  <div class="matchmaker-form-container">
    <h2 class="page-title">{{ isEdit ? '编辑红娘' : '添加红娘' }}</h2>
    
    <el-card shadow="never">
      <el-form ref="formRef" :model="form" :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="form.avatarUrl" :src="form.avatarUrl" 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="form.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.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="form.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="form.birthDate" 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="form.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="form.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-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="城市" prop="cityId">
              <el-select v-model="form.cityId" placeholder="请选择城市" filterable style="width: 100%">
                <el-option
                  v-for="city in cityList"
                  :key="city.id"
                  :label="city.name"
                  :value="city.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="个人简介" prop="profile">
          <el-input v-model="form.profile" type="textarea" :rows="4" placeholder="请输入个人简介" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.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 cityList = ref([])

const form = reactive({
  matchmakerId: null,
  avatarUrl: '',
  realName: '',
  phone: '',
  gender: 1,
  birthDate: null,
  matchmakerType: 2,
  level: 1,
  profile: '',
  status: 1,
  cityId: null
})

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 loadCityList = async () => {
  try {
    const response = await request.get(API_ENDPOINTS.CITY_LIST)
    if (response.code === 200) {
      cityList.value = response.data || []
    }
  } catch (error) {
    console.error('加载城市列表失败:', error)
    ElMessage.error('加载城市列表失败')
  }
}

const loadDetail = async (id) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.MATCHMAKER_DETAIL}/${id}`)
    if (response.code === 200) {
      const data = response.data
      // 将后端返回的 snake_case 字段映射到前端的驼峰字段
      form.matchmakerId = data.matchmaker_id || data.matchmakerId || null
      form.avatarUrl = data.avatar_url || data.avatarUrl || ''
      form.realName = data.real_name || data.realName || ''
      form.phone = data.phone || ''
      form.gender = data.gender !== undefined ? data.gender : 1
      form.birthDate = data.birth_date || data.birthDate || null
      form.matchmakerType = data.matchmaker_type !== undefined ? data.matchmaker_type : 2
      form.level = data.level !== undefined ? data.level : 1
      form.profile = data.profile || ''
      form.status = data.status !== undefined ? data.status : 1
      form.cityId = data.city_id || data.cityId || null
    }
  } 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确保响应式更新
      form.avatarUrl = imageUrl
      
      // 强制触发视图更新
      setTimeout(() => {
        console.log('当前form.avatarUrl值:', form.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
    
    // 将前端的驼峰字段转换为后端期望的 snake_case 格式
    const submitData = {
      matchmaker_id: form.matchmakerId,
      avatar_url: form.avatarUrl,
      real_name: form.realName,
      phone: form.phone,
      gender: form.gender,
      birth_date: form.birthDate,
      matchmaker_type: form.matchmakerType,
      level: form.level,
      profile: form.profile,
      status: form.status,
      city_id: form.cityId
    }
    
    const url = isEdit.value ? `${API_ENDPOINTS.MATCHMAKER_UPDATE}/${form.matchmakerId}` : API_ENDPOINTS.MATCHMAKER_CREATE
    const method = isEdit.value ? 'put' : 'post'
    
    const response = await request[method](url, submitData)
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      router.push('/matchmaker/list')
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  // 加载城市列表
  loadCityList()
  
  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>

