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

      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="学生学号" prop="userNumber">
        <el-input
          v-model="queryParams.userNumber"
          placeholder="请输入学生学号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="年级" prop="grade">
        <el-select
          v-model="queryParams.grade"
          placeholder="请选择年级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="year in grades"
            :key="year"
            :label="year.toString()"
            :value="year"
          />
        </el-select>
      </el-form-item>

        <el-form-item label="导师名称" prop="supervisorId">
          <el-select
            v-model="supervisor"
            @change="handleSupervisorChange"
            placeholder="请选择导师名称"
            clearable
            filterable
            class="!w-240px"
          >
            <el-option
              v-for="teacher in supervisors"
              :key="teacher.id"
              :label="teacher.nickname"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>

      <el-form-item label="工作间" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入工作间名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>


      <el-form-item label="成果名称" prop="achievementName">
        <el-input
          v-model="queryParams.achievementName"
          placeholder="请输入成果名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="成果类型" prop="achievementType">
        <el-select
          v-model="queryParams.achievementType"
          placeholder="请选择成果类型"
          clearable
          class="!w-240px"
        >
          <el-option :label="'北大中文核心期刊论文'" :value="1" />
          <el-option :label="'SCI、EI、SSCI、A&HCI国际学术期刊论文'" :value="2" />
          <el-option :label="'SCI、EI、ISIP会议论文'" :value="3" />
          <el-option :label="'专利'" :value="4" />
          <el-option :label="'著作'" :value="5" />
          <el-option :label="'竞赛'" :value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="署名" prop="sort">
        <el-select
          v-model="queryParams.sort"
          placeholder="请选择署名"
          clearable
          class="!w-240px"
        >
          <el-option :label="'第一作者'" :value="1" />
          <el-option :label="'第二作者（导师为第一作者）'" :value="2" />
          <el-option :label="'其他'" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="毕业条件" prop='isGraduate'>
            <el-select 
              v-model="queryParams.isGraduate" 
              placeholder="是否达成毕业条件"  
              @keyup.enter="handleQuery"
              class="!w-240px"
              >
              <el-option label="已达成" :value="0" />
              <el-option label="未达成" :value="1" />
              </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:user-achievement:selfCreate']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 创建成果
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:user-achievement:collegeExport']"
        >
          <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="userName" />
      <el-table-column label="学号" align="center" prop="userNumber" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="导师名称" align="center" prop="supervisor" />
      <el-table-column label="工作间" align="center" prop="deptName" />

      <el-table-column label="成果名称" align="center" prop="achievementName" />
      <el-table-column label="成果类型" align="center" prop="achievementType">
        <template #default="rowData">
          <span>
            {{
              rowData.row.achievementType == 1
               ? '北大中文核心期刊论文'
                : rowData.row.achievementType == 2
               ? 'SCI、EI、SSCI、A&HCI国际学术期刊论文'
                : rowData.row.achievementType == 3
               ? 'SCI、EI、ISIP会议论文'
                : rowData.row.achievementType ==4
               ? '专利'
                : rowData.row.achievementType == 5
               ? '著作'
                : rowData.row.achievementType == 6
               ? '竞赛'
                : '未知类型'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="署名" align="center" prop="sort">
        <template #default="rowData">
          <span>
            {{ 
              rowData.row.sort == 1
               ? '第一作者'
                : rowData.row.sort == 2
               ? '第二作者（导师为第一作者）'
                : rowData.row.sort == 3
               ? '其他'
                : '未知署名'
            }}
            </span>
        </template>
      </el-table-column>

      <el-table-column label="是否达成毕业条件" align="center" prop="isGraduate">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_STUDENT_GRADUATE_STATUS" :value="scope.row.isGraduate" />  
        </template>
      </el-table-column>

      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="图片材料" align="center" prop="detail" >
        <template #default="{ row }">
          <div class="demo-image__preview" v-if="queryParams" >
              <el-image
                style="width: 40px; height:40px;margin-right: 5px"
                class="h-80px w-80px"
                lazy
                :src="row.detail"
                :preview-src-list="[row.detail]"
                preview-teleported
                fit="cover"
              />
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="图片材料" align="center" prop="detail" >
        <template #default="{ row }">
          <a :href="row.detail" target="_blank" v-if="row.detail">{{ row.detail }}</a>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="rowData">
          <el-button
            link
            type="primary"
            @click="openForm('update', rowData.row.id)"
            v-hasPermi="['system:user-achievement:update']"
          >
            <Icon icon="ep:edit"/>
            修改
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(rowData.row.id)"
            v-hasPermi="['system:user-achievement:delete']"
          >
            <Icon icon="ep: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>
    <!-- 表单弹窗：添加/修改 -->
    <UserAchievementForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'

import download from '@/utils/download'
import { UserAchievementApi, UserAchievementVO } from '@/api/system/userAchievement'
import UserAchievementForm from './UserAchievementForm.vue'
import * as UserApi from '@/api/system/user'

/** 成果 列表 */
defineOptions({ name: 'UserAchievementCommon' })

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

const loading = ref(true) // 列表的加载中
const list = ref<UserAchievementVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  achievementName: undefined,
  achievementType: undefined,
  sort: undefined,
  userName: undefined,
  createTime: [],
  detail: undefined,
  isGraduate: undefined,
  deptId:undefined,
  userNumber:undefined,
  deptName:undefined,
  supervisorId:undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const users = ref()

const getList = async () => {
  loading.value = true
  try {
    const data = await UserAchievementApi.getSelfAchievementPage(queryParams)
    console.log(data, 'data');
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  // // treeRef.value.resetFields()
  // queryParams.deptId =null;
  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 UserAchievementApi.deleteUserAchievement(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await UserAchievementApi.collegeExportUserAchievement(queryParams)
    download.excel(data, '成果详情.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// /** 处理部门被点击 */
// const handleDeptNodeClick = async (row) => {
//   queryParams.deptId = row.id
//   await getList()
// }

// 生成年级选项数据
const currentYear = new Date().getFullYear();
const grades = ref(
  Array.from({ length: 21 }, (_, i) => `${currentYear - 10 + i}级`)
);

//获取所有导师
const supervisors = ref()
const supervisor =ref()
const getSupervisor= async () => {
  try {
    supervisors.value = await UserApi.getSupervisor()
  } catch (error) {
    console.error('Error fetching user data:', error)
  }
}
//传supervisorId给formData.supervisorId
const handleSupervisorChange = (value: number) => {
  const selectedUser = supervisors.value.find(user => user.id === value);
  if (selectedUser) {
    queryParams.supervisorId = selectedUser.id;
    supervisor.value=selectedUser.nickname;
  }
}

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