<template>
  <PageShell>
    <div class="apply-detail-page" v-loading="loading">
      <div class="apply-detail-card profile-card">
        <div class="profile-left">
          <img class="profile-avatar" :src="profileAvatar" alt="avatar" />
          <el-link type="primary" :underline="false">{{ profileAvailability }}</el-link>
        </div>
        <div class="profile-main">
          <div class="profile-name-row">
            <span class="profile-name">{{ student.name || '--' }}</span>
            <span v-if="student.gender === '0'" class="profile-gender">♂</span>
            <span v-else-if="student.gender === '1'" class="profile-gender female">♀</span>
          </div>
          <div class="profile-grid">
            <div class="profile-item"><span>身份证号</span><span>{{ displayText(student.idCardNumber) }}</span></div>
            <div class="profile-item"><span>联系电话</span><span>{{ displayText(student.mobile) }}</span></div>
            <div class="profile-item"><span>电子邮箱</span><span>{{ displayText(student.email) }}</span></div>
            <div class="profile-item"><span>求职意向</span><span>{{ displayText(student.jobIntention) }}</span></div>
            <div class="profile-item"><span>求职类型</span><span>{{ profileJobType }}</span></div>
            <div class="profile-item"><span>毕业院校</span><span>{{ profileSchool }}</span></div>
            <div class="profile-item"><span>实习时长</span><span>{{ profileInternshipDuration }}</span></div>
            <div class="profile-item"><span>注册日期</span><span>{{ formatDateTime(student.createTime) }}</span></div>
            <div class="profile-item"><span>最后更新</span><span>{{ formatDateTime(student.updateTime) }}</span></div>
          </div>
        </div>
      </div>

      <div class="apply-detail-card tabs-card">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="在线简历" name="resume" />
          <el-tab-pane label="测评信息" name="evaluation" />
          <el-tab-pane label="培训信息" name="training" />
          <el-tab-pane label="任职信息" name="job" />
        </el-tabs>

        <div v-if="activeTab === 'resume'" class="detail-section-list">
          <div class="detail-section">
            <div class="section-title">教育经历</div>
            <el-table :data="educationList" border empty-text="暂无教育经历">
              <el-table-column label="学校" prop="school" min-width="120" />
              <el-table-column label="学历" prop="education" min-width="120" />
              <el-table-column label="时间" prop="period" min-width="160" />
              <el-table-column label="专业" prop="major" min-width="120" />
              <el-table-column label="在校经历" prop="campusExperience" min-width="180" show-overflow-tooltip />
            </el-table>
          </div>

          <div class="detail-section">
            <div class="section-title">工作经历</div>
            <el-table :data="workList" border empty-text="暂无工作经历">
              <el-table-column label="公司" prop="company" min-width="140" />
              <el-table-column label="行业" prop="industry" min-width="120" />
              <el-table-column label="时间" prop="period" min-width="160" />
              <el-table-column label="职位" prop="jobTitle" min-width="120" />
              <el-table-column label="所属部门" prop="department" min-width="140" />
              <el-table-column label="工作内容" prop="workContent" min-width="160" show-overflow-tooltip />
            </el-table>
          </div>

          <div class="detail-section">
            <div class="section-title">项目经历</div>
            <el-table :data="projectList" border empty-text="暂无项目经历">
              <el-table-column label="项目" prop="projectName" min-width="140" />
              <el-table-column label="担任角色" prop="role" min-width="120" />
              <el-table-column label="时间" prop="period" min-width="160" />
              <el-table-column label="描述" prop="description" min-width="160" show-overflow-tooltip />
              <el-table-column label="业绩" prop="achievement" min-width="160" show-overflow-tooltip />
              <el-table-column label="链接" prop="link" min-width="160" show-overflow-tooltip />
            </el-table>
          </div>
        </div>

        <div v-else-if="activeTab === 'evaluation'" class="detail-section-list">
          <div class="detail-section">
            <div class="section-title">测评信息</div>
            <el-table :data="evaluationList" border empty-text="暂无测评信息">
              <el-table-column label="名称" prop="name" min-width="140" />
              <el-table-column label="岗位" prop="post" min-width="140" />
              <el-table-column label="结果" prop="result" min-width="160" />
              <el-table-column label="测评时间" prop="evaluateTime" min-width="180" />
            </el-table>
          </div>
        </div>

        <div v-else-if="activeTab === 'training'" class="detail-section-list">
          <div class="detail-section">
            <div class="section-title">培训信息</div>
            <el-table :data="trainingList" border empty-text="暂无培训信息">
              <el-table-column label="名称" prop="name" min-width="180" />
              <el-table-column label="培训方式" prop="type" min-width="140" />
              <el-table-column label="培训时间" prop="time" min-width="180" />
            </el-table>
          </div>
        </div>

        <div v-else-if="activeTab === 'job'" class="detail-section-list">
          <div class="detail-section">
            <div class="section-title">任职信息</div>
            <el-table :data="jobList" border empty-text="暂无任职信息">
              <el-table-column label="公司" prop="company" min-width="140" />
              <el-table-column label="岗位" prop="post" min-width="120" />
              <el-table-column label="岗位类型" prop="postType" min-width="140" />
              <el-table-column label="任职状态" prop="status" min-width="140" />
              <el-table-column label="入职时间" prop="entryTime" min-width="160" />
              <el-table-column label="离职时间" prop="leaveTime" min-width="160" />
              <el-table-column label="离职原因" prop="leaveReason" min-width="140" />
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </PageShell>
</template>

<script setup name="PostManageApplyDetail" lang="ts">
import { computed, getCurrentInstance, onMounted, ref, type ComponentInternalInstance } from 'vue';
import { useRoute } from 'vue-router';
import PageShell from '@/components/PageShell/index.vue';
import defaultAvatar from '@/assets/images/user.jpg';
import { getStudentInfo, type MainStudentEducationVO, type MainStudentExperienceVO, type MainStudentProjectVO, type MainStudentVO, type MainExamApplyRecordVO, type StudentTrainingRecordVO, type StudentJobRecordVO } from '@/api/main/student';
import { getDicts } from '@/api/system/dict/data';
import type { DictDataVO } from '@/api/system/dict/data/types';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const loading = ref(false);
const activeTab = ref('resume');
const student = ref<MainStudentVO>({});
const jobTypeOptions = ref<DictDataVO[]>([]);
const educationOptions = ref<DictDataVO[]>([]);
const gradeOptions = ref<DictDataVO[]>([]);
const internshipDurationOptions = ref<DictDataVO[]>([]);
const arrivalTimeOptions = ref<DictDataVO[]>([]);

const displayText = (value?: string | number | null) => {
  if (value === null || value === undefined) {
    return '--';
  }
  const text = String(value).trim();
  return text ? text : '--';
};

const getDictLabel = (options: DictDataVO[], value?: string | null) => {
  if (!value) {
    return '';
  }
  return options.find((item) => item.dictValue === value)?.dictLabel || value;
};

const getMultiDictLabel = (options: DictDataVO[], value?: string | null) => {
  if (!value) {
    return '--';
  }
  const values = value
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
  if (!values.length) {
    return '--';
  }
  return values.map((item) => getDictLabel(options, item)).join('、');
};

const formatDateTime = (value?: string | null) => parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}') || '--';

const formatPeriod = (startTime?: string, endTime?: string) => {
  const start = (startTime || '').trim();
  const end = (endTime || '').trim();
  if (start && end) {
    return `${start} - ${end}`;
  }
  return start || end || '--';
};

const profileAvatar = computed(() => student.value.avatarUrl || defaultAvatar);
const profileAvailability = computed(() => getDictLabel(arrivalTimeOptions.value, student.value.availability) || displayText(student.value.availability));
const profileJobType = computed(() => getMultiDictLabel(jobTypeOptions.value, student.value.jobType));
const profileInternshipDuration = computed(
  () => getDictLabel(internshipDurationOptions.value, student.value.internshipDuration) || displayText(student.value.internshipDuration)
);
const profileSchool = computed(() => {
  const schoolName = student.value.schoolName?.trim() || '';
  const education = getDictLabel(educationOptions.value, student.value.education);
  const grade = getDictLabel(gradeOptions.value, student.value.grade);
  return [schoolName, education, grade].filter(Boolean).join(' ') || '--';
});

const educationList = computed(() =>
  (student.value.educationList || []).map((item: MainStudentEducationVO) => ({
    ...item,
    education: getDictLabel(educationOptions.value, item.education) || displayText(item.education),
    period: formatPeriod(item.startTime, item.endTime),
    campusExperience: displayText(item.campusExperience)
  }))
);

const workList = computed(() =>
  (student.value.experienceList || []).map((item: MainStudentExperienceVO) => ({
    ...item,
    period: item.isInternship === 1 ? `${formatPeriod(item.startTime, item.endTime)}（实习）` : formatPeriod(item.startTime, item.endTime),
    workContent: displayText(item.workContent)
  }))
);

const projectList = computed(() =>
  (student.value.projectList || []).map((item: MainStudentProjectVO) => ({
    ...item,
    period: formatPeriod(item.startTime, item.endTime),
    description: displayText(item.description),
    achievement: displayText(item.achievement),
    link: displayText(item.link)
  }))
);

const evaluationList = computed(() =>
  (student.value.evaluationList || []).map((item: MainExamApplyRecordVO) => ({
    name: displayText(item.evaluationName),
    post: displayText(item.positionName),
    result: displayText(item.statusText || item.finalResult),
    evaluateTime: formatDateTime(item.finishedTime || item.createTime)
  }))
);

const trainingList = computed(() =>
  (student.value.trainingList || []).map((item: StudentTrainingRecordVO) => {
    // 培训方式
    let type = '--';
    if (item.trainingType === 'video') {
      type = item.progress === 100 ? '线上(已完成)' : item.progress != null ? `线上(学习中 ${item.progress}%)` : '线上';
    } else if (item.trainingType === 'offline') {
      type = '线下';
      if (item.enrollStatus === 3) type = '线下(已签到)';
      else if (item.enrollStatus === 1) type = '线下(已通过)';
      else if (item.enrollStatus === 0) type = '线下(待审核)';
    } else if (item.trainingType === 'live') {
      type = '直播';
    }
    // 培训时间
    const time = formatPeriod(
      item.trainingStartTime?.split(' ')[0] || '',
      item.trainingEndTime?.split(' ')[0] || ''
    );
    return {
      name: displayText(item.name),
      type,
      time
    };
  })
);

const jobList = computed(() =>
  (student.value.jobList || []).map((item: StudentJobRecordVO) => ({
    company: displayText(item.companyName),
    post: displayText(item.postName),
    postType: displayText(item.postType),
    status: item.employmentStatus === 'onboard' ? '在职' : item.employmentStatus === 'left' ? '已离职' : displayText(item.employmentStatus),
    entryTime: formatDateTime(item.entryTime),
    leaveTime: formatDateTime(item.leaveTime),
    leaveReason: item.employmentStatus === 'onboard' ? '--' : displayText(item.leaveReason)
  }))
);

const loadDicts = async () => {
  const [jobTypeRes, educationRes, gradeRes, internshipDurationRes, arrivalTimeRes] = await Promise.all([
    getDicts('main_position_type'),
    getDicts('main_education'),
    getDicts('main_experience'),
    getDicts('main_internship_duration'),
    getDicts('main_arrival_time')
  ]);
  jobTypeOptions.value = jobTypeRes.data || [];
  educationOptions.value = educationRes.data || [];
  gradeOptions.value = gradeRes.data || [];
  internshipDurationOptions.value = internshipDurationRes.data || [];
  arrivalTimeOptions.value = arrivalTimeRes.data || [];
};

const loadStudentDetail = async () => {
  const studentId = route.query.studentId as string | undefined;
  if (!studentId) {
    proxy?.$modal.msgWarning('学员ID不能为空');
    student.value = {};
    return;
  }
  loading.value = true;
  try {
    const res = await getStudentInfo(studentId);
    student.value = res.data || {};
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await Promise.all([loadDicts(), loadStudentDetail()]);
});
</script>

<style scoped>
.apply-detail-page {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.apply-detail-card {
  padding: 16px 20px;
  background: #fff;
  border-radius: 6px;
}

.profile-card {
  display: flex;
  gap: 16px;
}

.profile-left {
  width: 96px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.profile-avatar {
  width: 96px;
  height: 96px;
  border-radius: 12px;
  object-fit: cover;
}

.profile-main {
  flex: 1;
}

.profile-name-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
}

.profile-name {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.profile-gender {
  color: #409eff;
}

.profile-gender.female {
  color: #f56c6c;
}

.profile-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px 24px;
}

.profile-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #606266;
  font-size: 13px;
}

.profile-item span:last-child {
  color: #303133;
}

.tabs-card :deep(.el-tabs__header) {
  margin-bottom: 16px;
}

.detail-section-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.section-title {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style>
