<template>
  <div class="success-case-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 v-if="isEdit" label="案例编号">
          <el-input v-model="form.caseNo" disabled placeholder="系统自动生成" />
        </el-form-item>
        
        <el-alert v-if="!isEdit" type="info" :closable="false" style="margin-bottom: 20px;">
          <template #title>
            案例编号将在创建时自动生成（格式：SC + 年月日 + 序号）
          </template>
        </el-alert>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="男方昵称" prop="maleUserNickname">
              <el-input v-model="form.maleUserNickname" placeholder="请输入男方昵称（脱敏）" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="女方昵称" prop="femaleUserNickname">
              <el-input v-model="form.femaleUserNickname" placeholder="请输入女方昵称（脱敏）" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="案例引言" prop="quote">
          <el-input v-model="form.quote" placeholder="请输入案例引言/金句" maxlength="200" show-word-limit />
        </el-form-item>
        
        <el-form-item label="案例故事" prop="story">
          <el-input v-model="form.story" type="textarea" :rows="8" placeholder="请输入案例故事，详细描述两人的相识、相知、相爱过程" maxlength="2000" show-word-limit />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结婚日期" prop="marriageDate">
              <el-date-picker v-model="form.marriageDate" type="date" placeholder="选择结婚日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红娘姓名" prop="matchmakerName">
              <el-input v-model="form.matchmakerName" placeholder="请输入红娘姓名" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="状态" prop="caseStatus">
          <el-radio-group v-model="form.caseStatus">
            <el-radio :value="1">展示中</el-radio>
            <el-radio :value="0">隐藏</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 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 form = reactive({
  caseId: null,
  caseNo: '',
  maleUserNickname: '',
  femaleUserNickname: '',
  quote: '',
  story: '',
  marriageDate: null,
  matchmakerName: '',
  caseStatus: 1
})

const rules = {
  maleUserNickname: [
    { required: true, message: '请输入男方昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  femaleUserNickname: [
    { required: true, message: '请输入女方昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  quote: [
    { required: true, message: '请输入案例引言', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  story: [
    { required: true, message: '请输入案例故事', trigger: 'blur' },
    { min: 20, max: 2000, message: '长度在 20 到 2000 个字符', trigger: 'blur' }
  ]
}

const loadDetail = async (id) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.CASE_DETAIL}/${id}`)
    
    console.log('案例详情响应:', response)
    
    if (response.code === 200) {
      Object.assign(form, response.data)
      console.log('加载的表单数据:', form)
    } else {
      ElMessage.error(response.message || '加载详情失败')
    }
  } catch (error) {
    console.error('加载详情失败:', error)
    ElMessage.error('加载详情失败：' + (error.message || '网络错误'))
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const url = isEdit.value ? `${API_ENDPOINTS.CASE_UPDATE}/${form.caseId}` : API_ENDPOINTS.CASE_CREATE
    const method = isEdit.value ? 'put' : 'post'
    
    console.log('提交表单:', { url, method, data: form })
    
    const response = await request[method](url, form)
    
    console.log('提交响应:', response)
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      router.push('/success-case/list')
    } else {
      ElMessage.error(response.message || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败:', error)
      ElMessage.error('提交失败：' + (error.message || '请检查表单'))
    }
  } finally {
    submitLoading.value = false
  }
}

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

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

