<template>
  <div class="p-2 bg-gray-50 min-h-screen" v-loading="loading">
    <!-- 顶部导航和用户信息 -->
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between mb-6">
        <el-button link @click="handleBack" icon="ArrowLeft">返回</el-button>
        <div class="space-x-2">
          <el-button v-if="!isEditing" type="primary" plain size="small" @click="isEditing = true">编辑</el-button>
          <template v-else>
            <el-button type="primary" size="small" @click="handleSave" :loading="saveLoading">保存</el-button>
            <el-button size="small" @click="handleCancel">取消</el-button>
          </template>
        </div>
      </div>
      <div class="flex gap-8 relative">
        <div class="flex flex-col items-center">
          <el-avatar :size="100" :src="form.avatarUrl" />
          <dict-tag :options="main_arrivail_time" :value="form.availability" class="mt-2" />
        </div>
        <div class="flex-1">
          <el-form v-if="isEditing" :model="form" label-width="100px" size="small">
            <div class="grid grid-cols-3 gap-4">
              <el-form-item label="姓名">
                <el-input v-model="form.name" />
              </el-form-item>
              <el-form-item label="性别">
                <el-select v-model="form.gender" placeholder="请选择">
                  <el-option v-for="item in sys_user_sex" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="用户类型">
                <el-select v-model="form.userType" placeholder="请选择">
                  <el-option v-for="item in main_student_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="form.mobile" />
              </el-form-item>
              <el-form-item label="电子邮箱">
                <el-input v-model="form.email" />
              </el-form-item>
              <el-form-item label="身份证号">
                <el-input v-model="form.idCardNumber" />
              </el-form-item>
              <el-form-item label="求职意向">
                <el-input v-model="form.jobIntention" />
              </el-form-item>
              <el-form-item label="到岗时间">
                <el-select v-model="form.availability" placeholder="请选择">
                  <el-option v-for="item in main_arrivail_time" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="岗位类型">
                <el-select v-model="form.jobType" placeholder="请选择">
                  <el-option v-for="item in main_position_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="毕业院校">
                <el-input v-model="form.schoolName" />
              </el-form-item>
              <el-form-item label="学历">
                <el-select v-model="form.education" placeholder="请选择">
                  <el-option v-for="item in main_education" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="工作经验">
                <el-select v-model="form.grade" placeholder="请选择">
                  <el-option v-for="item in main_experience" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="实习时长">
                <el-select v-model="form.internshipDuration" placeholder="请选择">
                  <el-option v-for="item in main_internship_duration" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" class="col-span-3">
                <el-input v-model="form.remark" type="textarea" rows="3" />
              </el-form-item>
            </div>
          </el-form>
          <div v-else class="grid grid-cols-3 gap-y-4 gap-x-12">
            <div class="col-span-1">
              <div class="flex items-center gap-2 mb-2">
                <span class="text-2xl font-bold">{{ form.name }}</span>
                <el-icon v-if="form.gender === '0' || form.gender === 'M'" class="text-blue-500"><Male /></el-icon>
                <el-icon v-else-if="form.gender === '1' || form.gender === 'F'" class="text-pink-500"><Female /></el-icon>
                <span v-if="form.userType === '1'" class="text-orange-400">💎</span>
              </div>
              <div class="text-xs text-gray-400 mb-1">用户类型</div>
              <div class="text-sm">
                <dict-tag :options="main_student_type" :value="form.userType" />
              </div>
              <div class="text-xs text-gray-400 mb-1 mt-2">身份证号</div>
              <div class="text-sm">{{ form.idCardNumber || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">联系电话</div>
              <div class="text-sm">{{ form.mobile }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">电子邮箱</div>
              <div class="text-sm">{{ form.email || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">求职意向</div>
              <div class="text-sm">{{ form.jobIntention || '-' }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">岗位类型</div>
              <div class="text-sm">
                <dict-tag :options="main_position_type" :value="form.jobType" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">毕业院校</div>
              <div class="text-sm">
                {{ form.schoolName }} · 
                <dict-tag :options="main_experience" :value="form.grade" /> · 
                <dict-tag :options="main_education" :value="form.education" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">实习时长</div>
              <div class="text-sm">
                <dict-tag :options="main_internship_duration" :value="form.internshipDuration" />
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">注册日期</div>
              <div class="text-sm">{{ form.createTime }}</div>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">最后更新</div>
              <div class="text-sm">{{ form.updateTime }}</div>
            </div>
          </div>
        </div>
        <div v-if="!isEditing" class="absolute right-0 top-0 space-x-2">
          <el-button type="primary" plain size="small" icon="Download" @click="handleExport">导出在线简历</el-button>
          <el-button type="primary" plain size="small" icon="Download" @click="handleDownload">下载简历附件</el-button>
        </div>
      </div>
    </el-card>

    <!-- 底部 Tab 内容 -->
    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <!-- 在线简历 -->
        <el-tab-pane label="在线简历" name="resume">
          <div class="space-y-8 p-4">
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">教育经历</h3>
              <el-table :data="form.educationList" border>
                <el-table-column prop="school" label="学校" />
                <el-table-column prop="education" label="学历" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                  </template>
                </el-table-column>
                <el-table-column prop="major" label="专业" />
                <el-table-column prop="campusExperience" label="在校经历" show-overflow-tooltip />
              </el-table>
            </section>
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">工作经历</h3>
              <el-table :data="form.experienceList" border>
                <el-table-column label="公司">
                  <template #default="scope">
                    {{ scope.row.isHidden === 1 ? '***（已屏蔽）' : scope.row.company }}
                  </template>
                </el-table-column>
                <el-table-column prop="industry" label="行业" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                    <el-tag v-if="scope.row.isInternship === 1" size="small" type="info" class="ml-1">实习</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="jobTitle" label="职位" />
                <el-table-column prop="department" label="所属部门" />
                <el-table-column prop="workContent" label="工作内容" show-overflow-tooltip />
              </el-table>
            </section>
            <section>
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">项目经历</h3>
              <el-table :data="form.projectList" border>
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="role" label="角色" />
                <el-table-column label="时间" width="200">
                  <template #default="scope">
                    {{ scope.row.startTime }} - {{ scope.row.endTime }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="项目描述" show-overflow-tooltip />
              </el-table>
            </section>

            <!-- 简历附件列表 -->
            <section v-if="form.appendixList && form.appendixList.length > 0">
              <h3 class="font-bold text-base mb-4 border-l-4 border-blue-500 pl-2">简历附件</h3>
              <el-table :data="form.appendixList" border>
                <el-table-column prop="fileName" label="文件名" />
                <el-table-column label="文件大小" width="120">
                  <template #default="scope">
                    {{ (scope.row.fileSize / 1024).toFixed(2) }} KB
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="上传时间" width="180" />
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button link type="primary" icon="Download" @click="proxy.$download.oss(scope.row.ossId)">下载</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </section>
          </div>
        </el-tab-pane>

        <!-- 测评信息 -->
        <el-tab-pane label="测评信息" name="assessment">
          <div class="p-4" v-loading="assessmentLoading">
            <el-table :data="assessmentList" border>
              <el-table-column prop="evaluationName" label="测评名称" min-width="180" />
              <el-table-column label="结果" width="120" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.statusType === 'pass' ? 'success' : (scope.row.statusType === 'fail' ? 'danger' : 'info')">
                    {{ scope.row.statusText }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="申请时间" width="180" align="center" />
              <el-table-column prop="finishedTime" label="完成时间" width="180" align="center" />
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" @click="handleViewAssessment(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 培训信息 -->
        <el-tab-pane label="培训信息" name="training">
          <div class="p-4" v-loading="trainingLoading">
            <el-table :data="trainingList" border>
              <el-table-column prop="name" label="培训名称" min-width="180" />
              <el-table-column label="学习进度" width="180" align="center">
                <template #default="scope">
                  <el-progress :percentage="scope.row.progress || 0" />
                </template>
              </el-table-column>
              <el-table-column prop="learnedTime" label="累计学时" width="150" align="center">
                <template #default="scope">
                  {{ scope.row.learnedTime || 0 }} 分钟
                </template>
              </el-table-column>
              <el-table-column prop="lastLearnTime" label="最后学习时间" width="180" align="center" />
              <el-table-column prop="finishTime" label="完成时间" width="180" align="center">
                <template #default="scope">
                  {{ scope.row.finishTime || '-' }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 订单信息 -->
        <el-tab-pane label="订单信息" name="order">
          <div class="p-4" v-loading="orderLoading">
            <div class="flex items-center gap-2 mb-6">
              <div class="w-1 h-4 bg-blue-500"></div>
              <span class="font-bold text-gray-800">订单信息</span>
            </div>
            
            <el-tabs v-model="orderSubTab" class="mb-0 order-tabs">
              <el-tab-pane label="全部订单" name="all" />
              <el-tab-pane label="待付款" name="pending" />
              <el-tab-pane label="已完成" name="completed" />
              <el-tab-pane label="已关闭" name="closed" />
              <el-tab-pane label="退款中" name="refunding" />
            </el-tabs>
            
            <div class="order-table-header flex items-center bg-[#f8f9fb] py-3 px-4 text-xs font-bold text-gray-600 border border-b-0 border-gray-100">
              <div class="flex-1">商品信息</div>
              <div class="w-48 text-center">用户信息</div>
              <div class="w-32 text-center">订单来源</div>
              <div class="w-32 text-center">订单类型</div>
              <div class="w-32 text-center">订单状态</div>
              <div class="w-48 text-center">操作</div>
            </div>

            <div class="space-y-4" v-if="orderList && orderList.length > 0">
              <div v-for="order in orderList" :key="order.id" class="order-item border border-gray-100">
                <div class="order-info-bar flex justify-between items-center bg-[#f4faff] py-2 px-4 text-[11px] text-gray-500 border-b border-gray-100">
                  <div class="flex gap-8">
                    <span>订单编号：{{ order.orderNo }}</span>
                    <span>下单时间：{{ order.createTime }}</span>
                    <span>{{ order.payTime ? '支付时间：' + order.payTime : '未支付' }}</span>
                  </div>
                  <div class="text-[12px] font-bold text-gray-800">实付款（元）：{{ order.totalAmount }}元</div>
                </div>
                <div class="flex items-center py-4 px-4">
                  <div class="flex-1 flex items-center gap-4">
                    <el-image :src="order.productImg" class="w-14 h-14 rounded object-cover border border-gray-100">
                      <template #error>
                        <div class="image-slot bg-gray-100 w-full h-full flex items-center justify-center">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="flex flex-col gap-1">
                      <div class="font-bold text-blue-500 hover:text-blue-600 cursor-pointer text-[13px]">{{ order.productName || '未知商品' }}</div>
                      <div class="text-[11px] text-gray-400">单价：{{ order.totalAmount }}  数量：{{ order.quantity || 1 }}</div>
                    </div>
                  </div>
                  <div class="w-48 flex items-center justify-center gap-2 border-l border-gray-50 h-14">
                    <el-avatar :size="28" :src="order.userAvatar" />
                    <div class="flex flex-col items-start leading-tight">
                      <div class="text-[12px] font-medium text-blue-500 cursor-pointer">{{ order.buyerName }}</div>
                      <div class="text-[11px] text-gray-400 mt-0.5">{{ order.phone || '-' }}</div>
                    </div>
                  </div>
                  <div class="w-32 text-center text-[12px] text-gray-600 border-l border-gray-50 h-14 flex items-center justify-center">{{ order.source || '小程序' }}</div>
                  <div class="w-32 text-center text-[12px] text-gray-600 border-l border-gray-50 h-14 flex items-center justify-center">
                    <span v-if="order.orderType === 1">岗位</span>
                    <span v-else-if="order.orderType === 2">培训</span>
                    <span v-else-if="order.orderType === 3">商品</span>
                    <span v-else>其他</span>
                  </div>
                  <div class="w-32 flex justify-center border-l border-gray-50 h-14 items-center">
                    <el-tag v-if="order.orderStatus === 0" type="warning">待付款</el-tag>
                    <el-tag v-else-if="order.orderStatus === 1" type="success">已完成</el-tag>
                    <el-tag v-else-if="order.orderStatus === 2" type="info">已关闭</el-tag>
                    <el-tag v-else-if="order.orderStatus === 3" type="danger">售后中</el-tag>
                  </div>
                  <div class="w-48 flex items-center justify-center gap-4 border-l border-gray-50 h-14 text-[12px]">
                    <el-button link type="primary" class="!p-0 !text-[12px]" @click="handleOrderDetail(order)">订单详情</el-button>
                    <el-button link type="primary" class="!p-0 !text-[12px]">复制订单</el-button>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无订单数据" />
          </div>
        </el-tab-pane>

        <!-- 任职信息 -->
        <el-tab-pane label="任职信息" name="job">
          <div class="p-4">
            <el-table :data="jobData" border>
              <el-table-column prop="company" label="公司" />
              <el-table-column prop="position" label="岗位" />
              <el-table-column prop="type" label="岗位类型" />
              <el-table-column prop="status" label="任职状态" />
              <el-table-column prop="entryTime" label="入职时间" />
              <el-table-column prop="leaveTime" label="离职时间" />
              <el-table-column prop="reason" label="离职原因" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button link type="primary" @click="handleViewEvaluation(scope.row)">查看公司评价</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 评价对话框 -->
    <el-dialog v-model="evaluationOpen" title="评价" width="500px">
      <div class="space-y-6">
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">综合评价</span>
            <el-rate v-model="evaluationForm.score" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3.5星</span>
          </div>
          <el-input v-model="evaluationForm.comment" type="textarea" readonly rows="2" />
        </div>
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">能力A</span>
            <el-rate v-model="evaluationForm.scoreA" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3星</span>
          </div>
          <el-input v-model="evaluationForm.commentA" type="textarea" readonly rows="2" />
        </div>
        <div class="flex flex-col gap-2">
          <div class="flex items-center gap-4">
            <span class="w-20 font-bold">能力B</span>
            <el-rate v-model="evaluationForm.scoreB" disabled show-score text-color="#ff9900" />
            <span class="text-xs text-gray-400">3星</span>
          </div>
          <el-input v-model="evaluationForm.commentB" type="textarea" readonly rows="2" />
        </div>
      </div>
    </el-dialog>

    <!-- 测评详情弹窗 -->
    <el-dialog
      v-model="assessmentDialog.visible"
      :title="'测评详情 - ' + assessmentDialog.evaluationName"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-loading="assessmentDialog.loading">
        <!-- 无数据 -->
        <el-empty v-if="!assessmentDialog.loading && assessmentDialog.abilityDetails.length === 0" description="暂无考试记录" />

        <!-- 各能力维度详情 -->
        <div v-for="(ability, index) in assessmentDialog.abilityDetails" :key="index" class="mb-6 last:mb-0">
          <div class="ability-section-header">
            <h3 class="font-bold text-base mb-1">{{ ability.abilityName }}</h3>
            <div class="text-sm text-gray-500 space-x-4">
              <span>关联考试：{{ ability.examName || '-' }}</span>
              <span>总分：{{ ability.totalScore || 0 }}分</span>
              <span>及格分：{{ ability.passMark || 0 }}分</span>
            </div>
          </div>

          <!-- 作答记录表格 -->
          <el-table :data="ability.records" border size="small" class="mt-3" v-if="ability.records && ability.records.length > 0">
            <el-table-column label="作答次数" width="80" align="center">
              <template #default="scope">
                第{{ scope.row.times }}次
              </template>
            </el-table-column>
            <el-table-column prop="examName" label="考试名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="examStyleName" label="考试分类" width="120" align="center" />
            <el-table-column label="考试时间范围" min-width="180">
              <template #default="scope">
                {{ scope.row.examStartTime }} ~ {{ scope.row.examEndTime }}
              </template>
            </el-table-column>
            <el-table-column prop="examTime" label="时长" width="70" align="center">
              <template #default="scope">
                {{ scope.row.examTime }}分钟
              </template>
            </el-table-column>
            <el-table-column label="开始时间" width="160" align="center">
              <template #default="scope">
                {{ scope.row.startTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="交卷时间" width="160" align="center">
              <template #default="scope">
                {{ scope.row.commitTime || '未交卷' }}
              </template>
            </el-table-column>
            <el-table-column label="成绩" width="90" align="center">
              <template #default="scope">
                <span :class="{ 'text-red-500': Number(scope.row.score) < (ability.passMark || 0), 'font-bold': true }">
                  {{ scope.row.score }}分
                </span>
              </template>
            </el-table-column>
            <el-table-column label="是否通过" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.isPass === 1" type="success" size="small">及格</el-tag>
                <el-tag v-else-if="scope.row.isPass === 0" type="danger" size="small">不及格</el-tag>
                <el-tag v-else type="info" size="small">未知</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="mt-3 text-center text-gray-400 py-4 bg-gray-50 rounded">
            该维度暂无作答记录
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="StudentDetail" lang="ts">
import { ref, reactive, onMounted, watch, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft, Male, Female, Download, Picture } from '@element-plus/icons-vue'
import { getStudent, updateStudent } from "@/api/main/student";
import { StudentVO, StudentForm } from "@/api/main/student/types";
import { listOrder } from "@/api/system/order";
import { OrderVO } from "@/api/system/order/types";
import { listEvaluationRecord, getEvaluationDetailResult } from "@/api/main/evaluation";
import { EvaluationApplyRecordVO } from "@/api/main/evaluation/types";
import { listStudentTrainingRecords } from "@/api/main/training";
import { TrainingLearnRecordVO } from "@/api/main/training/types";

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_user_sex, main_student_type, main_arrivail_time, main_position_type, main_education, main_experience, main_internship_duration } = proxy?.useDict(
  "sys_user_sex",
  "main_student_type",
  "main_arrivail_time",
  "main_position_type",
  "main_education",
  "main_experience",
  "main_internship_duration"
) as any;

const loading = ref(false)
const saveLoading = ref(false)
const isEditing = ref(false)
const form = ref<Partial<StudentVO>>({})
const originalForm = ref<Partial<StudentVO>>({})
const activeTab = ref('resume')
const orderSubTab = ref('all')
const orderList = ref<OrderVO[]>([])
const orderLoading = ref(false)
const assessmentList = ref<EvaluationApplyRecordVO[]>([])
const assessmentLoading = ref(false)
const trainingList = ref<TrainingLearnRecordVO[]>([])
const trainingLoading = ref(false)

const getDetail = () => {
  // router/index.ts uses 'userId' for the param name
  const id = route.params && route.params.userId;
  if (id) {
    loading.value = true;
    getStudent(id as string).then(response => {
      const data = response.data;
      // 强制转换字典字段为字符串，确保 el-select 正确回显
      const dictFields = ['gender', 'userType', 'education', 'grade', 'internshipDuration', 'availability', 'jobType'];
      dictFields.forEach(field => {
        if (data[field] !== null && data[field] !== undefined) {
          data[field] = String(data[field]);
        }
      });
      
      form.value = data;
      originalForm.value = JSON.parse(JSON.stringify(data));
      loading.value = false;
      // 加载订单信息
      fetchOrderList();
      // 加载测评信息
      fetchAssessmentList();
      // 加载培训信息
      fetchTrainingList();
    }).catch(() => {
      loading.value = false;
    });
  }
}

const fetchOrderList = () => {
  const id = route.params && route.params.userId;
  if (!id) return;
  
  orderLoading.value = true;
  const query: any = {
    buyerId: id,
    buyerType: 2, // 学员
    pageNum: 1,
    pageSize: 100
  };
  
  if (orderSubTab.value !== 'all') {
    const statusMap: any = {
      'pending': 0,
      'completed': 1,
      'closed': 2,
      'refunding': 3
    };
    query.orderStatus = statusMap[orderSubTab.value];
  }
  
  listOrder(query).then(response => {
    orderList.value = response.rows || [];
    orderLoading.value = false;
  }).catch(() => {
    orderLoading.value = false;
  });
}

const fetchAssessmentList = () => {
  const id = route.params && route.params.userId;
  if (!id) return;
  
  assessmentLoading.value = true;
  listEvaluationRecord(id as string).then(response => {
    assessmentList.value = response.data || [];
    assessmentLoading.value = false;
  }).catch(() => {
    assessmentLoading.value = false;
  });
}

const fetchTrainingList = () => {
  const id = route.params && route.params.userId;
  if (!id) return;
  
  trainingLoading.value = true;
  listStudentTrainingRecords(id as string).then(response => {
    trainingList.value = response.data || [];
    trainingLoading.value = false;
  }).catch(() => {
    trainingLoading.value = false;
  });
}

watch(orderSubTab, () => {
  fetchOrderList();
});

onMounted(() => {
  getDetail()
})

const handleBack = () => {
  router.back()
}

/** 导出在线简历 */
const handleExport = () => {
  const userId = route.params && route.params.userId;
  if (!userId) return;
  // 调用后端 GET 接口：/main/student/exportResume/{id}
  proxy.$download.resource(`/main/student/exportResume/${userId}`);
}

/** 下载简历附件 */
const handleDownload = () => {
  const userId = route.params && route.params.userId;
  if (!userId) return;
  // 调用后端接口，后端会自动判断单文件或多文件打包
  proxy.$download.resource(`/main/student/downloadResume/${userId}`);
}

const jobData = ref([
  {
    company: 'XXXX公司',
    position: '审计A',
    type: '全职、实习、兼职',
    status: '在职',
    entryTime: '2023.12.12',
    leaveTime: '',
    reason: ''
  },
  {
    company: 'XXXX公司',
    position: '审计A',
    type: '全职',
    status: '离职',
    entryTime: '2024.12.12',
    leaveTime: '2025.12.01',
    reason: '个人发展'
  }
])

const evaluationOpen = ref(false)
const evaluationForm = reactive({
  score: 3.5,
  comment: '在职期间表现极佳',
  scoreA: 3,
  commentA: '在职期间表现极佳',
  scoreB: 3,
  commentB: '在职期间表现极佳'
})

const handleViewAssessment = async (row: EvaluationApplyRecordVO) => {
  const id = route.params && route.params.userId;
  if (!id) return;

  // 打开详情弹窗并加载数据
  assessmentDialog.visible = true;
  assessmentDialog.loading = true;
  assessmentDialog.evaluationName = row.evaluationName;
  assessmentDialog.abilityDetails = [];

  try {
    const res: any = await getEvaluationDetailResult(row.evaluationId, id);
    if (res.data) {
      assessmentDialog.abilityDetails = res.data.abilityDetails || [];
    }
  } catch (error) {
    console.error('获取测评详情失败:', error);
    proxy?.$modal.msgError('获取测评详情失败');
  } finally {
    assessmentDialog.loading = false;
  }
}

const handleOrderDetail = (order: OrderVO) => {
  router.push({
    path: '/system/order/detail',
    query: { id: order.id }
  })
}

const handleViewEvaluation = (row) => {
  evaluationOpen.value = true
}

// 测评详情弹窗
const assessmentDialog = reactive({
  visible: false,
  loading: false,
  evaluationName: '',
  abilityDetails: [] as any[]
})

const handleSave = () => {
  saveLoading.value = true;
  updateStudent(form.value as StudentForm).then(() => {
    proxy.$modal.msgSuccess('保存成功');
    originalForm.value = JSON.parse(JSON.stringify(form.value));
    isEditing.value = false;
    saveLoading.value = false;
  }).catch(() => {
    saveLoading.value = false;
  });
}

const handleCancel = () => {
  form.value = JSON.parse(JSON.stringify(originalForm.value));
  isEditing.value = false;
}
</script>

<style scoped lang="scss">
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
:deep(.el-tabs__active-bar) {
  height: 3px;
}
.order-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #f0f0f0;
  }
}
.order-item {
  transition: all 0.3s;
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
}

.ability-section-header {
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}
</style>
