<template>
  <div>
    <h2>投递管理</h2>
    <el-table :data="applications" v-loading="loading" border>
      <el-table-column prop="job_title" label="职位" />
      <el-table-column label="求职者">
        <template #default="{ row }">{{ row.resume_snapshot?.name }}</template>
      </el-table-column>
      <el-table-column prop="applied_at" label="投递时间" :formatter="(r,c,v) => v?.slice(0,10)" />
      <el-table-column label="状态" width="150">
        <template #default="{ row }">
          <el-select v-model="row.status" size="small" @change="updateStatus(row)">
            <el-option value="pending" label="待查看" />
            <el-option value="viewed" label="已查看" />
            <el-option value="interviewing" label="面试中" />
            <el-option value="hired" label="已录用" />
            <el-option value="rejected" label="已拒绝" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button size="small" @click="viewResume(row)">查看简历</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="resumeVisible" title="简历详情" width="600px">
      <div v-if="currentResume">
        <p><strong>姓名：</strong>{{ currentResume.name }}</p>
        <p><strong>性别：</strong>{{ currentResume.gender }}</p>
        <el-divider>教育经历</el-divider>
        <div v-for="(e, i) in currentResume.education" :key="i">{{ e.school }} · {{ e.degree }} · {{ e.major }}</div>
        <el-divider>工作经历</el-divider>
        <div v-for="(e, i) in currentResume.experience" :key="i">{{ e.company }} · {{ e.position }} · {{ e.duration }}</div>
        <div v-if="currentResume.attachment_url" style="margin-top:16px">
          <a :href="currentResume.attachment_url" target="_blank">下载简历附件</a>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getManageApplications, updateApplicationStatus } from '@/api/applications'
import { ElMessage } from 'element-plus'

const applications = ref([])
const loading = ref(false)
const resumeVisible = ref(false)
const currentResume = ref(null)

onMounted(async () => {
  loading.value = true
  const { data } = await getManageApplications()
  applications.value = data.results
  loading.value = false
})

async function updateStatus(row) {
  try {
    await updateApplicationStatus(row.id, { status: row.status })
    ElMessage.success('状态已更新，求职者将收到邮件通知')
  } catch { ElMessage.error('更新失败') }
}

function viewResume(row) {
  currentResume.value = row.resume_snapshot
  resumeVisible.value = true
}
</script>
