<template>
  <div class="resume-page dflex">
    <SideNav />
    <div class="resume-page__content">
      <!-- 页面标题 + 上传按钮 -->
      <div class="resume-page__header">
        <h2 class="resume-page__title">我的简历</h2>
        <button class="resume-page__upload-btn" @click="handleUpload">
          <svg viewBox="0 0 16 16" fill="none" class="resume-page__upload-icon">
            <path d="M8 3v10M3 8h10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
          上传简历
        </button>
      </div>

      <!-- 简历表格 -->
      <div class="resume-page__table-wrap">
        <table class="resume-page__table">
          <thead>
            <tr>
              <th class="resume-page__th">简历</th>
              <th class="resume-page__th">目标岗位</th>
              <th class="resume-page__th">最近修改</th>
              <th class="resume-page__th">创建时间</th>
              <th class="resume-page__th resume-page__th--action"></th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="item in resumeList"
              :key="item.id"
              class="resume-page__row"
              @click="goDetail(item.id)"
            >
              <td class="resume-page__td">
                <div class="resume-page__name-cell">
                  <span class="resume-page__avatar" :style="{ background: item.avatarColor }">
                    {{ item.avatarLetter }}
                  </span>
                  <span class="resume-page__name">{{ item.name }}</span>
                  <span v-if="item.isDefault" class="resume-page__default-tag">默认</span>
                </div>
              </td>
              <td class="resume-page__td">{{ item.targetJob }}</td>
              <td class="resume-page__td">{{ item.updatedAt }}</td>
              <td class="resume-page__td">{{ item.createdAt }}</td>
              <td class="resume-page__td resume-page__td--action">
                <button
                  class="resume-page__more-btn"
                  aria-label="更多操作"
                  @click.stop="toggleMenu(item.id)"
                >
                  <svg viewBox="0 0 16 16" fill="currentColor" class="resume-page__more-svg">
                    <circle cx="3" cy="8" r="1.5"/>
                    <circle cx="8" cy="8" r="1.5"/>
                    <circle cx="13" cy="8" r="1.5"/>
                  </svg>
                </button>
                <!-- 弹出菜单 -->
                <div v-if="activeMenuId === item.id" class="resume-page__popup" @click.stop>
                  <div
                    v-for="action in popupActions"
                    :key="action"
                    class="resume-page__popup-item"
                    @click="handleAction(action, item.id)"
                  >
                    {{ action }}
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!-- 编辑简历名称弹窗 -->
    <ResumeEditNameDialog
      v-model="editNameVisible"
      :resume-id="editResumeId"
      :resume-name="editResumeName"
      :target-position="editTargetPosition"
      @saved="loadResumeList"
    />

    <!-- 导出简历格式选择弹窗 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="导出简历"
      width="3.6rem"
      :close-on-click-modal="false"
      class="resume-export-dialog"
    >
      <!-- 格式选择 -->
      <el-radio-group v-model="exportFormat" class="resume-export-dialog__radio-group">
        <el-radio value="pdf">PDF 简历</el-radio>
        <el-radio value="word">Word 简历</el-radio>
      </el-radio-group>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="exporting" @click="doExport">下载</el-button>
      </template>
    </el-dialog>

    <!-- 隐藏的简历模板，用于导出时渲染DOM -->
    <div v-if="exportTemplateData" style="position:absolute;left:-9999px;top:0;">
      <JobResumeTemplate ref="exportTemplateRef" :resume-data="exportTemplateData" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import SideNav from '@/components/SideNav.vue'
import ResumeEditNameDialog from '@/components/ResumeEditNameDialog.vue'
import JobResumeTemplate from '@/components/JobResumeTemplate.vue'
import type { ResumeTemplateData } from '@/components/JobResumeTemplate.vue'
import { exportResumePdf, exportResumeWord, loadResumeTemplateData } from '@/utils/resumeExport'
import { uploadResume } from '@/utils/aiRequest'
import {
  fetchResumeList, deleteResume, type ResumeListItem,
} from '@/api/resume'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
// ElLoading.service() 是命令式调用，按需引入插件不会自动加载其样式，需手动引入
import 'element-plus/es/components/loading/style/css'

const router = useRouter()

// ==================== 头像颜色池 ====================

/** 头像背景色列表，按索引循环取色 */
const avatarColors = ['#1A1A2E', '#4FC2C9', '#F2994A', '#6C5CE7', '#E17055', '#00B894', '#FDCB6E']

// ==================== 类型定义 ====================

/** 简历列表项（前端展示用） */
interface ResumeItem {
  id: string
  name: string
  avatarLetter: string
  avatarColor: string
  isDefault: boolean
  targetJob: string
  updatedAt: string
  createdAt: string
}

// ==================== 工具方法 ====================

/**
 * 将毫秒时间戳转为友好的相对时间文案
 * @param timestamp 后端返回的毫秒级时间戳
 */
function formatTime(timestamp?: number): string {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const now = Date.now()
  const diff = now - date.getTime()
  const minutes = Math.floor(diff / 60000)
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`
  const days = Math.floor(hours / 24)
  if (days < 30) return `${days}天前`
  const months = Math.floor(days / 30)
  if (months < 12) return `${months}个月前`
  return `${Math.floor(months / 12)}年前`
}

/**
 * 将后端简历数据转为前端展示结构
 */
function mapResumeItem(item: ResumeListItem, index: number): ResumeItem {
  const name = item.resumeName || '未命名简历'
  return {
    id: String(item.id ?? ''),
    name,
    avatarLetter: name.charAt(0) || '?',
    avatarColor: avatarColors[index % avatarColors.length],
    isDefault: item.isDefault === 1,
    targetJob: item.targetPosition || '',
    updatedAt: formatTime(item.updateTime),
    createdAt: formatTime(item.createTime),
  }
}

// ==================== 数据 ====================

/** 简历列表 */
const resumeList = ref<ResumeItem[]>([])

/** 加载简历列表 */
async function loadResumeList() {
  try {
    const res = await fetchResumeList()
    if (res.code === '0' && res.data) {
      resumeList.value = res.data.map(mapResumeItem)
    }
  } catch (e) {
    console.error('获取简历列表失败', e)
  }
}

// ==================== 生命周期 ====================

onMounted(() => {
  loadResumeList()
})

// ==================== 页面状态 ====================

/** 当前打开弹出菜单的简历 ID */
const activeMenuId = ref<string | null>(null)

// ==================== 编辑简历名称弹窗状态 ====================

/** 编辑弹窗是否可见 */
const editNameVisible = ref(false)
/** 当前编辑的简历 ID */
const editResumeId = ref('')
/** 当前编辑的简历名称 */
const editResumeName = ref('')
/** 当前编辑的目标岗位 */
const editTargetPosition = ref('')

// ==================== 导出简历弹窗状态 ====================

/** 导出弹窗是否可见 */
const exportDialogVisible = ref(false)
/** 导出格式：pdf 或 word */
const exportFormat = ref<'pdf' | 'word'>('pdf')
/** 导出中状态 */
const exporting = ref(false)
/** 当前导出的简历 ID */
const exportResumeId = ref('')
/** 当前导出的简历名称（用于文件名） */
const exportResumeName = ref('')
/** 导出用的简历模板数据 */
const exportTemplateData = ref<ResumeTemplateData | null>(null)
/** 导出用的简历模板组件引用 */
const exportTemplateRef = ref<InstanceType<typeof JobResumeTemplate> | null>(null)

/** 执行导出下载 */
async function doExport() {
  exporting.value = true
  try {
    // 1. 加载简历完整数据
    const data = await loadResumeTemplateData(exportResumeId.value)
    if (!data) {
      ElMessage.error('获取简历数据失败')
      return
    }

    // 2. 设置模板数据，等待DOM渲染
    exportTemplateData.value = data
    await nextTick()

    // 3. 获取渲染后的DOM
    const element = exportTemplateRef.value?.resumeRef
    if (!element) {
      ElMessage.error('简历模板渲染失败')
      return
    }

    const fileName = exportResumeName.value || '简历'

    if (exportFormat.value === 'pdf') {
      await exportResumePdf(element, fileName)
    } else {
      exportResumeWord(element, fileName)
    }

    ElMessage.success('导出成功')
    exportDialogVisible.value = false
  } catch (err) {
    console.error('[导出简历] 失败', err)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    exporting.value = false
    // 清理隐藏模板数据
    exportTemplateData.value = null
  }
}

/** 弹出菜单操作项 */
const popupActions = ['设为默认简历', '编辑名称岗位', '导出简历', '删除']

// ==================== 事件处理 ====================

/** 切换弹出菜单的显示/隐藏 */
function toggleMenu(id: string) {
  activeMenuId.value = activeMenuId.value === id ? null : id
}

/** 弹出菜单操作点击 */
async function handleAction(action: string, id: string) {
  activeMenuId.value = null
  
  if (action === '删除') {
    // 二次确认删除
    try {
      await ElMessageBox.confirm('确定要删除这份简历吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      
      // 调用删除接口
      const res = await deleteResume(id)
      if (res.code === '0') {
        ElMessage.success('删除成功')
        // 刷新列表
        loadResumeList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      // 用户取消删除或接口报错
      if (error !== 'cancel') {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  } else if (action === '编辑名称岗位') {
    // 找到当前简历数据，打开编辑弹窗
    const target = resumeList.value.find(r => r.id === id)
    if (target) {
      editResumeId.value = id
      editResumeName.value = target.name
      editTargetPosition.value = target.targetJob
      editNameVisible.value = true
    }
  } else if (action === '导出简历') {
    // 打开导出格式选择弹窗
    exportResumeId.value = id
    const target = resumeList.value.find(r => r.id === id)
    exportResumeName.value = target?.name || '简历'
    exportDialogVisible.value = true
  } else {
    console.log(action, id)
  }
}

/** 上传简历 — 弹出文件选择，选择后调用 AI 接口上传 */
function handleUpload() {
  const input = document.createElement('input')
  input.type = 'file'
  // 限定 pdf 和 word 格式
  input.accept = '.pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'

  input.onchange = async () => {
    const file = input.files?.[0]
    if (!file) return

    // 全屏加载提示，AI 接口响应较慢
    const loading = ElLoading.service({
      lock: true,
      text: '简历解析中，请耐心等待…',
      background: 'rgba(0, 0, 0, 0.5)',
      customClass: 'resume-upload-loading',
    })

    try {
      const res = await uploadResume(file)
      if (res.code === 0) {
        // 上传成功，刷新列表
        loadResumeList()
        // 等待让后端异步处理数据，再关闭加载动画并跳转详情页
        await new Promise(resolve => setTimeout(resolve, 2000))
        loading.close()
        // resumeId 已经是字符串（transformResponse 处理过），直接使用
        goDetail(res.data.resumeId)
      } else {
        loading.close()
        ElMessage.error(res.msg || '上传失败')
      }
    } catch {
      loading.close()
      ElMessage.error('上传失败，请稍后重试')
    }
  }

  input.click()
}

/** 跳转到简历详情页 */
function goDetail(id: string) {
  router.push(`/resume/${id}`)
}
</script>
