<!--
  Description: 课程详情页面的课程作业表格组件
  Author: BaiQi
  Created Date: 2024-7-1
-->
<template>
  <el-card>
    <template v-if="props.role == 'teachers'">
      <el-button style="background-color: #6A9BD8; color: white;" @click="isTypeDialogVisible=true" v-if="props.isShowNewHomework">新建作业</el-button>
    </template>
    <template v-if="props.tableData.length > 0">
      <el-table :data="props.tableData" stripe style="width: 100%" height="100%" show-overflow-tooltip>
        <el-table-column type="index"></el-table-column>
        <el-table-column
            v-for="column in props.columns"
            :key="column.key"
            :prop="column.dataIndex"
            :label="column.title"
            :width="column.width"
        >
        </el-table-column>
        <!-- TODO:找到了 详情界面 -->
        <el-table-column label="详情" width="60">
          <template #default="scope">
            <el-button   style="background-color: #6A9BD8; color: white;" circle @click="openEditor(scope.row.descriptionFile, scope.row.assignmentName)">
              <el-icon :size="18">
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column :label="role == 'teachers'? '编辑':'开始'" width="60">
          <template #default="scope">
            <el-button @mouseover="handleMouse('over', scope.row.teacherId, scope.row.endDate)" @mouseleave="handleMouse('leave', scope.row.teacherId, scope.row.endDate)"
                style="background-color: #6A9BD8; color: white;" circle @click="handleFunctionButton(scope.row.assignmentId,scope.row.type)" :disabled="props.disabled || isDisabled(scope.row.teacherId, scope.row.endDate)">
              <el-icon :size="18">
                <Edit />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-else>
      <div style="text-align: center;">暂无作业</div>
    </template>
  </el-card>



  <writing-assignment-dialogue
      v-model:writingVisible="writingVisible"
      :dialogConfig="dialogConfig"
      :courseId="props.courseId"
    />
  <ai-speaking-assignment-dialogue
      v-model:AISpeakingVisible="AISpeakingVisible"
      :dialogConfig="dialogConfig"
      :courseId="props.courseId"
  />

  <el-dialog
    v-model="isTypeDialogVisible"
    title="选择作业类型"
    style="width:450px"
  >
    <el-radio-group v-model="assignmentType">
      <el-radio label="写作">写作</el-radio>
      <el-radio label="AI口语">AI口语</el-radio>
    </el-radio-group>
    <div class="dialog-footer" style="margin-top:40px;margin-left:30%;">
      <el-button @click="isTypeDialogVisible = false">取消</el-button>
      <el-button style="background-color: #6A9BD8; color: white;" type="primary" @click="createAssignmentDialog()">确定</el-button>
    </div>
  </el-dialog>
  <ViewsWordEditor :alert="alertProps" :docxInfo="docxInfo"></ViewsWordEditor>
</template>


<script lang="ts" setup>
import {defineProps, inject, onMounted, reactive, ref} from 'vue';
  import type {AssignmentVO, IAssignmentTableColumn, IAssignmentTableItem} from "@/types/vo";
  import router from "@/router";
  import type {AssignmentDTO} from "@/types/dto";
  import useApis from "@/apis";
  import {
  ElMessage,
  ElNotification,
  ElMessageBox,
  type UploadFile,
  type UploadFiles,
  type UploadProps,
  type UploadUserFile
} from "element-plus";
  import {useFormatDate} from "@/hooks/useFormatDate";
  import ViewsWordEditor from "@/components/ViewsWordEditor/ViewsWordEditor.vue";
  import WritingAssignmentDialogue from './AssignmentDialogue/WritingAssignmentDialogue.vue';
  import AiSpeakingAssignmentDialogue from './AssignmentDialogue/AiSpeakingAssignmentDialog.vue';
  import {useStore} from "@/store";
  import {Search, Edit, UploadFilled, Plus} from "@element-plus/icons-vue"

  const props = defineProps<{
    tableData: IAssignmentTableItem[],
    columns: IAssignmentTableColumn[],
    role: string,
    courseId: number,
    isShowNewHomework: boolean,
    disabled: boolean;
  }>()

  const apis = useApis()
  const store = useStore()
  const doRefresh:Function = inject("reload")
  const {formatDate} = useFormatDate()
  let uploadDescribeRef = ref()
  let uploadPictureRef = ref()

  const writingVisible = ref(false)
  const AISpeakingVisible = ref(false)
  const isTypeDialogVisible = ref(false);
  const assignmentType = ref()

  const dialogConfig = reactive({
    type: "",
    title: "",
    disable: false,
    assignmentId:0
  })


  const changeDialog = (type:string, assignmentId: number, assignmentType: string)=>{
    switch (type){
      case "add": {
        dialogConfig.type="add";
        dialogConfig.title=`新增${assignmentType}作业`;
        dialogConfig.disable=false;
        dialogConfig.assignmentId = assignmentId;
        break;
      }
      case "edit": {
        dialogConfig.type="edit";
        dialogConfig.title=`编辑${assignmentType}作业`;
        dialogConfig.disable=false;
        dialogConfig.assignmentId = assignmentId;
        break;
      }
    }
  }


  const createAssignmentDialog = ()=>{
    isTypeDialogVisible.value = false;
    if(assignmentType.value != ''){
     changeDialog('add', 0, assignmentType.value)
     if(assignmentType.value === '写作'){
        writingVisible.value = true;
      } else if(assignmentType.value === 'AI口语'){
        AISpeakingVisible.value = true;
      }
    }
  }

  let open = ref(false)

  const alertProps = reactive({
    open: open.value,
    onOk: () => (open.value = false),
    onCancel: () => (open.value = false),
  });

  const docxInfo = reactive({
    docxUrl: null,
    docxTitle: null,
  });

const openEditor = (url: string, title: string) => {
  open.value = true;
  Object.assign(alertProps, {
    open: open.value,
    // onOk: () => (open.value = false),
    onCancel: () => {
      open.value = false
      Object.assign(alertProps,{
        open: open.value,
        onOk: () => (open.value = false),
        onCancel: () => (open.value = false),
      })
      Object.assign(docxInfo, {
        docxUrl: url,
        docxTitle: title,
      })
    },
  })
  Object.assign(docxInfo, {
    docxUrl: url,
    docxTitle: title,
  })
};

  let newAssignmentInfo = reactive<AssignmentDTO>({
    assignmentName: '',
    description: '',
    type:'',
    descriptionFile: '',
    attachments: [''],
    startTime: '',
    endTime: ''
  })

  const cleanNewAssignmentInfo = () => {
    Object.assign(newAssignmentInfo, {
      assignmentName: '',
      description: '',
      type:'',
      descriptionFile: '',
      attachments: [''],
      startTime: '',
      endTime: ''
    })
  }

  const setNewAssignmentInfo = (assignment: AssignmentVO) => {
    Object.assign(newAssignmentInfo, {
      assignmentName: assignment.assignmentName,
      description: assignment.description,
      type:assignment.type,
      descriptionFile: assignment.descriptionFile,
      attachments: assignment.attachments == null? ['']:assignment.attachments,
      startTime: assignment.startTime,
      endTime: assignment.endTime
    })
    // console.log("获取作业信息", newAssignmentInfo)
  }

  /*
  鼠标聚焦于功能按钮（写作or编辑）时，显示提示信息
   */
  let lastTriggerTime = 0;

  // 防抖函数
  const throttleMessage = () => {
    const currentTime = Date.now();
    
    // 如果距离上次触发时间小于5秒，则不执行
    if (currentTime - lastTriggerTime < 5000) {
      return false;
    }
    
    // 更新触发时间并执行
    lastTriggerTime = currentTime;
    return true;
  };
  let hover = false
  const handleMouse = (type: string, teacherId:string, endDate:string) => {
    if(!hover && type == 'over'){
       hover = true;
       //如果被禁用则提示
      if((props.disabled || isDisabled(teacherId, endDate))&&throttleMessage()){
        if(props.role == 'student'){
          ElMessage.warning('请先加入课程')
        }else if(props.role == 'teachers'){
          ElMessage.warning('无权限')
        }
      }
    } else if(hover && type == 'leave'){                    
      hover = false
    }
  }

  // 用于记录当前编辑的作业的id
  let IAssignmentId = ref(0)
  const handleFunctionButton = (assignmentId:number,  type: string) => {
    if(props.role == 'student'){
      handleWriting(assignmentId)
    } else if(props.role == 'teachers'){
      changeDialog('edit', assignmentId, type)
      if(type === '写作' || type == 'writing'){
        writingVisible.value = true;
      } else if(type === 'AI口语' || type == 'speaking'){
        AISpeakingVisible.value =true;
      }
    }
  }

  const handleWriting = (assignmentId:number) => {
    router.push(`/home/homeworkDetail/${assignmentId}?fromCourse=1`).then(() => {
      window.location.reload()
    });
    // Location.reload()
  }




  const isDisabled = (teacherId: string, endDate: string) => {
    if(props.role == 'teachers'){// 是教师且不是作业发布人则禁用
      if(+teacherId != store.user.id){
        return true
      }
    }
    // 学生不再因为超过截止日期而禁用按钮
    return false
  }

</script>

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

<style scoped>
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }


</style>
