<template>
  <div>
    <h2>投递管理</h2>
    <el-table :data="applications" v-loading="loading" border style="width:100%">
      <el-table-column label="职位">
        <template #default="{ row }">
          <el-button type="primary" link @click="$router.push({ name: 'JobDetail', params: { id: row.job } })">
            {{ row.job_title }}
          </el-button>
        </template>
      </el-table-column>
      <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>
    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
      />
    </div>

    <el-dialog v-model="resumeVisible" title="简历详情" width="700px">
      <div v-if="currentResume" class="resume-detail">
        <!-- 基本信息 -->
        <div class="section">
          <div class="section-title">基本信息</div>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ currentResume.name || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">性别：</span>
              <span class="value">{{ getGenderLabel(currentResume.gender) }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ currentResume.email || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机：</span>
              <span class="value">{{ currentResume.phone || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">生日：</span>
              <span class="value">{{ currentResume.birthday || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 教育经历 -->
        <div class="section">
          <div class="section-title">教育经历</div>
          <div v-if="currentResume.education?.length" class="list-items">
            <div v-for="(e, i) in currentResume.education" :key="i" class="list-item">
              <div class="item-header">{{ e.school }}</div>
              <div class="item-detail">{{ e.degree }} · {{ e.major }}</div>
              <div class="item-detail">{{ e.start_year }} - {{ e.end_year }}</div>
            </div>
          </div>
          <div v-else style="color: #999; font-size: 12px;">暂无教育经历</div>
        </div>

        <!-- 工作经历 -->
        <div class="section">
          <div class="section-title">工作经历</div>
          <div v-if="currentResume.experience?.length" class="list-items">
            <div v-for="(e, i) in currentResume.experience" :key="i" class="list-item">
              <div class="item-header">{{ e.company }} - {{ e.position }}</div>
              <div class="item-detail">{{ e.duration }}</div>
              <div class="item-detail" v-if="e.description">{{ e.description }}</div>
            </div>
          </div>
          <div v-else style="color: #999; font-size: 12px;">暂无工作经历</div>
        </div>

        <!-- 附件 -->
        <div class="section" v-if="currentResume.attachment_url">
          <div class="section-title">附件</div>
          <div style="margin-top: 8px;">
            <el-button type="primary" @click="downloadAttachment">
              <el-icon><Download /></el-icon>
              下载简历附件
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getManageApplications, updateApplicationStatus } from '@/api/applications'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'

const applications = ref([])
const loading = ref(false)
const resumeVisible = ref(false)
const currentResume = ref(null)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const genderMap = {
  'male': '男',
  'female': '女',
  'other': '其他',
  '': '-'
}

const fetchApplications = async (page = 1) => {
  loading.value = true
  try {
    const { data } = await getManageApplications(page)
    applications.value = data.results
    total.value = data.count
    currentPage.value = page
  } finally {
    loading.value = false
  }
}

function handlePageChange(newPage) {
  fetchApplications(newPage)
}

onMounted(() => fetchApplications())

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
}

function getGenderLabel(gender) {
  return genderMap[gender] || '-'
}

async function downloadAttachment() {
  if (!currentResume.value?.attachment_url) {
    ElMessage.warning('附件不可用')
    return
  }
  try {
    // 修正 /media/media/ 双重前缀问题
    let url = currentResume.value.attachment_url.replace(/\/media\/media\//, '/media/')

    // 用 fetch+blob 确保触发下载而不是浏览器预览
    const response = await fetch(url)
    if (!response.ok) throw new Error('请求失败')

    // 优先用 Content-Type 判断扩展名，避免无扩展名文件名导致乱码
    const contentType = (response.headers.get('content-type') || '').split(';')[0].trim()
    const mimeMap = {
      'application/pdf': 'pdf',
      'application/msword': 'doc',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
      'image/jpeg': 'jpg',
      'image/png': 'png',
    }
    let ext = mimeMap[contentType]
    if (!ext) {
      const urlExt = url.split('.').pop().split('?')[0]
      ext = /^[a-zA-Z0-9]{1,5}$/.test(urlExt) ? urlExt : 'pdf'
    }
    const filename = `${currentResume.value.name}_resume.${ext}`

    const blob = await response.blob()
    const blobUrl = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = blobUrl
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(blobUrl)
    ElMessage.success('下载已启动')
  } catch {
    ElMessage.error('下载失败，请重试')
  }
}
</script>

<style scoped>
.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a2e;
  margin-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px 16px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.info-item .label {
  color: #666;
  min-width: 50px;
  font-weight: 500;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.list-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.list-item {
  padding: 12px;
  background: #f9f9f9;
  border-radius: 4px;
  border-left: 3px solid var(--brand-red);
}

.item-header {
  font-size: 13px;
  font-weight: 500;
  color: #1a1a2e;
  margin-bottom: 4px;
}

.item-detail {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
}
</style>
