<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="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></el-divider>

        <div class="introduce">
          <div class="title">简介</div>
          <div class="introduce-content">{{ description }}</div>
        </div>
      </el-card>
      <el-divider v-if="isCreator || isCourseSelected"/>
      <!--tab页-->
      <el-card v-if="isCreator || isCourseSelected">
        <!--tab标签&&tab按钮-->
        <div v-if="isCreator || isCourseSelected" class="course-tabs">
          <el-radio-group v-model="tabName" size="large">
            <el-radio-button label="task" @click="switchTab('task')">任务</el-radio-button>
            <el-radio-button label="courseware" @click="switchTab('courseware')">课件（暂未启用）</el-radio-button>
            <el-radio-button label="notice" @click="switchTab('notice')">通知</el-radio-button>
            <el-radio-button label="project" @click="switchTab('project')">项目</el-radio-button>
            <el-radio-button label="group" @click="switchTab('group')">团队</el-radio-button>
            <el-radio-button label="comment" @click="switchTab('comment')">评论</el-radio-button>
          </el-radio-group>
          <!--教师视角-->
          <div v-if="isCreator">
            <el-popover v-if="tabName==='task'" trigger="hover">
              <div style="display: flex;justify-content: space-around;">
                <el-button v-if="courseInfo.coderId!==null" type="text" @click="addTest('coder')" id="coder-button">
                  Coder
                </el-button>
                <el-button v-if="courseInfo.evalId!==null" type="text" @click="addTest('eval')" id="eval-button">Eval
                </el-button>
              </div>
              <template #reference>
                <el-button>添加测试</el-button>
              </template>
            </el-popover>
            <el-popover v-else-if="tabName==='notice'"
                        v-model:visible="noticePopover"
                        :width="160"
                        placement="bottom">
              <el-row class="sel-notice-type">
                <div :style="{color:themeColor.green}" class="notice-type-icon">
                  公告
                </div>
                <div class="notice-type-txt">
                  <el-link href="javascript:void(0);" type="success" @click="selAndInitAnnouncement('announcement')">
                    发布公告
                  </el-link>
                </div>
              </el-row>
              <el-row class="sel-notice-type">
                <div :style="{color:themeColor.orange}" class="notice-type-icon">
                  作业
                </div>
                <div class="notice-type-txt">
                  <el-link href="javascript:void(0);" type="warning" @click="selAndInitAnnouncement('homework')">发布作业
                  </el-link>
                </div>
              </el-row>
              <el-row class="sel-notice-type">
                <div :style="{color:themeColor.red}" class="notice-type-icon">
                  考试
                </div>
                <div class="notice-type-txt">
                  <el-link href="javascript:void(0);" type="danger" @click="selAndInitAnnouncement('exam')">发布考试
                  </el-link>
                </div>
              </el-row>
              <template #reference>
                <el-button plain type="primary" @click="noticePopover = true">添加发布
                </el-button>
              </template>
            </el-popover>
            <el-button v-else-if="tabName==='group'"
                       plain type="primary" :disabled="isRuleExisted||isRuleExisted===null"
                       @click="ruleFormDialog=true">
              {{ isRuleExisted === null ? null : (isRuleExisted ? '已开放组队' : '开放组队') }}
            </el-button>
            <el-upload v-else-if="tabName==='courseware'" :http-request="handleFileUploading"
                       :on-success="handleFileUploadSuccess"
                       :show-file-list="false" action="">
              <el-button plain type="primary">上传课件</el-button>
            </el-upload>
            <el-button v-else-if="tabName==='project'" @click="projectDialog=true"
                       plain type="primary">
              新建项目
            </el-button>
          </div>
          <!--学生视角-->
          <div v-if="isCourseSelected">
            <div v-if="tabName==='group'">
              <el-button v-if="isGroupExisted===false" :disabled="!isRuleExisted"
                         plain type="primary" @click="createGroupDialog=true">
                创建队伍
              </el-button>
              <el-button v-if="isGroupExisted===true"
                         plain type="primary" @click="addMemberDialog=true">
                邀请成员
              </el-button>
            </div>
          </div>
        </div>
        <!--tab内容-->
        <div v-if="isCreator || isCourseSelected" class="course-tab-content">
          <div v-if="tabName==='task'">
            <el-timeline>
              <el-timeline-item
                v-for="task in courseTaskList"
                :key="task['id']"
                :timestamp="task['examId'] ? task.startTime.substring(0, 16) + ' — ' + task.endTime.substring(0, 16) : timestampToTime(task['startAt'] * 1000) + ' — ' + timestampToTime(task['endAt'] * 1000)"
                :color="courseTaskStatusColor(task)" @click="toTask(task)">
                <el-row>
                  <el-tag v-if="task['examId']" class="timeline-content" size="small" color="#f5b86e" effect="dark"
                          style="border: none">E
                  </el-tag>
                  <el-tag v-else class="timeline-content" size="small" color="#8dc9e2" effect="dark"
                          style="border: none">C
                  </el-tag>
                  <el-row v-if="task['examId']" class="timeline-content">
                    <el-tag v-if="this.state(task)==='NOT_STARTED'" size="small" type="info">未开始</el-tag>
                    <el-tag v-else-if="this.state(task)==='RUNNING' && task['isJoined']" size="small" type="success">
                      已参加
                    </el-tag>
                    <el-tag v-else-if="this.state(task)==='RUNNING' && !task['isJoined']" size="small">未参加</el-tag>
                    <el-tag v-else-if="this.state(task)==='FINISHED'" size="small" type="info">已结束</el-tag>
                    <el-tag v-else-if="this.state(task)==='CLOSED'" size="small" type="info">已关闭</el-tag>
                  </el-row>
                  <el-row v-else class="timeline-content">
                    <el-tag v-if="this.state(task)==='NOT_STARTED'" size="small" type="info">未开始</el-tag>
                    <el-tag v-else-if="this.state(task)==='RUNNING' && task['isJoined']" size="small" type="success">已参加
                    </el-tag>
                    <el-tag v-else-if="this.state(task)==='RUNNING' && !task['isJoined']" size="small">未参加</el-tag>
                    <el-tag v-else-if="this.state(task)==='CLOSED'" size="small" type="info">已关闭</el-tag>
                    <el-tag v-else-if="this.state(task)==='FINISHED'" size="small" type="danger">已结束</el-tag>
                  </el-row>
                  <el-row v-if="task['examId']" class="task-title timeline-content">
                    {{ task["examName"] }}
                  </el-row>
                  <el-row v-else class="task-title timeline-content">
                    {{ task.name }}
                  </el-row>
                </el-row>
              </el-timeline-item>
            </el-timeline>
          </div>
          <div v-else-if="tabName==='notice'">
            <el-collapse v-if="announcementList.length!==0">
              <el-collapse-item v-for="(item,index) in announcementList" :key="item.id" :name="index"
                                @click="readAnnouncement(item)">
                <template #title>
                  <NoticeItem :ref="'noticeItem'+item.id"
                              :notice-v-o="item" @update="beforeUpdateAnnouncement(item)"
                              @delete="deleteAnnouncement(item, index)"/>
                </template>
                <div class="announcement-content">{{ announcementContent(item) }}</div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else-if="tabName==='courseware'">
            <div class="entry-header">
              <span class="name">文件名</span>
              <span class="size">文件大小</span>
              <span class="uploadTime">上传时间</span>
              <span class="operation">操作</span>
            </div>
            <FileEntry v-for="(entry,index) in fileEntryList"
                       :key="index"
                       :file-entry-info="entry"
                       @downloadFileIconClick="handleDownloadFileIconClick"
            ></FileEntry>
          </div>
          <div v-else-if="tabName==='comment'">
            <el-row>
              <el-col :span="20">
                <el-input v-model="commentContent" placeholder="发表一条友善的评论"/>
              </el-col>
              <el-col :span="4">
                <el-button style="width: 100%" type="primary" @click="createComment" plain>发表评论</el-button>
              </el-col>
            </el-row>
            <el-divider v-if="commentTree.length!==0"/>
            <div class="comment">
              <div v-for="(comments,index) in commentTree" :key="comments.id" class="comment-body">
                <div class="comment-main">
                  <el-row>
                    <div
                      style="color: white;background: #619dc9;border-radius: 50%;padding: 10px;width: 20px;height: 20px;display: flex;justify-content: center;align-items: center; margin: 10px 10px 0 0">
                      <span style="color: white; font-weight: bold;font-size: 24px;">{{
                          comments.mainMessage.sender.name.substring(0, 1)
                        }}</span>
                    </div>
                    <div>
                      <el-row style="font-weight: bold;">
                        {{ comments.mainMessage.sender.name }}
                      </el-row>
                      <el-row style="font-size: small; color: #6d6d6d; margin-bottom: 6px">
                        {{ comments.mainMessage.createdAt.substring(0, 16).replace("T", " ") }}
                      </el-row>
                      <el-row>
                        {{ comments.mainMessage.content }}
                        <span @click="handleReplyClick(comments.mainMessage, index)" class="reply-button">回复</span>
                        <span v-if="isOwnComment(comments.mainMessage.sender.id)"
                              @click="deleteComment(comments.mainMessage.id)"
                              class="reply-button">删除</span>
                      </el-row>
                    </div>
                  </el-row>
                </div>
                <div v-for="child in comments.children" :key="child.id" class="comment-child">
                  <el-row>
                    <div
                      style="color: white;background: #619dc9;border-radius: 50%;padding: 10px;width: 20px;height: 20px;display: flex;justify-content: center;align-items: center; margin: 10px 10px 0 0">
                      <span style="color: white; font-weight: bold;font-size: 24px;">{{
                          child.sender.name.substring(0, 1)
                        }}</span>
                    </div>
                    <div>
                      <el-row style="font-weight: bold; margin-bottom: 6px">
                        {{ child.sender.name }}
                      </el-row>
                      <el-row style="font-size: small; color: #6d6d6d; margin-bottom: 6px">
                        {{ child.createdAt.substring(0, 16).replace("T", " ") }}
                      </el-row>
                      <el-row>
                        <span style="color: black;">{{
                            child.targetId === null ? "" : `@${comments.children[child.targetId].sender.name}: `
                          }}</span>
                        {{ child.content }}
                        <span @click="handleReplyClick(child,index)" class="reply-button">回复</span>
                        <span v-if="isOwnComment(child.sender.id)"
                              @click="deleteComment(child.id)"
                              class="reply-button">删除</span>
                      </el-row>
                    </div>
                  </el-row>
                </div>
                <el-divider/>
              </div>
            </div>
          </div>
          <div v-else-if="tabName==='project'">
            <el-tabs v-model="projectTabName">
              <el-tab-pane label="公共项目" name="public">
                <div v-if="projects!==null">
                  <div v-if="projects.public.length===0">
                    当前没有公共项目
                  </div>
                  <div v-else>
                    <project-long-card v-for="item in projects.public" :key="'project'+item.id"
                                       :project="item" is-public :is-teacher="isCreator"
                                       @fork="handleForkProject(item.id)"
                                       @switch="handleSwitchProject(item.id)"/>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="私有项目" name="private">
                <div v-if="projects!==null">
                  <div v-if="projects.private.length===0">
                    当前没有私有项目
                  </div>
                  <div v-else>
                    <project-long-card v-for="item in projects.private" :key="'project'+item.id"
                                       :project="item" :is-teacher="isCreator"
                                       @switch="handleSwitchProject(item.id)"/>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div v-else-if="tabName==='group'">
            <el-table :data="groupTableData" style="width: 100%">
              <el-table-column label="组名">
                <template #default="scope">
                  <span :style="isGroupExisted && scope.row['groupVO'].id===groupData['groupVO'].id ? 'color: #67C23A':''">
                    {{ scope.row['groupVO'].name }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="组员">
                <template #default="scope">
                  <div v-for="item of scope.row.members" :key="'member'+item.id">
                    <span :style="isGroupExisted && scope.row['groupVO'].id===groupData['groupVO'].id ? 'color: #67C23A':''">
                      {{ item.username }}
                    </span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>
    <!--发布通知-->
    <el-dialog v-model="announcementFormDialog" :before-close="beforeFormClose" :title="announcementForm.dialogTitle">
      <el-form ref="announceFormRef" :model="announcementForm" :rules="announcementFormRule" label-position="right"
               label-width="60px">
        <el-form-item label="类别" prop="type">
          <el-select v-model="announcementForm.type">
            <el-option label="公告" value="announcement"></el-option>
            <el-option label="作业" value="homework"></el-option>
            <el-option label="考试" value="exam"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主题" prop="title">
          <el-input v-model="announcementForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="announcementForm.content" :rows="3" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: auto;width: fit-content">
        <el-button plain type="primary" @click="handlePublishAnnouncement">确认发布</el-button>
        <el-button plain type="danger" @click="beforeFormClose">我再想想</el-button>
      </div>
    </el-dialog>
    <!--小组规则-->
    <el-dialog v-model="ruleFormDialog" :before-close="beforeRuleFormClose" :title="ruleForm.dialogTitle">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="ruleFormRule" label-position="right" label-width="150px">
        <el-form-item label="小组最大人数" prop="maxSize">
          <el-input v-model="ruleForm.maxSize" type="number" min="1" max="5" placeholder="输入小组最大人数（1～5）" maxlength="1"
                    onkeypress='return( /[1-5]/.test(String.fromCharCode(event.keyCode)))'></el-input>
        </el-form-item>
        <el-form-item label="组名最大长度" prop="maxNameLen">
          <el-input v-model="ruleForm.maxNameLen" type="number" min="1" max="9" placeholder="输入组名最大长度(1~9)"
                    maxlength="1" onkeypress='return( /[1-9]/.test(String.fromCharCode(event.keyCode)))'></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: auto;width: fit-content">
        <el-button plain type="primary" @click="handleCreateRuleConfirm">确认</el-button>
      </div>
    </el-dialog>
    <!--新建项目-->
    <el-dialog v-model="projectDialog" :before-close="handleProjectFormClose" title="新建项目">
      <el-form :model="projectForm" ref="projectFormRef" label-position="right">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="projectForm.description" placeholder="请输入项目描述"/>
        </el-form-item>
        <el-form-item label="是否公共" prop="isPublic">
          <el-select v-model="projectForm.isPublic">
            <el-option label="公共" :value="true"/>
            <el-option label="私有" :value="false"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleProjectFormConfirm">
          确认
        </el-button>
      </template>
    </el-dialog>
    <!--组队信息-->
    <el-dialog v-model="createGroupDialog" :before-close="beforeGroupFormClose" :title="createGroupForm.dialogTitle">
      <el-form ref="createGroupFormRef" :model="createGroupForm" label-position="right">
        <el-form-item label="组名" prop="name">
          <el-input v-model="createGroupForm.name" placeholder="输入组名" maxlength="5"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: auto;width: fit-content">
        <el-button plain type="primary" @click="handleCreateGroupConfirm">确认</el-button>
      </div>
    </el-dialog>
    <!-- 添加组员-->
    <el-dialog v-model="addMemberDialog" :before-close="beforeGroupMemberFormClose" :title="addMemberForm.dialogTitle">
      <el-form ref="addMemberFormRef" :model="addMemberForm" label-position="right">
        <el-form-item label="组员手机号" prop="phone">
          <el-input v-model="addMemberForm.phone" placeholder="输入组员手机号" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: auto;width: fit-content">
        <el-button plain type="primary" @click="handleAddMemberConfirm">确认</el-button>
      </div>
    </el-dialog>
    <!-- 创建Coder考试-->
    <el-dialog v-model="coderExamDialog" :before-close="handleExamFormCancel" :width="1200" :title="coderExamForm.dialogTitle">
      <el-form ref="coderExamFormRef" :model="coderExamForm" :rules="coderExamFormRules" label-width="150px">
        <el-form-item label="所属课程" prop="course">
          <el-input disabled :placeholder="courseName" />
        </el-form-item>
        <el-form-item label="测试名称" prop="name">
          <el-input class="course-form-item" v-model="coderExamForm.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="测试时间" prop="range">
          <el-date-picker v-model="coderExamForm.range" range-separator="至"
                          start-placeholder="开始时间" end-placeholder="结束时间" type="datetimerange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="允许学生查看控制台">
          <el-switch v-model="coderExamForm.isConsoleOutputShownForStu" :disabled="switchExamDisabled" active-text="开启" inactive-text="不开启"/>
        </el-form-item>
        <el-form-item label="启用代码分析">
          <el-switch v-model="coderExamForm.isCodeAnalysisNeeded" :disabled="switchExamDisabled" active-text="开启" inactive-text="不开启"/>
        </el-form-item>
        <el-form-item label="题目列表">
          <el-button type="text" @click="showProblemDialog">选择题目</el-button>
        </el-form-item>
        <el-form-item v-if="$store.state.problem.cart.length">
          <el-collapse accordion>
            <el-collapse-item
                v-for="problem in $store.state.problem.cart"
                :key="problem.id"
                :name="problem.id"
            >
              <template #title>
                <span>{{ problem.name }}</span>
                <el-tag class="problem-type">{{ problem.type }}</el-tag>
              </template>
              <b>题目描述：</b>
              <span class="problem-description">{{ problem.description }}</span>
              <div class="remove-button">
                <el-button
                    type="danger"
                    size="mini"
                    @click="$store.commit('removeProblem', problem)"
                >移除该题</el-button
                >
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <div style="margin: auto;width: fit-content">
        <el-button type="primary" @click="handleExamCreate">确定</el-button>
        <el-button @click="handleExamFormCancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 展示Coder所有题目-->
    <el-dialog v-model="coderProblemDialog" :width="1200">
      <el-input v-model="dialogProblemName"
                style="width:200px;"
                placeholder="搜索"
      />
      <el-select v-model="dialogProblemTypeStr" style="width: 300px" @change="fetchProblemData(1)">
        <el-option v-for="item in problemTypeOptions" :key="item.value" :value="item.value">
          {{item.label}}
        </el-option>
      </el-select>
      <el-table :data="problemList" >
        <el-table-column type="expand">
          <template #default="props">
            <div>{{ props.row.description }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column label="类型">
          <template #default="scope">
            <span>{{ problemTypeToTagContent(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传时间">
          <template #default="scope">
            <span>{{ formatTimestamp(scope.row.createdAt)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
                type="primary"
                size="mini"
                @click="checkDetails"
            >详情</el-button
            >
            <el-button
                v-if="removeEnable(scope.row)"
                type="danger"
                size="mini"
                @click="$store.commit('removeProblem', scope.row)"
            >移出试题清单</el-button
            >
            <el-button
                v-else-if="addEnable(scope.row)"
                type="success"
                size="mini"
                @click="$store.commit('addProblem', scope.row)"
            >加入试题清单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="problemPageInfo.total"
          @current-change="changePage"
      />
    </el-dialog>
  </div>
</template>

<script>
import NoticeItem from "./components/NoticeItem";
import FileEntry from "./components/FileEntry";
import {ElMessageBox, ElMessage} from "element-plus";
import variables from "@/utils/variables";
import ProjectLongCard from "@/components/project/ProjectLongCard";
import {formatTimestamp, problemTypeOptions, problemTypeToTagContent} from "@/utils/coder-utils";

export default {
  name: "CourseDetail",
  components: {
    NoticeItem,
    FileEntry,
    ProjectLongCard,
  },
  data() {
    const themeColor = {
      green: "#67C23A",
      orange: "#E38800",
      blue: "#1989FA",
      red: "#F56C6C"
    };
    return {
      courseInfo: null,
      isCourseSelected: false,
      noImgUrl: variables.noImgUrl,
      themeColor,
      tabName: "task",
      noticePopover: false,
      //
      evalExamList: [],
      coderExamList: [],
      //
      announcementFormDialog: false,
      announcementForm: {
        dialogTitle: "添加发布",
        id: null,
        type: null,
        title: "",
        content: "",
      },
      announcementFormRule: {
        type: {
          required: true, message: "请选择发布类别", trigger: "change",
        },
        title: {
          required: true, message: "请输入发布主题", trigger: "blur",
        }
      },
      announcementList: [],
      //
      commentContent: "",
      commentTree: [],

      newNoticeType: {
        type: "",
        title: "",
        color: "",
      },
      noticeTypeMap: {
        announce: {type: "公告", title: "发布公告", color: themeColor.orange},
        homework: {type: "作业", title: "发布作业", color: themeColor.blue},
        exam: {type: "考试", title: "发布考试", color: themeColor.red},
      },
      newNoticeInfo: {noticeDescription: "", priority: "1", fileList: []},
      postNoticeInfo: {},
      fileEntryList: [{
        id: 1,
        name: "课程作业",
        size: "12.6MB",
        uploadTime: "2021-12-12 08:22:23",
        url: ""
      },
        {
          id: 2,
          name: "测试",
          size: "6KB",
          uploadTime: "2021-12-12 08:22:23",
          url: ""
        },
        {
          id: 3,
          name: "小练习",
          size: "45KB",
          uploadTime: "2021-12-12 08:22:23",
          url: ""
        }],

      // project
      projects: null,
      projectTabName: "public",
      projectDialog: false,
      projectForm: {
        name: "",
        description: "",
        isPublic: false,
      },

      // groupRule
      isRuleExisted: null,
      ruleFormDialog: false,
      ruleForm: {
        dialogTitle: "制定组队规则",
        courseVO: null,
        id: null,
        maxSize: null,
        maxNameLen: null,
      },
      ruleFormRule: {
        maxSize: {
          required: true, message: "请选择小组最大成员人数", trigger: "change",
        },
        maxNameLen: {
          required: true, message: "请选择组名最大长度", trigger: "change",
        }
      },

      // group
      isGroupExisted: null,
      createGroupDialog: false,
      createGroupForm: {
        dialogTitle: "队伍信息",
        courseId: null,
        name: null,
      },
      groupData: null,

      // group member
      addMemberDialog: false,
      groupTableData: [],
      addMemberForm: {
        dialogTitle: "组员信息",
        phone: null,
      },

      //create Coder exam
      coderExamDialog: false,
      coderExamDialogTitle: "新建Coder考试",
      coderExamForm: {
        examType: "coder",
        course: "",
        name: "",
        range: [],
        isCodeAnalysisNeeded: false,
        isConsoleOutputShownForStu: false
      },
      coderExamFormRules: {
        // type: {
        //   required: true, message: "请选择测试种类",
        // },
        name: {
          required: true, message: "请输入测试名称", trigger: "blur",
        },
        course: {
          required: true, message: "请选择测试名称",
        },
        range: {
          required: true, message: "请选择测试时间段", trigger: "blur",
        }
      },
      switchExamDisabled: false,

      //Coder problems
      coderProblemDialog: false,
      dialogProblemPage: 1,
      dialogProblemLimit: 10,
      dialogProblemTypeStr: "",
      dialogProblemName: "",
      problemList: [],
      problemPageInfo: {}

    };
  },
  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 ? this.noImgUrl : this.courseInfo.imageUrl;
    },
    courseTaskList() {
      return []
        .concat(this.evalExamList)
        .concat(this.coderExamList)
        .sort((a, b) => {
          let a_time = a["startAt"] * 1000 || new Date(a.startTime).getTime();
          let b_time = b["startAt"] * 1000 || new Date(b.startTime).getTime();
          return b_time - a_time;
        });
    },
    isOwnComment() {
      const _this = this;
      return function (senderId) {
        return senderId === Number(_this.$store.state.user.id);
      };
    },
    problemTypeOptions() {
      return problemTypeOptions(true);
    }
  },
  mounted() {
    switch (this.$route.params.jump_from_message) {
      case "1":
        this.tabName = "notice";
        break;
      case "2":
        this.tabName = "comment";
        break;
    }
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.$apis.getCourseById(this.$route.params.id)
          .then(res => {
            this.courseInfo = res.data.data;
            this.coderExamForm.course = this.courseInfo.coderId; //当前课程的coderId固定
            this.$apis.checkCourseSelection(this.$route.params.id, this.$store.state.user.id)
                .then(res => {
                  this.isCourseSelected = res.data.data;
                  if (this.isCreator || this.isCourseSelected) {
                    this.switchTab(this.tabName);
                  }
                });
          });
    },
    formatTimestamp,
    problemTypeToTagContent,
    // course

    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);
            });
        });
    },

    // tab

    async switchTab(tabName) {
      const _this = this;
      switch (tabName) {
        case "task":
          if (this.isTeacher) {
            if (this.courseInfo.evalId !== null) {
              this.evalExamList = (await this.$apis.getTeacherEvalExamsByCourseId(this.courseInfo.evalId)).data.data || [];
            }
            if (this.courseInfo.coderId !== null) {
              this.coderExamList = (await this.$apis.getTeacherCoderExamsByCourseId(this.courseInfo.coderId)).data.data;
            }
          } else if (this.isStudent) {
            if (this.courseInfo.evalId !== null) {
              this.evalExamList = (await this.$apis.getStudentEvalExamsByCourseId(this.courseInfo.evalId)).data.data || [];
            }
            if (this.courseInfo.coderId !== null) {
              this.coderExamList = (await this.$apis.getStudentCoderExamsByCourseId(this.courseInfo.coderId)).data.data;
            }
          }
          break;
        case "notice":
          this.announcementList = (await this.$apis.getAnnouncementsByCourseId(this.$route.params.id)).data.data;
          break;
        case "courseware":
          break;
        case "comment":
          this.commentTree = (await this.$apis.getCommentsByCourseId(this.$route.params.id)).data.data;
          break;
        case "project":
          const projectRes = (await _this.$apis.findProjectsByCourse(_this.courseInfo.id)).data;
          if (projectRes.code) {
            ElMessage.error(projectRes.message);
          } else {
            _this.projects = projectRes.data;
          }
          break;
        case "group":
          const ruleRes = (await _this.$apis.findGroupRule(this.courseInfo.id)).data;
          _this.isRuleExisted = !ruleRes.code;
          if (_this.isRuleExisted) {
            const groupsRes = (await _this.$apis.findAllGroupsByCourse(this.courseInfo.id)).data;
            if (!groupsRes.code) {
              _this.groupTableData = groupsRes.data;
            }
            const groupRes = (await _this.$apis.findGroup(_this.courseInfo.id)).data;
            _this.isGroupExisted = !groupRes.code;
            if (_this.isGroupExisted) {
              _this.groupData = groupRes.data;
            }
          }
          break;
      }
    },

    // time

    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;
    },

    // task

    courseTaskStatusColor(VO) {
      if (this.state(VO) === "FINISHED" || this.state(VO) === "NOT_STARTED" || this.state(VO) === "CLOSED") {
        return "grey";
      } else if (VO["isJoined"] || VO["joined"]) {
        return this.themeColor.green;
      } else {
        return this.themeColor.blue;
      }
    },

    state(VO) {
      if (VO["examId"]) {
        if (new Date(VO.endTime) < new Date()) {
          return "FINISHED";
        } else if (new Date(VO.startTime) > new Date()) {
          return "NOT_STARTED";
        } else {
          return "RUNNING";
        }
      } else {
        if (VO.status === "CLOSED") {
          return "CLOSED";
        } else if (VO["startAt"] * 1000 > new Date()) {
          return "NOT_STARTED";
        } else if (VO["endAt"] * 1000 < new Date()) {
          return "FINISHED";
        } else {
          return "RUNNING";
        }
      }
    },

    addTest(type) {
      switch (type) {
        case "eval":
          if (this.courseInfo.evalId === null) {
            ElMessage.error("本课程没有链接eval系统");
          }
          window.open("https://eval.seec.seecoder.cn/teacher/create/?id_token=" + this.$store.state.user.token);
          break;
        case "coder":
          if (this.courseInfo.coderId === null) {
            ElMessage.error("本课程没有链接coder系统");
          }
          this.coderExamDialog = true;
          // window.open("https://coder.seec.seecoder.cn/exam/create/?id_token=" + this.$store.state.user.token);
          break;
      }
    },

    toTask(task) {
      const type = task["examId"] ? "eval" : "coder";
      let evalUrl;
      let evalExamUrl;
      let coderUrl;
      let url;
      if (this.isStudent) {
        evalUrl = "https://eval.seec.seecoder.cn/student/home/";
        evalExamUrl = "https://eval.seec.seecoder.cn/exam/";
        coderUrl = "https://coder.seec.seecoder.cn/exam/";
        switch (this.state(task)) {
          case "NOT_STARTED":
            url = type === "eval" ? evalUrl : coderUrl;
            break;
          case "CLOSED":
            url = type === "eval" ? evalUrl : coderUrl;
            break;
          case "FINISHED":
            url = type === "eval" ? evalUrl : coderUrl;
            break;
          case "RUNNING":
            if (task["isJoined"] || task["joined"]) {
              url = type === "eval" ? evalExamUrl + task["examId"] + "/before-exam" : coderUrl + task.id;
            } else {
              url = type === "eval" ? evalUrl : coderUrl;
            }
            break;
        }
      } else {
        evalUrl = "https://eval.seec.seecoder.cn/teacher/exam/";
        coderUrl = "https://coder.seec.seecoder.cn/exam/";
        url = type === "eval" ? evalUrl + task["examId"] + "/details" : coderUrl + task.id;
      }

      if (type === "coder") {
        this.$router.push(`/exam/${task.id}`);
      }
      // window.open(url + "?id_token=" + this.$store.state.user.token);
    },

    // announcement

    selAndInitAnnouncement(type) {
      this.announcementForm.type = type;
      this.announcementFormDialog = true;
    },

    beforeFormClose() {
      ElMessageBox.confirm("是否确认退出？退出后将不保存表格信息。", "提示", {
        confirmButtonText: "确认退出",
        cancelButtonText: "我再想想",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.announcementFormDialog = false;
          this.$refs.announceFormRef.resetFields();
        });
    },

    handlePublishAnnouncement() {
      const _this = this;
      if (this.announcementForm.content === "") {
        ElMessageBox.confirm("是否确认发布内容为空？", "提示", {
          confirmButtonText: "确认为空",
          cancelButtonText: "我再想想",
          type: "warning",
          center: true,
        })
          .then(() => {
            if (this.announcementForm.id === null) {
              createAnnouncement();
            } else {
              updateAnnouncement();
            }
          });
      } else {
        if (this.announcementForm.id === null) {
          createAnnouncement();
        } else {
          updateAnnouncement();
        }
      }

      function createAnnouncement() {
        let announcementVO = {
          sender: {id: _this.$store.state.user.id,},
          courseId: _this.courseInfo.id,
          title: _this.announcementForm.title,
          content: _this.announcementForm.content,
          type: _this.announcementForm.type.toUpperCase(),
          createdAt: new Date(),
        };
        _this.$apis.createAnnouncement(announcementVO)
          .then(res => {
            _this.announcementList.push(res.data.data);
            _this.announcementFormDialog = false;
            _this.$refs.announceFormRef.resetFields();
            ElMessage.success("新建公告完成");
          });
      }

      function updateAnnouncement() {
        let announcementVO = {
          id: _this.announcementForm.id,
          title: _this.announcementForm.title,
          content: _this.announcementForm.content,
          type: _this.announcementForm.type.toUpperCase(),
        };
        _this.$apis.updateAnnouncement(announcementVO)
          .then(res => {
            for (let i = 0; i < _this.announcementList.length; i++) {
              if (_this.announcementList[i].id === _this.announcementForm.id) {
                _this.announcementList[i] = res.data.data;
              }
            }
            _this.$refs["noticeItem" + _this.announcementForm.id][0].setNoticeInfo(res.data.data);
            _this.announcementFormDialog = false;
            _this.$refs.announceFormRef.resetFields();
            ElMessage.success("修改公告完成");
          });
      }
    },

    beforeUpdateAnnouncement(item) {
      this.announcementForm.dialogTitle = "修改公告";
      this.announcementForm.id = item.id;
      this.announcementForm.type = item.type;
      this.announcementForm.title = item.title;
      this.announcementForm.content = item.content;
      this.announcementFormDialog = true;
    },

    deleteAnnouncement(item, index) {
      ElMessageBox.confirm("是否确认删除公告  \"" + item.title + "\"  ？", "提示", {
        confirmButtonText: "确认删除",
        cancelButtonText: "我再想想",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.$apis.deleteAnnouncement(item.id)
            .then(() => {
              this.announcementList.splice(index, 1);
            });
        });
    },

    announcementContent(item) {
      if (item.content === "") {
        return "当前公告暂无具体内容。";
      } else {
        return item.content;
      }
    },

    readAnnouncement(item) {
      if (!item.read) {
        this.$apis.readAnnouncement(item.id)
          .then(() => {
            item.read = true;
            this.$refs["noticeItem" + item.id][0].setNoticeInfo(item);
          });
      }
    },

    // courseware

    handleFileUploading() {
    },

    handleFileUploadSuccess() {
    },

    handleDownloadFileIconClick(url) {
    },

    // comment

    createComment() {
      if (this.commentContent === "") {
        ElMessage.error("无法发表空评论");
      } else {
        this.$apis.createMessage({
          sender: {
            id: this.$store.state.user.id,
          },
          actionType: "COMMENT",
          targetType: "COURSE",
          targetId: this.courseInfo.id,
          mntId: this.courseInfo.id,
          content: this.commentContent,
          createdAt: new Date(),
        })
          .then(res => {
            const msg = res.data.data;
            msg.createdAt = this.timestampToTime(msg.createdAt);
            this.commentTree.push({mainMessage: msg, children: {}});
            this.commentContent = "";
            ElMessage.success("发送成功");
          });
      }
    },

    async deleteComment(commentId) {
      const res = (await this.$apis.deleteMessage(commentId)).data.data || null;
      if (res == null) {
        alert(res);
        return;
      }
      this.$message.success(res);
      this.commentTree = (await this.$apis.getCommentsByCourseId(this.$route.params.id)).data.data;
    },

    handleReplyClick(target, index) {
      ElMessageBox.prompt("请输入评论内容", "回复", {
        confirmButtonText: "发送",
        cancelButtonText: "取消",
      })
        .then(({value}) => {
          if (value === "") {
            ElMessage.error("无法发表空评论");
          } else {
            this.$apis.createMessage({
              sender: {
                id: this.$store.state.user.id,
              },
              actionType: "COMMENT",
              targetType: "COMMENT",
              targetId: target.id,
              mntId: target.targetType === "COURSE" ? target.id : target.mntId,
              content: value,
              createdAt: new Date(),
            })
              .then(res => {
                const msg = res.data.data;
                msg.createdAt = this.timestampToTime(msg.createdAt);
                if (msg.targetId === this.commentTree[index].mainMessage.id) {
                  msg.targetId = null;
                }
                this.commentTree[index].children[msg.id] = msg;
                this.commentContent = "";
                ElMessage.success("发送成功");
              });
          }
        });
    },

    // project

    handleProjectFormClose() {
      const _this = this;
      _this.projectDialogVisible = false;
      _this.$refs.projectFormRef.resetFields();
    },

    async handleProjectFormConfirm() {
      const _this = this;
      const res = (await _this.$apis.createProject({
        courseId: _this.courseInfo.id,
        ..._this.projectForm,
      })).data;
      if (res.code) {
        ElMessage.error(res.message);
      } else {
        if (_this.projectForm.isPublic) {
          _this.projects.public.push(res.data);
        } else {
          _this.projects.private.push(res.data);
        }
        _this.projectDialogVisible = false;
        _this.$refs.projectFormRef.resetFields();
      }
    },

    async handleSwitchProject(id) {
      const _this = this;
      const res = (await _this.$apis.updateCourseProjectState(id)).data;
      if (!res.code) {
        if (res.data) {
          removeProject(_this.projects.private, _this.projects.public);
        } else {
          removeProject(_this.projects.public, _this.projects.private);
        }
      }

      function removeProject(array1, array2) {
        for (const index in array1) {
          if (array1[index].id === id) {
            array2.push(array1[index]);
            array1.splice(index, 1);
            return;
          }
        }
      }
    },

    async handleForkProject(id) {
      const _this = this;
      const res = (await _this.$apis.forkProject(id)).data;
      ElMessage.success(JSON.stringify(res));
    },

    // group rule

    beforeRuleFormClose() {
      ElMessageBox.confirm("是否确认退出？退出后将不保存组队规则信息。", "提示", {
        confirmButtonText: "确认退出",
        cancelButtonText: "我再想想",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.ruleFormDialog = false;
          this.$refs.ruleFormRef.resetFields();
        });
    },

    handleCreateRuleConfirm() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          let RuleVO = {
            courseVO: {id: this.courseInfo.id},
            maxSize: this.ruleForm.maxSize,
            maxNameLen: this.ruleForm.maxNameLen,
          };
          this.$apis.createGroupRule(RuleVO)
            .then(res => {
              if (res.data.code) {
                ElMessage.error(res.data.message);
              } else {
                this.isRuleExisted = true;
                this.ruleFormDialog = false;
                this.$refs.ruleFormRef.resetFields();
                ElMessage.success("创建规则成功");
              }
            });
        }
      });
    },

    // group

    beforeGroupFormClose() {
      this.createGroupDialog = false;
      this.$refs.createGroupFormRef.resetFields();
    },

    handleCreateGroupConfirm() {
      this.$refs.createGroupFormRef.validate((valid) => {
        if (valid) {
          let GroupVO = {
            courseId: this.courseInfo.id,
            name: this.createGroupForm.name,
          };
          this.$apis.createGroup(GroupVO)
            .then(res => {
              if (res.data.code) {
                ElMessage.error(res.data.message);
              } else {
                this.isGroupExisted = true;
                this.groupTableData.push(res.data.data);
                this.createGroupDialog = false;
                this.$refs.createGroupFormRef.resetFields();
                ElMessage.success("创建队伍成功");
              }
            });
        }
      });
    },

    // group member

    beforeGroupMemberFormClose() {
      this.addMemberDialog = false;
      this.$refs.addMemberFormRef.resetFields();
    },

    handleAddMemberConfirm() {
      const _this = this;
      this.$refs.addMemberFormRef.validate(async (valid) => {
        if (valid) {
          const userIdRes = (await _this.$apis.findUserIdByPhone(_this.addMemberForm.phone)).data;
          if (userIdRes.code) {
            ElMessage.error(userIdRes.message);
            return;
          }
          let groupMemberVO = {
            userId: userIdRes.data,
            groupId: _this.groupData.groupVO.id,
            courseId: _this.courseInfo.id,
          };
          this.$apis.addGroupMember(groupMemberVO)
            .then(res => {
              if (res.data.code) {
                ElMessage.error(res.data.message);
              } else {
                const groupDTO = res.data.data;
                for (const row of _this.groupTableData) {
                  if (groupDTO.groupVO.id === row.groupVO.id) {
                    row.members = groupDTO.members;
                  }
                }
                _this.addMemberDialog = false;
                _this.$refs.addMemberFormRef.resetFields();
                ElMessage.success("添加组员成功");
              }
            });
        }
      });

    },

    // 创建Coder考试的Dialog
    handleExamFormCancel(done) {
      //关闭dialog的提示
      ElMessageBox.confirm("是否确认退出？退出后将不保存表格信息。", "提示", {
        confirmButtonText: "确认退出",
        cancelButtonText: "我再想想",
        type: "warning",
        center: true,
      })
          .then(() => {
            this.coderExamDialog = false;
            // this.clearForm();
            //TODO 清除表格信息
            done();
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 展示Coder所有的problem题目（代码题）
    showProblemDialog(){ //打开弹框，获取初始数据
      this.fetchProblemData();
      this.coderProblemDialog = true;
    },

    fetchProblemData(page=1) { // 按需获得Coder题目
      this.$apis.retrievePageProblem(page, this.dialogProblemLimit, this.dialogProblemTypeStr, this.dialogProblemName)
          .then(_res => {
            this.problemPageInfo = _res.data.page;
            this.problemList = _res.data.res;
          }).catch(err => {
        console.log(err);
      });
    },

    //验证表单数据，创建考试
    handleExamCreate(){
      const form = this.$refs.coderExamFormRef;
      form.validate((valid) => {
        if (valid) {
          console.log("validate 成功");
          this.createCoderExam();
        } else {
          console.log("validate 失败了");
          return false;
        }
      });
    },

    createCoderExam(){
      //创建Coder考试
      this.$apis.createCoderExam({
        course: this.coderExamForm.course,
        name: this.coderExamForm.name,
        startAt: this.coderExamForm.range[0].getTime()/1000,
        endAt: this.coderExamForm.range[1].getTime()/1000,
        problems: this.$store.state.problem.cart.map((item) => item.id),
        isConsoleOutputShownForStu: this.coderExamForm.isConsoleOutputShownForStu
      }).then(_res => {
        this.$store.commit("clearProblem");
        ElMessage.success("创建测试成功！");
        this.clearCoderExamForm(); //清空Coder考试表单内容
        this.fetchData(); //重新获取数据，实时刷新页面
        this.coderExamDialog = false;
      }).catch(_err => {
        console.log(_err);
        ElMessage.warning("创建测试失败！");
      });
    },

    //查看题目详情（暂不支持）
    checkDetails(){
      ElMessage.warning("暂不支持查看详情！");
    },

    //题目购物车cart
    removeEnable(problem) { //是否可以移除题目
      return this.$store.state.problem.cart.length && this.$store.state.problem.cart
          .map((item) => item.id)
          .includes(problem.id);
    },
    addEnable(problem) { //是否可以添加题目
      return this.$store.getters.isTeacher && problem.modifiedAt;
    },

    changePage(val){
      this.fetchProblemData(val);
    },

    clearCoderExamForm(){
      this.coderExamForm = {
        examType: "coder",
        course: this.courseInfo.coderId,
        name: "",
        range: [],
        isCodeAnalysisNeeded: false,
        isConsoleOutputShownForStu: false
      };
    },
  },
};
</script>

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