<template>
  <el-drawer v-model="visible" :title="title" size="80%" append-to-body destroy-on-close>
    <div v-loading="loading">
      <template v-if="profile.student">
        <!-- 顶部概览: 学生头像+基本信息+核心指标 -->
        <el-card shadow="never" class="mb-3">
          <div class="profile-header">
            <el-avatar :size="64" :src="profile.student.avatar">
              {{ profile.student.name?.charAt(0) }}
            </el-avatar>
            <div class="profile-info">
              <div class="profile-name">
                {{ profile.student.name }}
                <el-tag size="small" :type="getStatusTag(profile.student.status)" class="ml-2">
                  {{ getStatusLabel(profile.student.status) }}
                </el-tag>
                <el-tag v-if="profile.student.level" size="small" type="warning" class="ml-1">{{ profile.student.level }}</el-tag>
                <el-tag v-if="profile.student.intentLevel" size="small" effect="plain" class="ml-1">意向{{ profile.student.intentLevel }}</el-tag>
              </div>
              <div class="profile-meta">
                <span><el-icon><Phone /></el-icon> {{ profile.student.phone || '-' }}</span>
                <span><el-icon><School /></el-icon> {{ profile.student.school || '-' }} · {{ profile.student.grade || '-' }}</span>
                <span v-if="profile.student.targetSchool"><el-icon><Aim /></el-icon> 目标: {{ profile.student.targetSchool }}</span>
              </div>
            </div>
          </div>
          <!-- 核心指标卡片 -->
          <el-row :gutter="10" class="mt-3">
            <el-col :span="4">
              <div class="metric"><div class="metric-num" style="color:#409eff">{{ profile.totalPurchasedHours || 0 }}</div><div class="metric-label">总购买课时</div></div>
            </el-col>
            <el-col :span="4">
              <div class="metric"><div class="metric-num" style="color:#e6a23c">{{ profile.totalConsumedHours || 0 }}</div><div class="metric-label">已消课时</div></div>
            </el-col>
            <el-col :span="4">
              <div class="metric"><div class="metric-num" style="color:#67c23a">{{ profile.totalRemainHours || 0 }}</div><div class="metric-label">剩余课时</div></div>
            </el-col>
            <el-col :span="4">
              <div class="metric"><div class="metric-num">{{ profile.totalLessonCount || 0 }}</div><div class="metric-label">消课次数</div></div>
            </el-col>
            <el-col :span="4">
              <div class="metric"><div class="metric-num" style="color:#f56c6c">¥{{ profile.totalAmount || 0 }}</div><div class="metric-label">合同总额</div></div>
            </el-col>
            <el-col :span="4">
              <div class="metric"><div class="metric-num" style="color:#67c23a">¥{{ profile.totalPaidAmount || 0 }}</div><div class="metric-label">累计实收</div></div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 生命周期标签页 -->
        <el-tabs v-model="activeTab">
          <!-- 合同记录 -->
          <el-tab-pane name="contract">
            <template #label>合同记录 <el-badge :value="profile.contracts?.length || 0" :max="99" /></template>
            <el-table border :data="profile.contracts" size="small">
              <el-table-column label="合同号" prop="contractNo" min-width="170" align="center" />
              <el-table-column label="类型" prop="contractType" width="90" align="center" />
              <el-table-column label="总课时" prop="totalHours" width="80" align="center" />
              <el-table-column label="剩余" prop="remainHours" width="70" align="center" />
              <el-table-column label="总额" prop="totalAmount" width="100" align="center" />
              <el-table-column label="实收" prop="paidAmount" width="100" align="center" />
              <el-table-column label="状态" width="90" align="center">
                <template #default="{ row }">
                  <el-tag :type="contractStatusMap[row.status]?.tag || 'info'" size="small">{{ contractStatusMap[row.status]?.label || row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="签约日" prop="signDate" width="110" align="center">
                <template #default="{ row }">{{ parseDay(row.signDate) }}</template>
              </el-table-column>
              <el-table-column label="到期日" prop="expireDate" width="110" align="center">
                <template #default="{ row }">{{ parseDay(row.expireDate) }}</template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 排课记录 -->
          <el-tab-pane name="schedule">
            <template #label>排课记录 <el-badge :value="profile.schedules?.length || 0" :max="99" /></template>
            <el-table border :data="profile.schedules" size="small">
              <el-table-column label="上课日期" prop="lessonDate" width="110" align="center">
                <template #default="{ row }">{{ parseDay(row.lessonDate) }}</template>
              </el-table-column>
              <el-table-column label="时间" width="140" align="center">
                <template #default="{ row }">{{ parseHM(row.startTime) }} - {{ parseHM(row.endTime) }}</template>
              </el-table-column>
              <el-table-column label="学科" prop="subject" width="80" align="center" />
              <el-table-column label="课型" prop="lessonType" width="90" align="center" />
              <el-table-column label="课时" prop="durationHours" width="70" align="center" />
              <el-table-column label="消课" prop="consumeHours" width="70" align="center" />
              <el-table-column label="状态" width="90" align="center">
                <template #default="{ row }">
                  <el-tag :type="scheduleStatusMap[row.status]?.tag || 'info'" size="small">{{ scheduleStatusMap[row.status]?.label || row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="课堂内容" prop="lessonContent" min-width="160" align="center" show-overflow-tooltip />
              <el-table-column label="课堂点评" prop="comment" min-width="160" align="center" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>

          <!-- 课时流水 -->
          <el-tab-pane name="hours">
            <template #label>课时流水 <el-badge :value="profile.hoursLogs?.length || 0" :max="99" /></template>
            <el-table border :data="profile.hoursLogs" size="small">
              <el-table-column label="时间" width="160" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.logTime) }}</template>
              </el-table-column>
              <el-table-column label="业务类型" width="110" align="center">
                <template #default="{ row }">
                  <el-tag :type="hoursBizTypeOptions.find(o=>o.value===row.businessType)?.elTagType || 'info'" size="small">
                    {{ hoursBizTypeOptions.find(o=>o.value===row.businessType)?.label || row.businessType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="方向" width="70" align="center">
                <template #default="{ row }">
                  <span :style="{color: row.direction==='+'?'#67c23a':'#f56c6c',fontWeight:600}">{{ row.direction }}</span>
                </template>
              </el-table-column>
              <el-table-column label="变动课时" width="90" align="center">
                <template #default="{ row }">
                  <span :style="{color: row.direction==='+'?'#67c23a':'#f56c6c'}">{{ row.direction }}{{ row.hours }}</span>
                </template>
              </el-table-column>
              <el-table-column label="变动前" prop="beforeHours" width="80" align="center" />
              <el-table-column label="变动后" prop="afterHours" width="80" align="center" />
              <el-table-column label="原因" prop="reason" min-width="180" align="center" show-overflow-tooltip />
              <el-table-column label="操作人" prop="operatorName" width="90" align="center" />
            </el-table>
          </el-tab-pane>

          <!-- 预警 -->
          <el-tab-pane name="alert">
            <template #label>
              预警 <el-badge v-if="pendingAlerts > 0" :value="pendingAlerts" type="danger" />
            </template>
            <el-empty v-if="!profile.alerts?.length" description="暂无预警记录" />
            <el-table v-else border :data="profile.alerts" size="small">
              <el-table-column label="级别" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="alertLevelTag(row.level)" size="small">{{ alertLevelLabel(row.level) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="类型" width="100" align="center">
                <template #default="{ row }">{{ alertTypeLabel(row.alertType) }}</template>
              </el-table-column>
              <el-table-column label="内容" prop="content" min-width="220" align="center" show-overflow-tooltip />
              <el-table-column label="状态" width="90" align="center">
                <template #default="{ row }">
                  <el-tag :type="alertStatusTag(row.status)" size="small">{{ alertStatusLabel(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="时间" width="160" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.createTime) }}</template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 服务团队 -->
          <el-tab-pane name="staff">
            <template #label>服务团队 <el-badge :value="profile.currentStaff?.length || 0" :max="99" type="primary" /></template>
            <el-descriptions title="当前服务团队" :column="4" border class="mb-4">
              <el-descriptions-item v-for="s in profile.currentStaff" :key="s.id" :label="staffRoleMap[s.role] || s.role">
                {{ s.name }}（{{ s.staffNo }}）
                <div class="staff-phone">{{ s.phone }}</div>
              </el-descriptions-item>
              <el-descriptions-item v-if="!profile.currentStaff?.length" label="暂无">-</el-descriptions-item>
            </el-descriptions>
            <el-divider content-position="left">服务变更历史</el-divider>
            <el-table border :data="profile.staffHistory" size="small">
              <el-table-column label="角色" width="110" align="center">
                <template #default="{ row }">{{ staffRoleMap[row.staffRole] || row.staffRole }}</template>
              </el-table-column>
              <el-table-column label="员工ID" prop="staffId" width="90" align="center" />
              <el-table-column label="绑定时间" width="160" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.bindTime) }}</template>
              </el-table-column>
              <el-table-column label="解绑时间" width="160" align="center">
                <template #default="{ row }">{{ row.unbindTime ? proxy.parseTime(row.unbindTime) : '-' }}</template>
              </el-table-column>
              <el-table-column label="状态" width="90" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === '0' ? 'success' : 'info'" size="small">{{ row.status === '0' ? '生效中' : '已解绑' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="主责" width="70" align="center">
                <template #default="{ row }">{{ row.isPrimary === 'Y' ? '是' : '否' }}</template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 约谈记录 -->
          <el-tab-pane name="interview">
            <template #label>约谈记录 <el-badge :value="profile.interviews?.length || 0" :max="99" type="primary" /></template>
            <el-empty v-if="!profile.interviews?.length" description="暂无约谈记录" />
            <el-table v-else border :data="profile.interviews" size="small">
              <el-table-column label="约谈时间" width="150" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.interviewTime) }}</template>
              </el-table-column>
              <el-table-column label="方式" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="interviewMethodTag(row.method)" size="small">{{ interviewMethodLabel(row.method) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="地点" prop="location" width="100" align="center" show-overflow-tooltip />
              <el-table-column label="谈话主题" prop="topic" min-width="140" align="center" show-overflow-tooltip />
              <el-table-column label="约谈人" prop="interviewerName" width="90" align="center" />
              <el-table-column label="结论" width="110" align="center">
                <template #default="{ row }">
                  <el-tag :type="interviewResultTag(row.result)" size="small">{{ interviewResultLabel(row.result) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="下次跟进" width="130" align="center">
                <template #default="{ row }">
                  <span v-if="row.followStatus === '2'" class="text-gray-400">无需跟进</span>
                  <span v-else-if="row.followStatus === '1'">{{ proxy.parseTime(row.nextFollowTime, '{y}-{m}-{d}') }}</span>
                  <span v-else :class="{ 'text-red-500 font-bold': row.nextFollowTime && new Date(row.nextFollowTime) < new Date() }">
                    {{ row.nextFollowTime ? proxy.parseTime(row.nextFollowTime, '{y}-{m}-{d}') : '-' }}
                    <el-tag v-if="row.nextFollowTime && new Date(row.nextFollowTime) < new Date()" type="danger" size="small" class="ml-1">逾期</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="跟进状态" width="90" align="center">
                <template #default="{ row }">
                  <el-tag :type="followStatusTag(row.followStatus)" size="small">{{ followStatusLabel(row.followStatus) }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 考试成绩 -->
          <el-tab-pane name="exam">
            <template #label>考试成绩 <el-badge :value="profile.exams?.length || 0" :max="99" /></template>
            <el-empty v-if="!profile.exams?.length" description="暂无考试记录" />
            <el-table v-else border :data="profile.exams" size="small">
              <el-table-column label="考试名称" prop="examName" min-width="160" align="center" show-overflow-tooltip />
              <el-table-column label="考试日期" width="110" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.examDate, '{y}-{m}-{d}') }}</template>
              </el-table-column>
              <el-table-column label="类型" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="examTypeTag(row.examType)" size="small">{{ examTypeLabel(row.examType) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="科目" prop="subject" width="80" align="center" />
              <el-table-column label="学校" prop="school" width="120" align="center" show-overflow-tooltip />
              <el-table-column label="总分" prop="totalScore" width="80" align="center" />
              <el-table-column label="录入人" prop="recorderName" width="90" align="center" />
            </el-table>
          </el-tab-pane>

          <!-- 奖惩记录 -->
          <el-tab-pane name="reward">
            <template #label>奖惩记录 <el-badge :value="profile.rewardPunishes?.length || 0" :max="99" /></template>
            <el-empty v-if="!profile.rewardPunishes?.length" description="暂无奖惩记录" />
            <el-table v-else border :data="profile.rewardPunishes" size="small">
              <el-table-column label="类型" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="rpTypeTag(row.type)" size="small">{{ rpTypeLabel(row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="分类" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="rpCategoryTag(row.category)" effect="plain" size="small">{{ rpCategoryLabel(row.category) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="标题" prop="title" min-width="160" align="center" show-overflow-tooltip />
              <el-table-column label="发生时间" width="110" align="center">
                <template #default="{ row }">{{ proxy.parseTime(row.occurTime, '{y}-{m}-{d}') }}</template>
              </el-table-column>
              <el-table-column label="分值变动" width="100" align="center">
                <template #default="{ row }">
                  <span :style="{ color: row.scoreChange >= 0 ? '#67c23a' : '#f56c6c', fontWeight: 600 }">
                    {{ row.scoreChange >= 0 ? '+' : '' }}{{ row.scoreChange || 0 }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="处理人" prop="handlerName" width="90" align="center" />
              <el-table-column label="状态" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="rpStatusTag(row.status)" size="small">{{ rpStatusLabel(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="描述" prop="description" min-width="160" align="center" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>

          <!-- 家长 & 紧急联系人 -->
          <el-tab-pane name="contact">
            <template #label>家长/联系人</template>
            <el-descriptions title="家长信息" :column="2" border class="mb-4">
              <template v-if="profile.student.parents?.length">
                <el-descriptions-item v-for="p in profile.student.parents" :key="p.id" :label="parentRelationLabel(p.relation)">
                  {{ p.name }} · {{ p.phone }}
                  <el-tag v-if="p.isPrimary === 'Y'" size="small" type="success" class="ml-1">主联系人</el-tag>
                </el-descriptions-item>
              </template>
              <el-descriptions-item v-else label="暂无">-</el-descriptions-item>
            </el-descriptions>
            <el-divider content-position="left">紧急联系人</el-divider>
            <el-table border :data="profile.student.emergencies" size="small">
              <el-table-column label="姓名" prop="name" align="center" />
              <el-table-column label="关系" prop="relation" align="center" />
              <el-table-column label="电话" prop="phone" align="center" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { getStudentProfile } from '@/api/edu/profile';
import {
  StudentProfileVO,
  hoursBizTypeOptions,
  staffRoleMap,
  contractStatusMap,
  scheduleStatusMap
} from '@/api/edu/profile/types';
import { studentStatusOptions, parentRelationOptions } from '@/api/edu/student/types';
import { alertTypeOptions, alertLevelOptions, alertStatusOptions } from '@/api/edu/alert/types';
import { interviewMethodOptions, interviewResultOptions, followStatusOptions } from '@/api/edu/interview/types';
import { examTypeOptions } from '@/api/edu/exam/types';
import { rpTypeOptions, rpCategoryOptions, rpStatusOptions } from '@/api/edu/reward/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const visible = ref(false);
const loading = ref(false);
const title = ref('学生档案');
const activeTab = ref('contract');
const profile = ref<Partial<StudentProfileVO>>({});

// 字典辅助
const getStatusLabel = (v: string) => studentStatusOptions.find((o) => o.value === v)?.label || v;
const getStatusTag = (v: string) => studentStatusOptions.find((o) => o.value === v)?.elTagType || 'info';
const parentRelationLabel = (v: string) => parentRelationOptions.find((o) => o.value === v)?.label || v;
const alertTypeLabel = (v: string) => alertTypeOptions.find((o) => o.value === v)?.label || v;
const alertLevelLabel = (v: string) => alertLevelOptions.find((o) => o.value === v)?.label || v;
const alertLevelTag = (v: string) => alertLevelOptions.find((o) => o.value === v)?.elTagType || 'info';
const alertStatusLabel = (v: string) => alertStatusOptions.find((o) => o.value === v)?.label || v;
const alertStatusTag = (v: string) => alertStatusOptions.find((o) => o.value === v)?.elTagType || 'info';

// 约谈字典
const interviewMethodLabel = (v: string) => interviewMethodOptions.find((o) => o.value === v)?.label || v;
const interviewMethodTag = (v: string) => interviewMethodOptions.find((o) => o.value === v)?.elTagType || 'info';
const interviewResultLabel = (v: string) => interviewResultOptions.find((o) => o.value === v)?.label || v;
const interviewResultTag = (v: string) => interviewResultOptions.find((o) => o.value === v)?.elTagType || 'info';
const followStatusLabel = (v: string) => followStatusOptions.find((o) => o.value === v)?.label || v;
const followStatusTag = (v: string) => followStatusOptions.find((o) => o.value === v)?.elTagType || 'info';

// 考试字典
const examTypeLabel = (v: string) => examTypeOptions.find((o) => o.value === v)?.label || v;
const examTypeTag = (v: string) => examTypeOptions.find((o) => o.value === v)?.elTagType || 'info';

// 奖惩字典
const rpTypeLabel = (v: string) => rpTypeOptions.find((o) => o.value === v)?.label || v;
const rpTypeTag = (v: string) => rpTypeOptions.find((o) => o.value === v)?.elTagType || 'info';
const rpCategoryLabel = (v: string) => rpCategoryOptions.find((o) => o.value === v)?.label || v;
const rpCategoryTag = (v: string) => rpCategoryOptions.find((o) => o.value === v)?.elTagType || 'info';
const rpStatusLabel = (v: string) => rpStatusOptions.find((o) => o.value === v)?.label || v;
const rpStatusTag = (v: string) => rpStatusOptions.find((o) => o.value === v)?.elTagType || 'info';

const parseDay = (d: string) => (d ? proxy.parseTime(d, '{y}-{m}-{d}') : '-');
const parseHM = (d: string) => (d ? proxy.parseTime(d, '{h}:{i}') : '-');

/** 待处理预警数(badge) */
const pendingAlerts = computed(() => profile.value.alerts?.filter((a) => a.status === '0').length || 0);

/** 打开抽屉 */
const open = async (studentId: number | string, studentName?: string) => {
  visible.value = true;
  activeTab.value = 'contract';
  loading.value = true;
  try {
    const res = await getStudentProfile(studentId);
    profile.value = res.data;
    title.value = `学生档案 - ${studentName || profile.value.student?.name || ''}`;
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<style scoped>
.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
}
.profile-info {
  flex: 1;
}
.profile-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 6px;
}
.profile-meta {
  color: #909399;
  font-size: 13px;
  display: flex;
  gap: 20px;
}
.profile-meta span {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.metric {
  text-align: center;
  padding: 8px 0;
}
.metric-num {
  font-size: 22px;
  font-weight: 700;
  line-height: 1.3;
}
.metric-label {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
.staff-phone {
  font-size: 12px;
  color: #909399;
}
:deep(.el-tabs__content) {
  overflow: visible;
}
</style>
