<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="studentName" v-if="!roleGroup.includes('学生')">
        <el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="民族" prop="nation">
        <el-select v-model="queryParams.nation" placeholder="请选择民族" clearable>
          <el-option v-for="dict in dict.type.rt_nation" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable>
          <el-option v-for="dict in dict.type.rt_grade" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="学号" prop="studentNo">
        <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="班级" prop="className">
        <el-select v-model="queryParams.className" placeholder="请选择班级" clearable>
          <el-option v-for="dict in dict.type.rt_classes" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="专业名称" prop="major">
        <el-input v-model="queryParams.major" placeholder="请输入专业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="保留学籍开始日期" prop="reserveStartDate">
        <el-date-picker clearable v-model="queryParams.reserveStartDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择保留学籍开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="保留学籍结束日期" prop="reserveEndDate">
        <el-date-picker clearable v-model="queryParams.reserveEndDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择保留学籍结束日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['routine:enlistmentReserve:add']">发起入伍保留学籍申请</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm">发起入伍保留学籍申请</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['routine:enlistmentReserve:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['routine:enlistmentReserve:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['routine:enlistmentReserve:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="enlistmentReserveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请编号" align="center" prop="applyNo" />
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="辅导员姓名" align="center" prop="teacherName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <span v-if="scope.row.gender == 1">男</span>
          <span v-else>女</span>
        </template>
      </el-table-column>
      <el-table-column label="民族" align="center" prop="nation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rt_nation" :value="scope.row.nation" />
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="grade">
      </el-table-column>
      <el-table-column label="学号" align="center" prop="studentNo" />
      <el-table-column label="班级" align="center" prop="className">
      </el-table-column>
      <el-table-column label="专业名称" align="center" prop="major" />
      <el-table-column label="家庭地址" align="center" prop="familyAddress">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.familyAddress" placement="top">
            <div class="text-ellipsis">{{ scope.row.familyAddress }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="家长电话" align="center" prop="parentPhone" />
      <el-table-column label="申请理由" align="center" prop="applyReason">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.applyReason" placement="top">
            <div class="text-ellipsis">{{ scope.row.applyReason }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applyStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.applyStatus == 0" type="info">待提交</el-tag>
          <el-tag v-if="scope.row.applyStatus == 1">审核中</el-tag>
          <el-tag v-if="scope.row.applyStatus == 2" type="success">审核通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="保留学籍编号" align="center" prop="reserveNo" />
      <el-table-column label="保留学籍开始日期" align="center" prop="reserveStartDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reserveStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保留学籍结束日期" align="center" prop="reserveEndDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reserveEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="批文号" align="center" prop="approvalNo" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['routine:enlistmentReserve:edit']"  v-if="scope.row.applyStatus == 0">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['routine:enlistmentReserve:remove']" v-if="scope.row.applyStatus == 0">删除</el-button>
          <el-button v-if="scope.row.applyStatus == 1" size="mini" type="text" icon="el-icon-info"
            @click="detail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改应征入伍保留学籍申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请编号" prop="applyNo">
          <el-input v-model="form.applyNo" placeholder="请输入申请编号" />
        </el-form-item>
        <el-form-item label="学生ID" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生ID" />
        </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-select v-model="form.nation" placeholder="请选择民族">
            <el-option v-for="dict in dict.type.rt_nation" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option v-for="dict in dict.type.rt_grade" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-select v-model="form.className" placeholder="请选择班级">
            <el-option v-for="dict in dict.type.rt_classes" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业名称" />
        </el-form-item>
        <el-form-item label="家庭地址" prop="familyAddress">
          <el-input v-model="form.familyAddress" placeholder="请输入家庭地址" />
        </el-form-item>
        <el-form-item label="家长联系电话" prop="parentPhone">
          <el-input v-model="form.parentPhone" placeholder="请输入家长联系电话" />
        </el-form-item>
        <el-form-item label="申请理由" prop="applyReason">
          <el-input v-model="form.applyReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="Flowable流程实例ID" prop="processInstanceId">
          <el-input v-model="form.processInstanceId" placeholder="请输入Flowable流程实例ID" />
        </el-form-item>
        <el-form-item label="保留学籍编号" prop="reserveNo">
          <el-input v-model="form.reserveNo" placeholder="请输入保留学籍编号" />
        </el-form-item>
        <el-form-item label="保留学籍开始日期" prop="reserveStartDate">
          <el-date-picker clearable v-model="form.reserveStartDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择保留学籍开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保留学籍结束日期" prop="reserveEndDate">
          <el-date-picker clearable v-model="form.reserveEndDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择保留学籍结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="批文号" prop="approvalNo">
          <el-input v-model="form.approvalNo" placeholder="请输入批文号" />
        </el-form-item>
        <el-form-item label="状态" prop="applyStatus">
          <el-input v-model="form.applyStatus" placeholder="请输入批文号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEnlistmentReserve, getOwnInfo, delEnlistmentReserve, addEnlistmentReserve, updateEnlistmentReserve } from "@/api/routine/enlistmentReserve/enlistmentReserve";
import { getUserProfile } from '@/api/system/user' // 获取当前登录用户
export default {
  name: "EnlistmentReserve",
  dicts: ['rt_classes', 'rt_nation', 'rt_grade'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应征入伍保留学籍申请表格数据
      enlistmentReserveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyNo: null,
        studentId: null,
        studentName: null,
        gender: null,
        nation: null,
        grade: null,
        studentNo: null,
        className: null,
        major: null,
        familyAddress: null,
        parentPhone: null,
        applyReason: null,
        applyStatus: null,
        processInstanceId: null,
        reserveNo: null,
        reserveStartDate: null,
        reserveEndDate: null,
        approvalNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applyNo: [
          { required: true, message: "申请编号不能为空", trigger: "blur" }
        ],
        studentId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        nation: [
          { required: true, message: "民族不能为空", trigger: "change" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "change" }
        ],
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        className: [
          { required: true, message: "班级不能为空", trigger: "change" }
        ],
        major: [
          { required: true, message: "专业名称不能为空", trigger: "blur" }
        ],
        familyAddress: [
          { required: true, message: "家庭地址不能为空", trigger: "blur" }
        ],
        parentPhone: [
          { required: true, message: "家长联系电话不能为空", trigger: "blur" }
        ],
        applyReason: [
          { required: true, message: "申请理由不能为空", trigger: "blur" }
        ],
        applyStatus: [
          { required: true, message: "申请状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "提交时间不能为空", trigger: "blur" }
        ],
      },
      roleGroup: '',
      user: ''
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    /** 查询应征入伍保留学籍申请列表 */
    getList() {
      this.loading = true;
      listEnlistmentReserve(this.queryParams).then(response => {
        this.enlistmentReserveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        this.roleGroup = response.roleGroup;
        // this.postGroup = response.postGroup;
        if (this.roleGroup) {
          if (this.roleGroup.includes("学生")) {
            this.queryParams.studentName = this.user.nickName
          } else if (this.roleGroup.includes("辅导员")) {
            getOwnInfo().then(res => {
              if (res.data) {
                this.queryParams.teacherName = res.data.teacherName
              }
            })
          }
          this.getList()
        }

      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applyNo: null,
        studentId: null,
        studentName: null,
        gender: null,
        nation: null,
        grade: null,
        studentNo: null,
        className: null,
        major: null,
        familyAddress: null,
        parentPhone: null,
        applyReason: null,
        applyStatus: null,
        processInstanceId: null,
        reserveNo: null,
        reserveStartDate: null,
        reserveEndDate: null,
        approvalNo: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应征入伍保留学籍申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids
      // getEnlistmentReserve(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改应征入伍保留学籍申请";
      // });
      // 跳转时携带 row.id 作为路由参数
      this.$router.push({
        path: "/routine/enlistmentReserve/applicationForm",
        query: { id: row.id } // 将 row.id 放在 query 中
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEnlistmentReserve(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEnlistmentReserve(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应征入伍保留学籍申请编号为"' + ids + '"的数据项？').then(function () {
        return delEnlistmentReserve(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('routine/enlistmentReserve/export', {
        ...this.queryParams
      }, `enlistmentReserve_${new Date().getTime()}.xlsx`)
    },
    // 跳转申请表
    openForm() {
      // 利用some方法快速判断是否存在重复申请（找到匹配项后立即终止遍历）
      const isDuplicate = this.enlistmentReserveList?.some(element => 
        element.studentName === this.user?.nickName && element.studentNo === this.user?.userName
      ) || false;

      if (isDuplicate) {
        this.$message.error('您已经申请过了，请勿重新申请！');
      } else {
        this.$router.push("/routine/enlistmentReserve/applicationForm");
      }
    },
    detail(row) {
      this.$router.push({
        path: "/routine/enlistmentReserve/applicationForm",
        query: { id: row.id, type: 'detail',deployId: row.deployId, processInstanceId: row.processInstanceId } // 将 row.id 放在 query 中
      })
    },
  }
};
</script>

<style scoped>
.text-ellipsis {
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 显示省略号 */
}
</style>
