<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-form-item label="参与导师" prop="supervisorIds">
        <el-select
          v-model="queryParams.supervisorId"
          placeholder="请选择参与导师"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="supervisor in supervisors"
            :key="supervisor.id"
            :label="supervisor.nickname"
            :value="supervisor.id"
          />
        </el-select>

      </el-form-item>
<!--      <el-form-item label="学硕名额" prop="academicSlots">-->
<!--        <el-input-->
<!--          v-model="queryParams.academicSlots"-->
<!--          placeholder="请输入学硕名额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="专硕名额" prop="professionalSlots">-->
<!--        <el-input-->
<!--          v-model="queryParams.professionalSlots"-->
<!--          placeholder="请输入专硕名额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

        <el-button
          plain
          type="primary"
          @click="openForm('update', scope.row.id)"
          v-hasPermi="['system:student-select-supervisor-record:update']"
          v-if="userInfo?.userType === '1'"
        >
          志愿编辑
        </el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          @click="openForm('create')"-->
<!--          v-hasPermi="['system:supervisor-selection-setting:create']"-->
<!--        >-->
<!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          @click="handleExport"-->
<!--          :loading="exportLoading"-->
<!--          v-hasPermi="['system:supervisor-selection-setting:export']"-->
<!--        >-->
<!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="index" width="50" />
<!--      <el-table-column label="项目名称" align="center" prop="projectId" />-->
      <el-table-column label="导师姓名" align="center" prop="supervisorName" />
      <el-table-column
        label="导师类型"
        align="center"
        prop="userType"
        :formatter="userTypeFormatter"
      />
      <el-table-column label="招生指标" align="center">
        <template #default="scope">
          学硕/{{ scope.row.academicSlots }} 专硕/{{ scope.row.professionalSlots }}
        </template>
      </el-table-column>
<!--      <el-table-column label="学硕名额" align="center" prop="academicSlots" />-->
<!--      <el-table-column label="专硕名额" align="center" prop="professionalSlots" />-->

      <el-table-column label="已招生名额" align="center">
        <template #default="scope">
          <span>
            <span v-if="scope.row.occupiedAcademicSlots">
              学硕/{{ scope.row.occupiedAcademicSlots }}
            </span>
            <span v-if="scope.row.occupiedProfessionalSlots">
              专硕/{{ scope.row.occupiedProfessionalSlots }}
            </span>
            <span v-if="!scope.row.occupiedAcademicSlots && !scope.row.occupiedProfessionalSlots">
              暂无
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="剩余名额" align="center">
        <template #default="scope">
          学硕/{{ scope.row.academicSlots -scope.row.occupiedAcademicSlots }} 专硕/{{ scope.row.professionalSlots-scope.row.occupiedProfessionalSlots }}
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="导师详情" align="center" min-width="120px"  v-if="userInfo?.userType === '4' || userInfo?.userType === '1'">
        <template #default="scope">
          <el-button link
                      type="primary"
                      @click="openTeacherRequireForm( scope.row.supervisorId)"
                      v-hasPermi="['system:user:query']"
          >
            <Icon icon="ep:bell" />
            查看
          </el-button>
        </template>
      </el-table-column>

      <!--  学生志愿填报-->
      <el-table-column label="志愿填报" align="center" min-width="120px"  v-if=" userInfo?.userType === '1'">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="openStudentSelectSupervisorPop('create', scope.row.projectId,scope.row.supervisorId,null,null)"
            v-hasPermi="['system:student-select-supervisor-record:create']"
            v-if="userInfo?.userType === '1'"
          >
            <Icon icon="ep:bell" />
            选择
          </el-button>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
<!--          学院查看招生详情-->
          <el-button type="text"  v-if="userInfo?.userType === '4'" @click="openStudentSelectSupervisorRecord(scope.row.projectId,scope.row.supervisorId)" v-hasPermi="['system:student-select-supervisor-record:query']"
                     >
            <Icon icon="ep:bell" />
            招生详情
          </el-button>
<!--       志愿填报修改-->
          <el-button
            link
            type="primary"
            @click="handelWithdraw( scope.row.supervisorId)"
            v-hasPermi="['system:student-select-supervisor-record:withdraw']"
            v-if="userInfo?.userType === '1'&&scope.row.selectType ==1"
          >
            撤回
          </el-button>

<!--名额设置-->
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:supervisor-selection-setting:update']"
            v-if="userInfo?.userType === '4'"
          >
            编辑
          </el-button>
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-hasPermi="['system:supervisor-selection-setting:delete']"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!--  是学生-->
  <ContentWrap v-if="userInfo.userType==='1' ||userInfo.userType==='4'" >
      <el-table
        v-loading="loading"
        :data="selectionList"
        row-key="id"
      >
      <el-table-column type="index" width="50" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="硕士类型" align="center" prop="masterType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_STUDENT_MASTER_TYPE" :value="scope.row.masterType" />
        </template>
      </el-table-column>
        <el-table-column label="导师姓名" align="center" prop="supervisor" />

        <el-table-column
          label="导师类型"
          align="center"
          prop="supervisorType"
          :formatter="userTypeFormatter"
        />

<!--      <el-table-column label="专业" align="center" prop="major" />-->

<!--      <el-table-column label="简历" align="center" prop="introduction" />-->

      <el-table-column label="申请状态" align="center" prop="selectType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_STUDENT_SELECT_RECORD_SELECT_TYPE" :value="scope.row.selectType" />
        </template>
      </el-table-column>
<!--      <el-table-column label="学生电子签名" align="center" prop="studentSignature" />-->
<!--      <el-table-column label="导师电子签名" align="center" prop="supervisorSignature" />-->
      <el-table-column
        label="提交时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="导师审批时间"
        align="center"
        prop="supervisorApproveTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <supervisorSelectionSettingForm ref="formRef" @success="getList" />
  <!-- 导师详情弹窗-->
  <teacherRequireForm ref="teacherRequireFormRef" @success="getList"/>

  <studentSelectSupervisorRecordForm ref="studentSelectSupervisorPop" @success="getList"/>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { supervisorSelectionSettingApi, supervisorSelectionSettingVO } from '@/api/system/supervisorSelectionSetting'
import supervisorSelectionSettingForm from './supervisorSelectionSettingForm.vue'
import teacherRequireForm from '../userDetail/teacher.vue'
import studentSelectSupervisorRecordForm from '../studentSelectSupervisorRecord/studentSelectSupervisorRecordForm.vue'
import * as UserApi from '@/api/system/user'
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
import {
  studentSelectSupervisorRecordApi,
  studentSelectSupervisorRecordVO
} from "@/api/system/studentSelectSupervisorRecord";
import {DICT_TYPE} from "@/utils/dict";

/** 导师学硕专硕名额设置 列表 */
defineOptions({ name: 'supervisorSelectionSetting' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<supervisorSelectionSettingVO[]>([]) // 列表的数据

const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectId: undefined,
  supervisorId: undefined,
  academicSlots: undefined,
  professionalSlots: undefined,
  supervisorName:undefined,
  userType:undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

//记录页面
const router = useRouter()
const openStudentSelectSupervisorRecord = (projectId,supervisorId) => {
  router.push({ name: 'studentSelectSupervisorRecord', query: { projectId: projectId ,supervisorId :supervisorId} });
}

//导师类型
const userTypeFormatter = (row, column, cellValue, index) => {
  switch (cellValue) {
    case "3":
      return '校内导师';
    case "5":
      return '校外导师';
    default:
      return '未知';
  }
};

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await supervisorSelectionSettingApi.getSupervisorSelectionSettingPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

//获取登录人员信息
const userInfo = ref({} as ProfileVO)
const getUserInfo = async () => {
  const users = await getUserProfile()
  userInfo.value = users
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await supervisorSelectionSettingApi.deleteSupervisorSelectionSetting(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await supervisorSelectionSettingApi.exportSupervisorSelectionSetting(queryParams)
    download.excel(data, '导师学硕专硕名额设置.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

//获取所有导师
const supervisors = ref()
const getSupervisor= async () => {
  try {
    const result = await UserApi.getSupervisor()
    supervisors.value = result
  } catch (error) {
    console.error('未获取到导师', error)
  }
}
//传supervisorId给formData.supervisorId

const teacherRequireFormRef = ref()
const openTeacherRequireForm = (supervisorId?: number) => {
  teacherRequireFormRef.value.open("detail",supervisorId)
}

//志愿填报弹窗
const studentSelectSupervisorPop= ref()
const openStudentSelectSupervisorPop =  (type: string, projectId?: number,supervisorId? :number,id:number,studentId:number) => {
  studentSelectSupervisorPop.value.open(type, projectId ,supervisorId,id,studentId)
}

//没处理好

const recordData = ref({
  id: undefined,
  projectId: undefined,
  studentId: undefined,
  supervisorId: undefined,
  selectType: undefined,
  studentSignature: "",
  supervisorApproveTime: undefined,
  supervisorSignature: "",
  externalSupervisorId: undefined,
  masterType:undefined,
  studentSignDate:[],
  supervisorSignDate:[],
})
const handelWithdraw = async (supervisorId:number) => {
  try {
    await message.confirm()
    recordData.value.supervisorId=supervisorId
    const data =recordData.value as unknown as studentSelectSupervisorRecordVO
    await studentSelectSupervisorRecordApi.withdrawStudentSelectSupervisorRecord(data)
    message.success("撤回了申请")
    await getList()
  } catch {}
}

const selectionList = ref<studentSelectSupervisorRecordVO[]>([]) //下面的选择记录列表
/** 查询互选记录列表 */
const getRecordList = async () => {
  loading.value = true
  try {
    const data = await studentSelectSupervisorRecordApi.getSelectSupervisorRecordList()
    selectionList.value = data
  } finally {
    loading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()
  getUserInfo()
  getSupervisor()
  await getRecordList()
})
</script>
