<template>
  <div class="resume-page dflex">
    <SideNav />
    <div class="resume-page__content">
      <!-- 页面标题 -->
      <div class="resume-page__header">
        <h2 class="resume-page__title">简历管理</h2>
      </div>

      <!-- 简历卡片网格 -->
      <div ref="gridRef" class="resume-page__card-grid scrollbar-thin" @scroll="onGridScroll">
        <!-- 简历卡片列表 -->
        <div
          v-for="item in resumeList"
          :key="item.id"
          class="resume-page__card"
          @click="goDetail(item.id)"
        >
          <!-- 预览图区域 -->
          <div class="resume-page__card-preview">
            <!-- 默认标记 -->
            <span v-if="item.isDefault" class="resume-page__card-default-tag">默认</span>
            <!-- 更多按钮（右上角） -->
            <button
              class="resume-page__card-more-btn"
              @click.stop="toggleMenu(item.id)"
            >
              <svg viewBox="0 0 24 24" fill="none">
                <circle cx="6" cy="12" r="2" fill="#52CAD1"/>
                <circle cx="12" cy="12" r="2" fill="#52CAD1"/>
                <circle cx="18" cy="12" r="2" fill="#52CAD1"/>
              </svg>
            </button>
            <!-- 更多菜单 -->
            <div v-if="activeMenuId === item.id" class="resume-page__card-menu" @click.stop>
              <!-- 设为默认 -->
              <div
                v-if="!item.isDefault"
                class="resume-page__card-menu-item resume-page__card-menu-item--default"
                @click.stop="handleSetDefault(item.id)"
              >
                <svg viewBox="0 0 16 16" fill="none">
                  <path d="M8 1.5L9.79 5.12L13.8 5.71L10.9 8.53L11.58 12.52L8 10.63L4.42 12.52L5.1 8.53L2.2 5.71L6.21 5.12L8 1.5Z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" fill="none"/>
                </svg>
                <span>设为默认</span>
              </div>
              <!-- 导出简历 -->
              <div
                class="resume-page__card-menu-item"
                @click.stop="handleExport(item)"
              >
                <svg viewBox="0 0 16 16" fill="none">
                  <path d="M8 2v8M8 2L5 5M8 2l3 3" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M2 10v3a1 1 0 001 1h10a1 1 0 001-1v-3" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <span>导出简历</span>
              </div>
              <!-- 删除简历 -->
              <div
                class="resume-page__card-menu-item resume-page__card-menu-item--delete"
                @click.stop="handleDelete(item.id, item.isDefault)"
              >
                <svg viewBox="0 0 16 16" fill="none">
                  <path d="M3 4h10M5.5 4V3a1 1 0 011-1h3a1 1 0 011 1v1M6.5 7v4M9.5 7v4" stroke="#EF4444" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M4 4l.7 8.5a1 1 0 001 .9h4.6a1 1 0 001-.9L12 4" stroke="#EF4444" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <span style="color: #6A7282;">删除简历</span>
              </div>
            </div>
            <!-- 预览图片 -->
            <img src="@/assets/images/resume-list-img01.png" alt="简历预览" />
          </div>

          <!-- 底部信息区域 -->
          <div class="resume-page__card-info">
            <!-- 名称 + 编辑按钮 -->
            <div class="resume-page__card-info-header">
              <span class="resume-page__card-name">{{ item.name }}</span>
              <!-- 编辑按钮（笔图标） -->
              <button class="resume-page__card-edit-btn" @click.stop="handleEditName(item)">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M4.16667 17.5H15.8333C16.75 17.5 17.5 16.75 17.5 15.8333V9.16667H15.8333V15.8333H4.16667V4.16667H10.8333V2.5H4.16667C3.25 2.5 2.5 3.25 2.5 4.16667V15.8333C2.5 16.75 3.25 17.5 4.16667 17.5Z" fill="#52CAD1"/>
                  <path d="M6.83334 10.6662V12.3329C6.83334 12.7912 7.20834 13.1662 7.66668 13.1662H9.33334C9.55834 13.1662 9.76668 13.0746 9.92501 12.9246L15.3 7.54956L12.4583 4.7079L7.08334 10.0829C7.00611 10.1608 6.945 10.2531 6.90353 10.3546C6.86206 10.4562 6.84104 10.5649 6.84168 10.6746L6.83334 10.6662ZM17.2583 5.59123C17.3356 5.51413 17.3969 5.42256 17.4387 5.32175C17.4805 5.22094 17.502 5.11287 17.502 5.00373C17.502 4.89459 17.4805 4.78652 17.4387 4.68571C17.3969 4.5849 17.3356 4.49332 17.2583 4.41623L15.5917 2.74956C15.5146 2.67231 15.423 2.61102 15.3222 2.5692C15.2214 2.52738 15.1133 2.50586 15.0042 2.50586C14.895 2.50586 14.787 2.52738 14.6862 2.5692C14.5853 2.61102 14.4938 2.67231 14.4167 2.74956L13.0417 4.12456L15.8833 6.96623L17.2583 5.59123Z" fill="#52CAD1"/>
                </svg>
              </button>
            </div>
            <!-- 目标岗位 -->
            <div class="resume-page__card-target">{{ item.targetJob || '' }}</div>
            <!-- 最后编辑时间（hover时显示） -->
            <div class="resume-page__card-edit-time">最后编辑于：{{ item.updatedAtDate }}</div>
          </div>
        </div>

        <!-- 新建卡片（始终在最后） -->
        <div class="resume-page__card-new" @click="handleUpload">
          <svg viewBox="0 0 32 32" fill="none">
            <circle cx="16" cy="16" r="16" fill="#52CAD1"/>
            <path d="M16 10v12M10 16h12" stroke="#fff" stroke-width="2.5" stroke-linecap="round"/>
          </svg>
          <span>新建</span>
        </div>

        <!-- 加载中 -->
        <div v-if="loadingMore" class="resume-page__loading-box">
          <span>加载中...</span>
        </div>
      </div>
    </div>

    <!-- 编辑简历名称弹窗 -->
    <ResumeEditNameDialog
      v-model="editNameVisible"
      :resume-id="editResumeId"
      :resume-name="editResumeName"
      :target-position="editTargetPosition"
      @saved="loadResumeList"
    />

    <!-- 导出简历弹窗组件 -->
    <ResumeExportDialog
      v-model="exportDialogVisible"
      :resume-id="exportResumeId"
      :resume-name="exportResumeName"
    />

    <!-- 上传简历弹窗组件 -->
    <ResumeUploadDialog
      v-model="uploadDialogVisible"
      @confirm="handleUploadConfirm"
    />

    <!-- 全屏加载遮罩 -->
    <FullscreenLoading :visible="fullLoading" :text="fullLoadingText" title="Nova 正在帮您努力处理~" />

    <!-- 简历解析步骤进度遮罩 -->
    <StepProgressOverlay
      v-if="showUploadProgress"
      :title="uploadProgressTitle"
      :subtitle="uploadProgressSubtitle"
      :steps="uploadProgressSteps"
      :durations="uploadProgressDurations"
      :done="uploadProgressDone"
      @finished="handleUploadProgressFinished"
      @close="handleUploadProgressClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import SideNav from '@/components/SideNav.vue'
import ResumeEditNameDialog from '@/components/ResumeEditNameDialog.vue'
import ResumeExportDialog from '@/components/ResumeExportDialog.vue'
import ResumeUploadDialog from '@/components/ResumeUploadDialog.vue'
import { uploadResume } from '@/utils/aiRequest'
import {
  fetchResumeList, deleteResume, setDefaultResume, type ResumeListItem,
} from '@/api/resume'
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/es/components/message-box/style/css'
import FullscreenLoading from '@/components/FullscreenLoading.vue'
import StepProgressOverlay from '@/components/StepProgressOverlay.vue'

const router = useRouter()

// 声明友盟统计 _czc 对象
const _czc: any[] = (window as any)._czc || [];
(window as any)._czc = _czc;
_czc.push(["_setAccount", "1281490571"]);

// ==================== 全屏加载状态 ====================
/** 全屏加载是否显示 */
const fullLoading = ref(false)
/** 全屏加载文案 */
const fullLoadingText = ref('')

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

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

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

/**
 * 将毫秒时间戳转为日期格式 YYYY-MM-DD
 */
function formatDate(timestamp?: number): string {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

/**
 * 将后端简历数据转为前端展示结构
 */
function mapResumeItem(item: ResumeListItem): ResumeItem {
  const name = item.resumeName || '未命名简历'
  return {
    id: String(item.id ?? ''),
    name,
    isDefault: item.isDefault === 1,
    targetJob: item.targetPosition || '',
    updatedAt: String(item.updateTime || ''),
    updatedAtDate: formatDate(item.updateTime),
  }
}

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

/** 简历列表 */
const resumeList = ref<ResumeItem[]>([])
/** 当前页码 */
const pageNum = ref(1)
/** 每页条数 */
const pageSize = ref(20)
/** 是否加载更多中 */
const loadingMore = ref(false)
/** 是否无更多数据 */
const hasNoMoreData = ref(false)
/** 首次加载中 */
const loading = ref(false)
/** 网格容器ref */
const gridRef = ref<HTMLElement | null>(null)

/** 加载简历列表（首页） */
async function loadResumeList() {
  loading.value = true
  pageNum.value = 1
  hasNoMoreData.value = false
  try {
    const res = await fetchResumeList(pageSize.value)
    if (res.code === '0' && res.data) {
      resumeList.value = res.data.map(mapResumeItem)
      // 如果返回数量少于 pageSize，说明没有更多了
      if (res.data.length < pageSize.value) {
        hasNoMoreData.value = true
      }
    }
  } catch (e) {
    console.error('获取简历列表失败', e)
  } finally {
    loading.value = false
    // 首次加载后检查是否需要自动填满容器
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 加载下一页 */
async function loadNextPage() {
  if (loadingMore.value || hasNoMoreData.value) return
  loadingMore.value = true
  pageNum.value++
  try {
    const res = await fetchResumeList(pageSize.value)
    if (res.code === '0' && res.data) {
      if (res.data.length === 0) {
        hasNoMoreData.value = true
        pageNum.value--
      } else {
        resumeList.value.push(...res.data.map(mapResumeItem))
        if (res.data.length < pageSize.value) {
          hasNoMoreData.value = true
        }
      }
    }
  } catch (e) {
    pageNum.value--
    console.error('加载下一页失败', e)
  } finally {
    loadingMore.value = false
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 自动填满容器：当列表内容不足以产生滚动条且还有更多数据时，自动加载下一页 */
function autoFillIfNeeded() {
  const el = gridRef.value
  if (!el) return
  if (el.scrollHeight <= el.clientHeight && !hasNoMoreData.value && !loadingMore.value && !loading.value) {
    loadNextPage()
  }
}

/** 网格滚动事件 — 触底自动加载 */
function onGridScroll() {
  const el = gridRef.value
  if (!el) return
  if (el.scrollHeight - el.scrollTop - el.clientHeight < 100) {
    loadNextPage()
  }
}

// ==================== 卡片菜单状态 ====================

/** 当前展开菜单的简历ID */
const activeMenuId = ref<string>('')

/** 切换菜单 */
function toggleMenu(id: string) {
  activeMenuId.value = activeMenuId.value === id ? '' : id
}

/** 点击页面其他区域关闭菜单 */
function closeMenuOnClickOutside() {
  activeMenuId.value = ''
}

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

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

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

/** 导出弹窗是否可见 */
const exportDialogVisible = ref(false)
/** 当前导出的简历 ID */
const exportResumeId = ref('')
/** 当前导出的简历名称 */
const exportResumeName = ref('')

// ==================== 上传简历弹窗状态 ====================

/** 上传弹窗是否可见 */
const uploadDialogVisible = ref(false)

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

/** 点击编辑图标 — 打开编辑名称岗位弹窗 */
function handleEditName(item: ResumeItem) {
  editResumeId.value = item.id
  editResumeName.value = item.name
  editTargetPosition.value = item.targetJob
  editNameVisible.value = true
}

/** 设为默认简历 */
async function handleSetDefault(id: string) {
  activeMenuId.value = ''
  try {
    const res = await setDefaultResume(id)
    if (res.code === '0') {
      ElMessage.success('已设为默认简历')
      loadResumeList()
    } else {
      ElMessage.error(res.msg || '设置失败')
    }
  } catch {
    ElMessage.error('设置失败，请稍后重试')
  }
}

/** 导出简历 */
function handleExport(item: ResumeItem) {
  activeMenuId.value = ''
  exportResumeId.value = item.id
  exportResumeName.value = item.name || '简历'
  exportDialogVisible.value = true
}

/** 删除简历 */
async function handleDelete(id: string, isDefault: boolean) {
  activeMenuId.value = ''
  try {
    await ElMessageBox.confirm('确定要删除这份简历吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (resumeList.value.length <= 1 || isDefault) {
      ElMessage.warning('默认简历不可删除')
      return
    }

    const res = await deleteResume(id)
    if (res.code === '0') {
      ElMessage.success('删除成功')
      loadResumeList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

/** 上传简历 — 打开上传弹窗 */
function handleUpload() {
  uploadDialogVisible.value = true
}

/** 上传弹窗确认回调 */
async function handleUploadConfirm(file: File) {
  showUploadProgress.value = true
  uploadProgressDone.value = false
  pendingResumeId.value = ''

  try {
    const res = await uploadResume(file)
    if (res.code === 0) {
      loadResumeList()
      pendingResumeId.value = res.data.resumeId
      uploadProgressDone.value = true
    } else {
      showUploadProgress.value = false
      ElMessage.error(res.msg || '上传失败')
    }
  } catch {
    showUploadProgress.value = false
    ElMessage.error('上传失败，请稍后重试')
  }
}

// ==================== 简历解析步骤进度遮罩 ====================

/** 解析步骤进度遮罩是否显示 */
const showUploadProgress = ref(false)
/** 解析接口是否已完成 */
const uploadProgressDone = ref(false)
/** 大标题 */
const uploadProgressTitle = '正在解析简历'
/** 副标题 */
const uploadProgressSubtitle = '正在识别教育背景、工作经历与技能关键词'
/** 4个步骤名称 */
const uploadProgressSteps = ['教育背景解析...', '工作经历解析...', '技能特长解析...', '个人资料最终确认']
/** 每步时长 */
const uploadProgressDurations = [4200, 4200, 4200, 4200]
/** 缓存的简历ID */
const pendingResumeId = ref('')

/** 解析进度走完后跳转详情页 */
function handleUploadProgressFinished() {
  showUploadProgress.value = false
  if (pendingResumeId.value) {
    goDetail(pendingResumeId.value)
    pendingResumeId.value = ''
  }
}

/** 关闭解析进度遮罩 */
function handleUploadProgressClose() {
  showUploadProgress.value = false
}

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

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

onMounted(() => {
  loadResumeList()
  document.addEventListener('click', closeMenuOnClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenuOnClickOutside)
})
</script>
