<template>
  <div class="course-detail-page">
    <!--课程信息-->
    <div v-if="courseInfo!==null" class="course-detail-container">
      <!--课程基本信息-->
      <el-card>
        <div class="header">
          <div class="course-img">
            <img :src="imgUrl" alt="err">
          </div>
          <div class="course-info">
            <el-row style="font-size: xx-large; font-weight: bold">
              {{ courseName }}
            </el-row>
            <div class="course-info-main">
              <el-row>{{ teacherName }}</el-row>
              <el-row>{{ semester }}</el-row>
              <el-row>{{ coursePeriod }}</el-row>
            </div>
            <el-row class="mooc-link">
              MOOC链接：
              <el-link v-if="courseInfo.moocUrl!==null" :href="courseInfo.moocUrl" target="_blank">点击此处<i
                      class="el-icon-link el-icon--right"></i></el-link>
              <span v-else>无</span>
            </el-row>
            <el-row v-if="isCreator">
              邀请码：{{courseInfo.invitationCode}}
            </el-row>
            <el-row v-if="isStudent">
              <el-button :disabled="isCourseSelected" size="mini" @click="handleSelectCourse">
                {{ isCourseSelected ? "已选课" : "确认选课" }}
              </el-button>
              <el-button v-if="isCourseSelected" size="mini" type="danger" @click="handleDropCourse">
                退课
              </el-button>
            </el-row>
          </div>
        </div>
        <el-divider/>
        <div class="introduce">
          <div class="title">简介</div>
          <div class="introduce-content">{{ description }}</div>
        </div>
      </el-card>
      <!--el-divider-->
      <el-divider v-if="isCreator || isCourseSelected"/>
      <!--tab页-->
      <el-card id="tab-main"
               v-if="isCreator || isCourseSelected"
               style="position: relative">
        <el-button type="success"
                   @click="refreshTab"
                   style="position: absolute;top: 21px;right: 20px;z-index: 999">
          刷新
        </el-button>
        <el-tabs v-model="tabName"
                 type="card"
                 @tab-click="handleTabsClick">
          <el-tab-pane label="任务" name="task">
            <task-tab ref="taskTab"
                      v-if="taskTabVisible"
                      :coder-id="courseInfo.coderId"
                      :eval-id="courseInfo.evalId"
                      :teacher-id="courseInfo.teacher.id"
                      :course-id="courseInfo.id"/>
          </el-tab-pane>
          <el-tab-pane label="课件" name="courseware">
            <courseware-tab ref="coursewareTab"
                            v-if="coursewareTabVisible"
                            :teacher-id="courseInfo.teacher.id"
                            :course-id="courseInfo.id"/>
          </el-tab-pane>
          <el-tab-pane label="通知" name="announcement">
            <announcement-tab ref="announcementTab"
                              v-if="announcementTabVisible"
                              :course-id="courseInfo.id"
                              :teacher-id="courseInfo.teacher.id"/>
          </el-tab-pane>
          <el-tab-pane label="评论" name="message">
            <message-tab ref="messageTab"
                         v-if="messageTabVisible"
                         :course-id="courseInfo.id"
                         :teacher-id="courseInfo.teacher.id"/>
          </el-tab-pane>
          <el-tab-pane label="项目" name="project">
            <project-tab ref="projectTab"
                         v-if="projectTabVisible"
                         :course-id="courseInfo.id"
                         :teacher-id="courseInfo.teacher.id"/>
          </el-tab-pane>
          <el-tab-pane label="团队" name="group">
            <group-tab ref="groupTab"
                       v-if="groupTabVisible"
                       :course-id="courseInfo.id"
                       :teacher-id="courseInfo.teacher.id"/>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
  import {ElMessageBox, ElMessage} from "element-plus";
  import ProjectTab from "@/views/CourseDetailPage/tabs/ProjectTab/ProjectTab.vue";
  import GroupTab from "@/views/CourseDetailPage/tabs/GroupTab.vue";
  import TaskTab from "@/views/CourseDetailPage/tabs/TaskTab.vue";
  import CoursewareTab from "@/views/CourseDetailPage/tabs/CoursewareTab.vue";
  import AnnouncementTab from "@/views/CourseDetailPage/tabs/AnnouncementTab.vue";
  import MessageTab from "@/views/CourseDetailPage/tabs/MessageTab.vue";
  import portal from "@/utils/portal/portal";

  export default {
    name: "CourseDetail",
    components: {
      MessageTab,
      AnnouncementTab,
      CoursewareTab,
      TaskTab,
      GroupTab,
      ProjectTab,
    },
    data() {
      return {
        courseInfo: null,
        isCourseSelected: false,

        jump_from_message: null,
        jump_from_message_id: null,

        tabName: "task",
        taskTabVisible: true,
        coursewareTabVisible: true,
        announcementTabVisible: true,
        messageTabVisible: true,
        projectTabVisible: true,
        groupTabVisible: true,

      };
    },
    computed: {
      userId() {
        return Number(this.$store.state.user.id);
      },
      description() {
        return this.courseInfo.description;
      },
      courseName() {
        return this.courseInfo.name;
      },
      teacherName() {
        return "教师：" + this.courseInfo.teacher.name;
      },
      semester() {
        return "学期：" + this.courseInfo.semester;
      },
      coursePeriod() {
        return "时间：" + this.timestampToTime(this.courseInfo.startTime) + "至" + this.timestampToTime(this.courseInfo.endTime);
      },
      isStudent() {
        return this.$store.getters.isStudent;
      },
      isTeacher() {
        return this.$store.getters.isTeacher;
      },
      isCreator() {
        return Number(this.courseInfo.teacher.id) === Number(this.$store.state.user.id);
      },
      imgUrl() {
        return this.courseInfo.imageUrl === null ? portal.variables.noImgUrl : this.courseInfo.imageUrl;
      },
    },
    async mounted() {
      this.fetchData();
      if (this.$route.params.jump_from_message) {
        this.jump_from_message = this.$route.params.jump_from_message;
        this.jump_from_message_id = this.$route.params.id;
      }
    },
    methods: {
      fetchData() {
        this.$apis.getCourseById(this.$route.params.id)
                .then(res => {
                  this.courseInfo = res.data.data;
                  this.$apis.checkCourseSelection(this.$route.params.id, this.$store.state.user.id)
                          .then(res => {
                            this.isCourseSelected = res.data.data;
                          });
                });
      },

      handleSelectCourse() {
        ElMessageBox.prompt("请输入选课码", "选课：" + this.courseInfo.name, {
          confirmButtonText: "立即选课",
          cancelButtonText: "我再想想",
        })
                .then(({value}) => {
                  if (value !== this.courseInfo.invitationCode) {
                    ElMessage.error("选课码错误");
                  } else {
                    this.$apis.confirmCourseSelection(
                            {
                              courseId: this.courseInfo.id,
                              userId: this.$store.state.user.id,
                            })
                            .then((res) => {
                              if (res.data.code === -1) {
                                ElMessage.error("选课失败");
                              } else {
                                ElMessage.success("选课成功");
                                setTimeout(function () {
                                  location.reload();
                                }, 500);
                              }
                            });
                  }
                });
      },

      handleDropCourse() {
        ElMessageBox.confirm("是否确认退课？", "退课：" + this.courseInfo.name, {
          confirmButtonText: "立即退课",
          cancelButtonText: "我再想想",
        })
                .then(() => {
                  this.$apis.cancelCourseSelection(
                          {
                            courseId: this.courseInfo.id,
                            userId: this.$store.state.user.id,
                          }
                  )
                          .then(() => {
                            ElMessage.success("退课成功");
                            setTimeout(function () {
                              location.reload();
                            }, 500);
                          })
                          .catch(err => {
                            ElMessage.error("handleCancelCourse: " + err);
                          });
                });
      },

      timestampToTime(timestamp) {
        const date = new Date(timestamp);
        const Y = date.getFullYear() + "-";
        const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
        const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        const h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        const m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        return Y + M + D + h + m;
      },

      handleTabsClick(tab) {
        this.refreshTab();
      },

      refreshTab() {
        switch (this.tabName) {
          case "task":
            this.$refs.taskTab.init();
            break;
          case "courseware":
            this.$refs.coursewareTab.init();
            break;
          case "announcement":
            this.$refs.announcementTab.init();
            break;
          case "message":
            this.$refs.messageTab.init();
            break;
          case "project":
            this.$refs.projectTab.init();
            break;
          case "group":
            this.$refs.groupTab.init();
            break;
          default:
            break;
        }
      },
    },
    watch: {
      jump_from_message(newVal, oldVal) {
        switch (newVal) {
          case "1":
            this.tabName = "announcement";
            break;
          case "2":
            this.tabName = "message";
            break;
          default:
            break;
        }
        document
                .getElementById("tab-main")
                .scrollIntoView({behavior: "smooth"});
      }
    }
  };
</script>

<style scoped>
  @import "./CourseDetail.css";
</style>
