<template>
  <!-- 弹窗开关 -->
  <el-form
    class="switch-form"
    :inline="true"
    label-width="200px"
  >
    <el-form-item label="是否开启导师弹窗"  v-if="userInfo?.userType === '4' ">
      <el-switch v-model="popData.isSupervisor" :active-value="1" :inactive-value="0" @change="(val) => handleSwitchChange(popData.id, 'isSupervisor', val)" />
    </el-form-item>

    <el-form-item label="是否开启学生弹窗"  v-if="userInfo?.userType === '4'">
      <el-switch v-model="popData.isStudent" :active-value="1" :inactive-value="0" @change="(val) => handleSwitchChange(popData.id, 'isStudent', val)" />
    </el-form-item>
  </el-form>

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="学生开始时间" prop="studentStartTime">
        <el-date-picker
          v-model="queryParams.studentStartTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          placeholder="选择学生开始时间"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="导师截止时间" prop="supervisorConfirmDeadline">
        <el-date-picker
          v-model="queryParams.supervisorConfirmDeadline"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          placeholder="选择导师截止时间"
          clearable
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="参与学生年级" prop="studentGrade">
        <el-select
          v-model="queryParams.studentGrade"
        placeholder="请选择参与学生年级"
        clearable
        @change="handleQuery"
        class="!w-240px"
        >
        <el-option
          v-for="year in gradeOptions"
          :key="year"
          :label="year"
          :value="year"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </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
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:student-selection-project:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:student-selection-project: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="projectName" />
      <el-table-column
        label="学生开始时间"
        align="center"
        prop="studentStartTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="导师截止时间"
        align="center"
        prop="supervisorConfirmDeadline"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="参与学生年级" align="center" prop="studentGrade" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
<!--          校内导师查看项目详情,互选记录-->
          <el-button type="text" v-if="userInfo?.userType === '3'" @click="openStudentSelectSupervisorRecord(scope.row.id)" v-hasPermi="['system:student-select-supervisor-record:query']">
          <Icon icon="ep:bell" />
           详情
          </el-button>

<!--          学院或者学生查看详情,导师名额设置页面-->
          <el-button type="text"  v-if="userInfo?.userType === '4' || userInfo?.userType === '1'" @click="openSupervisorSelectionSetting(scope.row.id)" v-hasPermi="['system:supervisor-selection-setting:query']" >
            <Icon icon="ep:bell" />
            详情
          </el-button>

          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:student-selection-project:update']"
            v-if="userInfo?.userType === '4'"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:student-selection-project: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>

  <!-- 表单弹窗：添加/修改 -->
  <studentSelectionProjectForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { studentSelectionProjectApi, studentSelectionProjectVO } from '@/api/system/studentSelectionProject'
import studentSelectionProjectForm from './studentSelectionProjectForm.vue'
import { ref } from 'vue'
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
import { getPopData, updateIsPop,PopDo } from '@/api/system/user/pop'

/** 师生互选项目 列表 */
defineOptions({ name: 'StudentSelectionProject' })

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

const isPopDataLoaded = ref(false); // 标志，用于防止初始时更新
const popData = ref<PopDo>({
  id: 1,
  isStudent: undefined,
  isSupervisor: undefined
});

const loading = ref(true) // 列表的加载中
const list = ref<studentSelectionProjectVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectName: undefined,
  studentStartTime: [],
  supervisorConfirmDeadline: undefined,
  studentGrade: undefined,  // 年级属性绑定到 queryParams
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await studentSelectionProjectApi.getStudentSelectionProjectPage(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
  // userType.value = Number(users.userType)
}


/** 搜索按钮操作 */
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 studentSelectionProjectApi.deleteStudentSelectionProject(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await studentSelectionProjectApi.exportStudentSelectionProject(queryParams)
    download.excel(data, '师生互选项目.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const currentYear = new Date().getFullYear(); // 获取当前年份
const gradeOptions = computed(() => {
  return [
    currentYear + '级',         // 今年
    currentYear - 1 + '级',     // 去年
    currentYear - 2 + '级',     // 前年
    currentYear - 3 + '级',     // 大前年
    currentYear - 4 + '级',     // 大大前年
  ];
});

//不同人员跳转不同页面
const router = useRouter()
const openStudentSelectSupervisorRecord = (id) => {
  router.push({ name: 'studentSelectSupervisorRecord', query: { projectId: id} });
}
const openSupervisorSelectionSetting = (id) => {
  router.push({ name: 'supervisorSelectionSetting', query: { projectId: id} });
}

// 更新导师，学生开关
const handleSwitchChange = async (id: number, field: string, value: number) => {
  if (!isPopDataLoaded.value) return; // 如果尚未加载弹窗数据，阻止更新
  try {
    popData.value[field] = value;
    console.log(popData.value)
    updateIsPop(popData.value); // 确保传递的是popData.value
    message.success(t('common.updateSuccess'));
  } catch (error) {
    message.error(t('common.updateError'));
  }
};

// 获取弹窗数据
const getPopDataFunction = async () => {
  loading.value = true;
  try {
    popData.value = await getPopData();
    isPopDataLoaded.value = true; // 更新标志
  } finally {
    loading.value = false;
  }
}

/** 初始化 **/
onMounted(async () => {
  getList();
  await getUserInfo(); // 等待用户信息加载完成
  if (userInfo.value.userType === '4') {
    getPopDataFunction();
  }
});
</script>

<style>
.switch-form {
  background-color: white; /* 设置白色背景 */
  padding: 10px; /* 根据需要添加内边距 */
  border-radius: 4px; /* 根据需要添加边框圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 根据需要添加阴影 */
  font-size: 16px; /* 增大字体大小 */
  margin-bottom: 10px; /* 增加元素之间的间距 */
}

.switch-form.switch-form{
  padding: 10px 20px; /* 增大按钮内边距 */
}

</style>
