<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="日期" prop="date">
        <el-date-picker
          class="!w-240px"
          v-model="queryParams.date"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="请选择日期"
        />
      </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input
            placeholder="请输入姓名 "
            v-model="queryParams.studentName"
            clearable
             @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="学号" prop="userNumber">
          <el-input
            placeholder="请输入学号 "
            v-model="queryParams.userNumber"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="导师姓名" prop="supervisor">
          <el-select
              v-model="queryParams.supervisor"
              @change="handleSupervisorChange"
              placeholder="请选择导师"
              clearable
              filterable
              class="!w-240px"
            >
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="工作间名称" prop="deptName" v-if="userInfo.userType === '4'">
        <el-input
          placeholder="请输入工作间名称 "
          v-model="queryParams.deptName"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="!w-240px"
            />
          </el-form-item> -->

      <!-- <el-form-item label="打卡状态 " prop="clockInStatus">
        <el-select
          v-model="queryParams.clockInStatus"
          placeholder="请选择打卡状态 "
          clearable
          class="!w-240px"
        >
          <el-option :label="'正常'" :value="0" />
          <el-option :label="'未打卡'" :value="1" />

        </el-select>
      </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-attendance:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:student-attendance:exportError']"
        >
          <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="date">
        <template #default="scope">
          {{scope.row.date[0]}} 年 {{scope.row.date[1]}} 月 {{scope.row.date[2]}} 日
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="学号" align="center" prop="userNumber"  />
      <el-table-column label="导师姓名" align="center" prop="supervisor" />
      <el-table-column
        v-if="userInfo.userType === '4'"
        label="工作间名称"
        align="center"
        prop="deptName"
        width="100"
      />
      <el-table-column label="打卡类型" align="center" prop="clockInStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_STUDENT_ATTENDANCE_TYPE" :value="scope.row.clockInStatus" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="打卡状态 " align="center" prop="clockInStatus" >
        <template #default="rowData">
          <span :class="getStatusClass(rowData.row.clockInStatus)">
            {{
              rowData.row.clockInStatus == 0
               ? '正常'
                : rowData.row.clockInStatus ==1
               ? '迟到'
                : rowData.row.clockInStatus == 2
               ? '早退'
                : rowData.row.clockInStatus == 3
               ? '缺勤'
                : rowData.row.clockInStatus == 4
               ? '请假'
                : '未知类型'
            }}
          </span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
<!--      <el-table-column label="操作" align="center" min-width="120px">-->
<!--        <template #default="scope">-->
<!--          <el-button-->
<!--            link-->
<!--            type="primary"-->
<!--            @click="openForm('update', scope.row.id)"-->
<!--            v-hasPermi="['system:student-attendance:update']"-->
<!--          >-->
<!--            编辑-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-hasPermi="['system:student-attendance: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>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StudentAttendanceApi, StudentAttendanceVO } from '@/api/system/studentAttendance'
import StudentAttendanceForm from './StudentAttendanceForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
import * as UserApi from '@/api/system/user'

/** 学生考勤记录 列表 */
defineOptions({ name: 'StudentAttendance' })

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

const userInfo = ref({} as ProfileVO)
const getUserInfo = async () => {
  const users = await getUserProfile()
  console.log(users)
  userInfo.value = users
}

const loading = ref(true) // 列表的加载中
const list = ref<StudentAttendanceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  studentId: undefined,
  studentName: undefined,
  userNumber: undefined,
  deptId: undefined,
  date: [],
  clockInTime: [],
  clockInTimeRange: [],
  clockInStatus: undefined,
  createTime: [],
  remark: undefined,
  supervisor: undefined,
  supervisorId: undefined,
  deptName: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

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

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StudentAttendanceApi.getStudentAttendanceErrorPage(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()
  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 StudentAttendanceApi.deleteStudentAttendance(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StudentAttendanceApi.exportStudentAttendanceErrorExcel(queryParams)
    download.excel(data, '学生考勤记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 状态颜色显示
const getStatusClass = (status) => {
  switch (status) {
    case "0":
      return 'status-normal';
    case "1":
      return 'status-late';
    case "2":
      return 'status-early';
    case "3":
      return 'status-absent';
    case "4":
      return 'status-leave';
    default:
      return 'status-unknown';
  }
};

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

<style scoped>
.status-normal {
  color: green;
}

.status-late {
  color: orange;
}

.status-early {
  color: blue;
}

.status-absent {
  color: red;
}

.status-leave {
  color: purple;
}

.status-unknown {
  color: gray;
}
</style>
