<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="学生" prop="searchKey">
        <el-input v-model="queryParams.searchKey" placeholder="学号/姓名/身份证号" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="在校状态" prop="studentStatus" label-width="100">
        <el-select v-model="queryParams.studentStatus" clearable style="width: 200px;">
          <el-option v-for="dict in student_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="体检结果" prop="physicalExamResult" label-width="100">
        <el-select v-model="queryParams.physicalExamResult" clearable style="width: 200px;">
          <el-option v-for="dict in physical_exam_result" :key="dict.value" :label="dict.label" :value="dict.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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="studentList">
      <el-table-column label="学号" prop="studentId" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="性别" prop="gender_dictText" :show-overflow-tooltip="true" width="70" align="center" />
      <el-table-column label="年龄" prop="age" :show-overflow-tooltip="true" width="70" align="center" />
      <el-table-column label="身份证号" prop="idNumber" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="电话" prop="phone" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="学院" prop="college" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="专业" prop="major" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="年级" prop="grade" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="学历层次" prop="educationLevel_dictText" :show-overflow-tooltip="true" width="120"
        align="center" />
      <el-table-column label="入校时间" prop="enrollmentDate" :show-overflow-tooltip="true" width="120" align="center" />
      <el-table-column label="离校时间" prop="graduationDate" :show-overflow-tooltip="true" width="120" align="center" />
      <el-table-column label="学习形式" prop="studyMode_dictText" :show-overflow-tooltip="true" width="120"
        align="center" />
      <el-table-column label="在校状态" prop="studentStatus_dictText" :show-overflow-tooltip="true" width="100"
        align="center" />
      <el-table-column label="体检结果" prop="physicalExamResult_dictText" :show-overflow-tooltip="true" width="120"
        align="center" />
      <el-table-column label="辅导员" width="120">
        <template #default="scope">
          <span v-if="scope.row.counselor !== null && scope.row.counselor !== undefined && scope.row.counselor !== ''">
            {{ scope.row.counselor }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="辅导员电话" width="170">
        <template #default="scope">
          <span
            v-if="scope.row.counselorPhone !== null && scope.row.counselorPhone !== undefined && scope.row.counselorPhone !== ''">
            {{ scope.row.counselorPhone }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="studentListRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 左侧列 -->
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="form.studentId" placeholder="请输入学号" style="width: 100%" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" style="width: 100%" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio v-for="dict in sys_user_sex" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input :disabled="true" v-model="form.age" placeholder="根据身份证自动计算，无需填写" style="width: 100%" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号" style="width: 100%" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话" style="width: 100%" />
            </el-form-item>
            <el-form-item label="学院" prop="college">
              <el-input v-model="form.college" placeholder="请输入学院" style="width: 100%" />
            </el-form-item>
            <el-form-item label="专业" prop="major">
              <el-input v-model="form.major" placeholder="请输入专业" style="width: 100%" />
            </el-form-item>
          </el-col>

          <!-- 右侧列 -->
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-input v-model="form.grade" placeholder="请输入年级" style="width: 100%" />
            </el-form-item>
            <el-form-item label="学历层次" prop="educationLevel">
              <el-select v-model="form.educationLevel" clearable style="width: 100%">
                <el-option v-for="dict in education_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="入校时间" prop="enrollmentDate">
              <el-date-picker v-model="form.enrollmentDate" type="date" placeholder="请选择入校时间" value-format="YYYY-MM-DD"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="离校时间" prop="graduationDate">
              <el-date-picker v-model="form.graduationDate" type="date" placeholder="请选择离校时间" value-format="YYYY-MM-DD"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="学习形式" prop="studyMode">
              <el-select v-model="form.studyMode" clearable style="width: 100%">
                <el-option v-for="dict in study_mode" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="在校状态" prop="studentStatus">
              <el-select v-model="form.studentStatus" clearable style="width: 100%">
                <el-option v-for="dict in student_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="体检结果" prop="physicalExamResult">
              <el-select v-model="form.physicalExamResult" clearable style="width: 100%">
                <el-option v-for="dict in physical_exam_result" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="辅导员" prop="counselor">
              <el-input v-model="form.counselor" placeholder="请输入辅导员" style="width: 100%" />
            </el-form-item>
            <el-form-item label="辅导员电话" prop="counselorPhone">
              <el-input v-model="form.counselorPhone" placeholder="请输入辅导员电话" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GfStudentList">
import { getToken } from "@/utils/auth";
import {
  getPage,
  getDetail,
  add,
  edit,
  remove
} from "@/api/gf/studentList";

const { proxy } = getCurrentInstance();
const {
  sys_user_sex,
  education_level,
  study_mode,
  student_status,
  physical_exam_result
} = proxy.useDict(
  "sys_user_sex",
  "education_level",
  "study_mode",
  "student_status",
  "physical_exam_result",
);

const studentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

/*** 器材目录导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/nenu/gf-student-list/import-data"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    searchKey: undefined,
    studentStatus: undefined,
    physicalExamResult: undefined,
  },
  rules: {
    studentId: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "blur" }
    ],
    idNumber: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "电话不能为空", trigger: "blur" }
    ],
    college: [
      { required: true, message: "学院不能为空", trigger: "blur" }
    ],
    major: [
      { required: true, message: "专业不能为空", trigger: "blur" }
    ],
    grade: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    educationLevel: [
      { required: true, message: "学历层次不能为空", trigger: "blur" }
    ],
    enrollmentDate: [
      { required: true, message: "入校时间不能为空", trigger: "blur" }
    ],
    graduationDate: [
      { required: true, message: "离校时间不能为空", trigger: "blur" }
    ],
    studyMode: [
      { required: true, message: "学习形式不能为空", trigger: "blur" }
    ],
    studentStatus: [
      { required: true, message: "在校状态不能为空", trigger: "blur" }
    ],
    physicalExamResult: [
      { required: true, message: "体检结果不能为空", trigger: "blur" }
    ],
  },
});

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

/** 查询学生名单 */
function getList() {
  loading.value = true;
  getPage(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    studentList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    gender: undefined,
    age: undefined,
    studentId: undefined,
    idNumber: undefined,
    phone: undefined,
    college: undefined,
    major: undefined,
    educationLevel: undefined,
    enrollmentDate: undefined,
    graduationDate: undefined,
    grade: undefined,
    studyMode: undefined,
    studentStatus: undefined,
    physicalExamResult: undefined,
    counselor: undefined,
    counselorPhone: undefined,
    patientId: undefined,
  };
  proxy.resetForm("studentListRef");
}
/** 添加学生 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生信息";
}
/** 修改学生 */
function handleUpdate(row) {
  reset();
  getDetail(row.id).then(response => {
    form.value = response.data;
    //字典str与实际值num不匹配导致无法回显加了这个
    form.value.gender = response.data.gender.toString()
    form.value.educationLevel = response.data.educationLevel.toString()
    form.value.studyMode = response.data.studyMode.toString()
    form.value.studentStatus = response.data.studentStatus.toString()
    form.value.physicalExamResult = response.data.physicalExamResult.toString()
    open.value = true;
    title.value = "修改学生信息";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentListRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        edit(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        add(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '学生名单导入';
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download('/nenu/gf-student-list/import-template', {}, `student_template_${new Date().getTime()}.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs['uploadRef'].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit();
}

getList();
</script>

<style>
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px 15px;
}

.grid-item {
  margin-bottom: 0;
  background: white;
  border-radius: 8px;
  padding: 5px;
  transition: all 0.3s ease;
}

.grid-item :deep(.el-input) {
  width: 100%;
}

/* 描述文本样式 */
.item-description {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 8px;
  line-height: 1.4;
  padding: 5px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
</style>
