<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <el-input v-model="queryParams.grade" placeholder="请输入年级" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课程体系" prop="curriculumSystem">
              <el-select v-model="queryParams.curriculumSystem" placeholder="课程体系" clearable style="width: 140px">
                <el-option v-for="opt in curriculumSystemOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="学生状态" clearable style="width: 160px">
                <el-option v-for="opt in studentStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:student:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:student:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:student:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:student:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="studentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学号" align="center" prop="studentNo" width="140" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="英文名" align="center" prop="englishName" width="100" show-overflow-tooltip />
        <el-table-column label="性别" align="center" prop="gender" width="70">
          <template #default="scope">
            <span>{{ getGenderLabel(scope.row.gender) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" width="130" />
        <el-table-column label="就读学校" align="center" prop="school" show-overflow-tooltip />
        <el-table-column label="年级" align="center" prop="grade" width="90" />
        <el-table-column label="课程体系" align="center" prop="curriculumSystem" width="100">
          <template #default="scope">
            <span>{{ getCurriculumLabel(scope.row.curriculumSystem) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="意向地区" align="center" prop="targetRegion" width="100" show-overflow-tooltip />
        <el-table-column label="目标专业" align="center" prop="targetMajor" width="110" show-overflow-tooltip />
        <el-table-column label="等级" align="center" prop="level" width="80" />
        <el-table-column label="意向" align="center" prop="intentLevel" width="70" />
        <el-table-column label="状态" align="center" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报名时间" align="center" prop="enrollAt" width="160">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.enrollAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="详情档案" placement="top">
              <el-button v-hasPermi="['edu:student:query']" link type="primary" icon="View" @click="handleProfile(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['edu:student:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:student:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 学生详情档案(完整生命周期) -->
    <student-profile ref="profileRef" />

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="960px" append-to-body>
      <el-form ref="studentFormRef" :model="form" :rules="rules" label-width="110px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学生姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="英文名" prop="englishName">
              <el-input v-model="form.englishName" placeholder="English Name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="form.studentNo" placeholder="留空自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio value="0">男</el-radio>
                <el-radio value="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="form.birthday" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">学校信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="就读学校" prop="school">
              <el-input v-model="form.school" placeholder="请输入就读学校" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年级" prop="grade">
              <el-input v-model="form.grade" placeholder="如: 高三" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目标学校" prop="targetSchool">
              <el-input v-model="form.targetSchool" placeholder="请输入目标学校" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="课程体系" prop="curriculumSystem">
              <el-select v-model="form.curriculumSystem" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in curriculumSystemOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选科/科目" prop="selectedSubjects">
              <el-input v-model="form.selectedSubjects" placeholder="如: 物理/化学/生物" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="国籍/地区" prop="nationality">
              <el-select v-model="form.nationality" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in nationalityOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">考试信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="考试语言" prop="examLanguage">
              <el-input v-model="form.examLanguage" placeholder="如: 中文/英文" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考生身份" prop="examIdentity">
              <el-input v-model="form.examIdentity" placeholder="如: 内地生/港澳台" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试地区" prop="examLocation">
              <el-input v-model="form.examLocation" placeholder="如: 广东/香港" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学术测试分" prop="academicTestScore">
              <el-input v-model="form.academicTestScore" placeholder="学术测试成绩" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="英语成绩" prop="englishScore">
              <el-input v-model="form.englishScore" placeholder="如: 雅思7.0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="听力成绩" prop="listeningScore">
              <el-input v-model="form.listeningScore" placeholder="听力模块成绩" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">升学规划</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="意向地区" prop="targetRegion">
              <el-input v-model="form.targetRegion" placeholder="如: 香港/英国/澳洲" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录取路径" prop="admissionPathway">
              <el-input v-model="form.admissionPathway" placeholder="如: 高考/国际生/持证" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目标专业" prop="targetMajor">
              <el-input v-model="form.targetMajor" placeholder="请输入目标专业" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="专业选择原因" prop="targetMajorReason">
              <el-input v-model="form.targetMajorReason" placeholder="为何选此专业" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请方案" prop="applicationPlan">
              <el-input v-model="form.applicationPlan" placeholder="申请方案概述" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人经历" prop="personalExperience">
              <el-input v-model="form.personalExperience" placeholder="竞赛/科研/实习等" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="健康状况" prop="hasHealthCondition">
              <el-select v-model="form.hasHealthCondition" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in ynOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="健康说明" prop="healthConditionNote">
              <el-input v-model="form.healthConditionNote" placeholder="如有健康问题请说明" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="政审要求" prop="needPoliticalReview">
              <el-select v-model="form.needPoliticalReview" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in ynOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="首次到访" prop="firstVisitAt">
              <el-date-picker v-model="form.firstVisitAt" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">客户管理</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学员等级" prop="level">
              <el-select v-model="form.level" placeholder="请选择" style="width: 100%">
                <el-option label="普通" value="普通" />
                <el-option label="VIP" value="VIP" />
                <el-option label="钻石" value="钻石" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="意向等级" prop="intentLevel">
              <el-select v-model="form.intentLevel" placeholder="请选择" style="width: 100%">
                <el-option v-for="lv in ['A', 'B', 'C', 'D']" :key="lv" :label="lv" :value="lv" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in studentStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生源渠道" prop="source">
              <el-input v-model="form.source" placeholder="如: 老带新/地推/线上" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="标签，逗号分隔" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入家庭住址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="特殊备注" prop="specialRemark">
          <el-input v-model="form.specialRemark" type="textarea" :rows="2" placeholder="重要备注信息" />
        </el-form-item>

        <!-- 家长子表 -->
        <el-divider content-position="left">家长信息</el-divider>
        <el-table border :data="form.parents" size="small">
          <el-table-column label="关系" width="120" align="center">
            <template #default="{ row }">
              <el-select v-model="row.relation" placeholder="关系" size="small">
                <el-option v-for="opt in parentRelationOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="姓名" min-width="100" align="center">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="姓名" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" min-width="130" align="center">
            <template #default="{ row }">
              <el-input v-model="row.phone" placeholder="手机号" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="主联系人" width="90" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.isPrimary" true-value="Y" false-value="N" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" @click="form.parents.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-2" type="primary" plain icon="Plus" size="small" @click="addParent">添加家长</el-button>

        <!-- 紧急联系人子表 -->
        <el-divider content-position="left">紧急联系人</el-divider>
        <el-table border :data="form.emergencies" size="small">
          <el-table-column label="姓名" min-width="110" align="center">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="姓名" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="关系" min-width="110" align="center">
            <template #default="{ row }">
              <el-input v-model="row.relation" placeholder="关系" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" min-width="130" align="center">
            <template #default="{ row }">
              <el-input v-model="row.phone" placeholder="手机号" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" @click="form.emergencies.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-2" type="primary" plain icon="Plus" size="small" @click="addEmergency">添加紧急联系人</el-button>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduStudent" lang="ts">
import { listStudent, getStudent, addStudent, updateStudent, delStudent } from '@/api/edu/student';
import StudentProfile from './profile.vue';
import {
  StudentForm,
  StudentQuery,
  StudentVO,
  studentStatusOptions,
  genderOptions,
  parentRelationOptions,
  ParentForm,
  EmergencyForm,
  curriculumSystemOptions,
  nationalityOptions,
  ynOptions
} from '@/api/edu/student/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const studentList = ref<StudentVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const studentFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const profileRef = ref();

const dialog = reactive<DialogOption>({ visible: false, title: '' });

const initFormData: StudentForm = {
  id: undefined,
  studentNo: '',
  name: '',
  englishName: '',
  gender: '0',
  birthday: '',
  idCard: '',
  phone: '',
  wechat: '',
  email: '',
  school: '',
  grade: '',
  targetSchool: '',
  subjects: '',
  examLanguage: '',
  examIdentity: '',
  nationality: 'MAINLAND',
  examLocation: '',
  curriculumSystem: '',
  selectedSubjects: '',
  hasHealthCondition: 'N',
  healthConditionNote: '',
  needPoliticalReview: 'N',
  applicationPlan: '',
  academicTestScore: '',
  personalExperience: '',
  englishScore: '',
  listeningScore: '',
  address: '',
  avatar: '',
  source: '',
  level: '普通',
  intentLevel: 'B',
  targetRegion: '',
  admissionPathway: '',
  targetMajor: '',
  targetMajorReason: '',
  firstVisitAt: '',
  enrollAt: '',
  tags: '',
  status: '0',
  remark: '',
  specialRemark: '',
  parents: [],
  emergencies: []
};

const data = reactive<PageData<StudentForm, StudentQuery>>({
  form: { ...initFormData, parents: [], emergencies: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentNo: '',
    name: '',
    phone: '',
    gender: '',
    grade: '',
    school: '',
    status: '',
    level: '',
    intentLevel: '',
    source: '',
    curriculumSystem: ''
  },
  rules: {
    name: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getStatusLabel = (val: string) => studentStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => studentStatusOptions.find((o) => o.value === val)?.elTagType || 'info';
const getGenderLabel = (val: string) => genderOptions.find((o) => o.value === val)?.label || val;
const getCurriculumLabel = (val: string) => curriculumSystemOptions.find((o) => o.value === val)?.label || val;

/** 查询学生列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStudent(queryParams.value);
  studentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData, parents: [], emergencies: [] };
  studentFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: StudentVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增学生';
};

/** 详情档案 */
const handleProfile = (row: StudentVO) => {
  profileRef.value?.open(row.id, row.name);
};

const handleUpdate = async (row?: StudentVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getStudent(id);
  Object.assign(form.value, res.data);
  // 确保子表有数据(后端可能返回空)
  form.value.parents = res.data.parents || [];
  form.value.emergencies = res.data.emergencies || [];
  dialog.visible = true;
  dialog.title = '修改学生';
};

const submitForm = () => {
  studentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updateStudent(form.value) : await addStudent(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const handleDelete = async (row?: StudentVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除学生编号为"' + delIds + '"的数据项？');
  await delStudent(delIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleExport = () => {
  proxy?.download('edu/student/export', { ...queryParams.value }, `student_${new Date().getTime()}.xlsx`);
};

/** 添加家长行 */
const addParent = () => {
  const item: ParentForm = {
    relation: 'FATHER',
    name: '',
    phone: '',
    wechat: '',
    email: '',
    idCard: '',
    occupation: '',
    isPrimary: form.value.parents.length === 0 ? 'Y' : 'N',
    receiveNotice: 'Y',
    remark: ''
  };
  form.value.parents.push(item);
};

/** 添加紧急联系人行 */
const addEmergency = () => {
  const item: EmergencyForm = {
    name: '',
    relation: '',
    phone: '',
    remark: ''
  };
  form.value.emergencies.push(item);
};

onMounted(() => {
  getList();
});
</script>
