<!--
  Description: 我的课程页面
  Author: BaiQi
  Created Date: 2024-7-2
-->
<template>
  <el-card style="margin: 10px auto 0;height: 100%; width: 80%" shadow="never">
    <el-button :icon="Refresh" circle @click="doRefresh"></el-button>
    <template v-if="role == 'teachers'">
      <el-button @click="visible = !visible" style="background-color: #409EFF; border-color: #409EFF; color: white;">新增课程</el-button>
    </template>
    <el-input v-model="courseName" placeholder="请输入课程名称" clearable style="width: 180px; margin: 0 10px 0 10px ;"/>
    <el-button   style="background-color: #409EFF; border-color: #409EFF; color: white;" 
 @click="handleSearch">
      <el-icon style="margin-right: 3px"><Search/></el-icon>
      查询
    </el-button>

    <el-table :data="pageInfo.records" style="width: 100%" height="100%" show-overflow-tooltip>
      <template #empty>
        暂无课程
      </template>
      <el-table-column type="index"/>
      <el-table-column prop="courseName" label="课程名称"/>
      <!-- <el-table-column prop="description" label="描述" width="420"/> -->
      <el-table-column prop="endTime" label="截止时间" sortable/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleShowDetail(scope.row.courseId)" style="margin-right: 0; margin-left: 0;padding-left: 10px; padding-right: 10px" type="primary">
            <el-icon style="margin-right: 3px" ><ZoomIn/></el-icon>
            详情
          </el-button>
          <el-button @click="handleDelete(scope.row.courseId)" style="margin-right: 0; margin-left: 15px;padding-left: 10px; padding-right: 10px" type="danger">
            <el-icon style="margin-right: 3px" ><DeleteFilled/></el-icon>
            {{role == 'teachers' ? "删除" : "退课"}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        small
        style="font-size: 16px;margin-top: 10px;margin-left: 450px"
        :page-sizes="[5, 10, 15]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="queryInfo.pageNow"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
    </el-pagination>

  </el-card>

  <el-dialog v-model="visible" title="新增课程">
    <el-form :model="newCourse" label-width="80px">
      <el-form-item label="课程名称" >
        <el-input v-model="newCourse.courseName" placeholder="请输入课程名称"></el-input>
      </el-form-item>
      <el-form-item label="面向年级">
        <el-input v-model="newCourse.targetGrade" placeholder="请输入目标年级，例：2024级软件1-4班"></el-input>
      </el-form-item>
      <el-form-item label="课程描述">
        <el-input
            type="textarea"
            autosize
            resize="none"
            v-model="newCourse.description"
            placeholder="请输入课程描述"
        >
        </el-input>
      </el-form-item>
      <!-- <el-form-item label="选课码" style="display: flex; align-items: center">
        <el-input v-model="newCourse.enrollCode" placeholder="请输入选课码" style="flex: 1; margin-right: 10px;"></el-input>
        <el-button type="primary" plain size="mini" @click="newCourse.enrollCode = Math.random().toString(36).substr(2, 6).toUpperCase()">随机生成</el-button>
      </el-form-item> -->
      <el-form-item label="开始时间">
        <el-date-picker v-model="newCourse.startTime" type="datetime" placeholder="截止时间" style="width: 180px"/>
      </el-form-item>
      <el-form-item label="截止时间">
        <el-date-picker v-model="newCourse.endTime" type="datetime" placeholder="截止时间" style="width: 180px"/>
      </el-form-item>
<!--      <el-form-item label="课程图片">-->
<!--        <el-upload-->
<!--            ref="uploadRef"-->
<!--            drag-->
<!--            action= "http://127.0.0.1:8080/api/file"-->
<!--            multiple-->
<!--            v-model:file-list="fileList"-->
<!--            :limit="1"-->
<!--            :on-success="handleSuccess"-->
<!--            :on-error="handleError"-->
<!--            :on-exceed="handleExceed"-->
<!--            :on-change="handleChange"-->
<!--            list-type="picture-card"-->
<!--            accept=".png, .jpg"-->
<!--            :auto-upload="false"-->
<!--        >-->
<!--          <el-icon class="el-icon&#45;&#45;upload"><upload-filled /></el-icon>-->
<!--          <div class="el-upload__text">-->
<!--            拖拽上传或<em>点击此处上传</em>-->
<!--          </div>-->
<!--          <template #tip>-->
<!--            <div class="el-upload__tip">-->
<!--              jpg/png 文件不大于 500kb-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-upload>-->
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import useApis from "@/apis";
  import {useStore} from "@/store";
  import {inject, onMounted, reactive, ref} from "vue";
  import type {CourseVO} from "@/types/vo";
  import {Refresh, Search, UploadFilled, ZoomIn, DeleteFilled} from "@element-plus/icons-vue";
  import router from "@/router";
  import type {CourseDTO} from "@/types/dto";
  import {
    ElMessage,
    ElMessageBox,
    ElNotification,
    type UploadFile,
    type UploadFiles,
    type UploadProps,
    type UploadUserFile
  } from "element-plus";
  import type {CourseQuery} from "@/types/query";
  import {useFormatDate} from "@/hooks/useFormatDate";

  const apis = useApis()
  const store = useStore()
  const doRefresh:Function = inject("reload")
  const {formatDate} = useFormatDate()
  const role:'teachers' | 'student' = store.user.role === 'STUDENT' ?   'student':'teachers';

  let visible = ref(false)
  let uploadRef = ref()

  const queryInfo = reactive({
    pageNow: 1,
    pageSize: 10,
  })

  let pageInfo = reactive<{
    records: CourseVO[],
    current: number,// 当前页码
    size: number, // 分页大小
    pages: number, // 总页数
    total: number
  }>({
    records: null,
    current: 0,
    size: 0,
    pages: 0,
    total: 0,
  })

  let newCourse = reactive<CourseDTO>({
    courseName: "",
    teacherIds: [store.user.id],
    courseImages: [],
    targetGrade: "",
    startTime: "",
    endTime: "",
    description: "",
  })

  const query = reactive<CourseQuery>({
    courseId:0,
    teacherId:store.user.id,
    teacherPid:null,
    studentId:0,
    courseName:"",
    semester:"",
  })

  // 用于编辑课程展示预览图片
  const fileList = ref<UploadUserFile[]>([])

  const handleSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    newCourse!.courseImages[0] = response.data
  }

  const handleError: UploadProps['onError'] = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log(error, uploadFile, uploadFiles)
  }

  const handleExceed = (files, fileList) => {
    // console.log(files)
    uploadRef.value.clearFiles()  //清空上传文件（限制一个，所以直接清空即可）
    const file = files[0]
    uploadRef.value.handleStart(file)  //重新上传
  }

  //选择文件
  const handleChange = (file,fileList) => {
    // console.log(file)
    const fileImgType = file.name.match(/\.([^\.]+)$/)[1];  //匹配文件格式（最后一个'.'后的格式）或者匹配file.raw.type
    const isImageType = ['png','jpg'];
    const isLt5KB = file.size / 1024  < 500;  //判断图片格式与大小
    if (isImageType.indexOf(fileImgType)==-1) {
      ElMessage.error('文件仅支持png、jpg格式')  //限制文件类型
      uploadRef.value.clearFiles()  //清空上传文件
      return false;
    }
    if (!isLt5KB) {
      ElMessage.error('文件不能超过500kb!')  //限制文件大小
      uploadRef.value.clearFiles()  //清空上传文件
      return false;
    }
  }

  let courseName = ref('')
  const handleSearch = () => {
    if (role === 'student') {
      Object.assign(query, {
        courseId: null,
        teacherId: null,
        teacherPid:null,
        studentId: store.user.id,
        courseName: courseName.value,
        semester: null,
      })
    } else if(role === 'teachers'){
      Object.assign(query, {
        courseId: null,
        teacherId: store.user.id,
        teacherPid:store.user.pid ? Number(store.user.pid) : null,
        studentId: null,
        courseName: courseName.value,
        semester: null,
      })
    }
    apis.getAllCourse(query, queryInfo.pageNow, queryInfo.pageSize)
        .then((res: any) => {
          let data = res.data.data
          Object.assign(pageInfo, {...data})
        })
        .catch((err: any) => {
          console.error(err);
        })
        .finally(() => {
        });
  }

  const handleSubmit = () => {
    if(newCourse.courseName === '') {
      ElNotification({title: '课程名称不得为空',type: 'error',})
      return
    }
    if(newCourse.targetGrade === '') {
      ElNotification({title: '面向年级不得为空',type: 'error',})
      return
    }
    if(newCourse.description === '') {
      ElNotification({title: '描述不得为空',type: 'error',})
      return
    }
    // if(newCourse.enrollCode === '') {
    //   ElNotification({title: '选课码不得为空',type: 'error',})
    //   return
    // }
    if(newCourse.startTime === '') {
      ElNotification({title: '开始时间不得为空',type: 'error',})
      return
    }
    if(newCourse.endTime === '') {
      ElNotification({title: '结束时间不得为空',type: 'error',})
      return
    }
    if(newCourse.startTime >= newCourse.endTime) {
      ElNotification({title: '结束时间不得在起始时间之前',type: 'error',})
      return
    }
    newCourse.endTime = formatDate(newCourse.endTime)
    newCourse.startTime = formatDate(newCourse.startTime)
    if(new Date(newCourse.endTime) < new Date(newCourse.startTime)){
      ElMessage.error('截止时间不能早于开始时间！');
      return;
    }

    apis.createCourse(newCourse)
        .then((res:any) => {
          if(res.data.code===200) {
            ElNotification({
              title: '添加成功',
              type: 'success',
            })
            fetchData()
          }else {
            console.log(res.data)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    visible.value = false
  }

  const handleShowDetail = (value:number) => {
    // router.push(`/home/courseDetail/${value}`)
    router.replace(`/home/courseDetail/${value}`);
    // location.reload()
  }

  const fetchData = () => {
    if (role === 'student') {
      Object.assign(query, {
        courseId:null,
        teacherId:null,
        studentId:store.user.id,
        courseName:null,
        semester:null,
      })
      apis.getAllCourse(query, queryInfo.pageNow, queryInfo.pageSize)
          .then((res: any) => {
            let data = res.data.data
            Object.assign(pageInfo, {...data})
            processData()
          })
          .catch((err: any) => {
            console.error(err);
          })
          .finally(() => {
          });
    } else if (role === "teachers") {
      Object.assign(query, {
        courseId:null,
        teacherId:store.user.id,
        teacherPid:store.user.pid ? Number(store.user.pid) : null,
        studentId:null,
        courseName:null,
        semester:null,
      })
      apis.getAllCourse(query, queryInfo.pageNow, queryInfo.pageSize)
          .then((res: any) => {
            let data = res.data.data
            console.log(data)
            Object.assign(pageInfo, {...data})
            processData()
          })
          .catch((err: any) => {
            console.error(err);
          })
          .finally(() => {
          });
    }
  }

  const processData = () => {
    for(let i = 0; i < pageInfo.records.length; i++){
      pageInfo.records[i].endTime = formatDate(pageInfo.records[i].endTime)
    }
  }

  const handleCurrentChange =(index:number)=>{
    queryInfo.pageNow=index;
    fetchData();
  }
  const handleSizeChange = (pageSize: number) => {
    queryInfo.pageSize = pageSize
    fetchData()
  }


  onMounted(() => {
    fetchData()
  })

  // TODO:状态选择
  let state = ref(null)
  const stateOptions = [
    {
      value: 0,
      label: "已结课"
    },
    {
      value: 1,
      label: "未结课"
    },
  ]

  const handleDelete = (courseId : number)=>{
    ElMessageBox.confirm('您确定要执行此操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(role == "teachers") {
          apis.deleteCourse(courseId)
          .then((res: any) => {
            ElMessage.success("执行成功")
            doRefresh()
          })
          .catch((err: any) => {
            console.error(err);
          })
          .finally(() => {});
        } else {
          apis.dropCourse(courseId)
          .then((res: any) => {
            ElMessage.success("执行成功")
            doRefresh()
          })
          .catch((err: any) => {
            console.error(err);
          })
          .finally(() => {});
        }
      })
  }
</script>

<script lang="ts">
export default {
  name: "CoursePage"
}
</script>

<style scoped>
:deep(.el-upload-dragger) {
  padding: 0px 0px;
}
</style>
