<template>
  <div class="homework-details">
    <div class="homework-details-title">
      作业详情
    </div>
    <div class="homework-details-info">
      <div class="homework-details-text">
        <div class="title">
          {{data.assignmentName}}
        </div>
        <div class="item">
          <span style="font-weight: 600">作业描述: </span>
          {{data.description}}
        </div>
        <div class="item">
          <span style="font-weight: 600">发布老师: </span>
          {{data.teacherName}}
        </div>
        <div class="item">
          <span style="font-weight: 600">开始时间: </span>
          {{new Date(Date.parse(data.startTime)).toLocaleString()}}
        </div>
        <div class="item">
          <span style="font-weight: 600">截止日期: </span>
          {{new Date(Date.parse(data.endTime)).toLocaleString()}}
        </div>
        <div class="item">
          <el-link type="primary" @click="downloadFile(data.descriptionFile, `${data.assignmentName}-描述文件`)">相关文件下载</el-link>
          <div class="button-container">
            <el-button style="margin-left: 550px; color: #FFFFFF;" color="#7EB5E1" @click="handleBack">返回</el-button>
            <el-button
              style="color: #FFFFFF;"
              color="#7ADBB0"
              @click="handleStart()"
              :disabled="isAssignmentDisabled"
              :title="getButtonTooltip"
            >
              开始{{ data.type }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
<!--    <div class="homework-details-title">-->
<!--      评论区-->
<!--    </div>-->
<!--    <div class="homework-remark">-->
<!--      <div>-->
<!--        <el-skeleton style="width: 240px" animated >-->
<!--          <template #template>-->
<!--            <el-skeleton-item variant="circle" style="&#45;&#45;el-skeleton-circle-size: 40px"></el-skeleton-item>-->
<!--            <el-skeleton-item variant="text" style="height: 40px;width: 200px; margin-left: 30px"></el-skeleton-item>-->
<!--          </template>-->
<!--        </el-skeleton>-->
<!--      </div>-->
<!--      <div>-->
<!--        <el-input type="textarea" style="width: 100%;margin: 20px 0"></el-input>-->
<!--        <el-button color="#597d3b" size="large" style="float: right" :disabled="true">发布</el-button>-->
<!--      </div>-->
<!--    </div>-->
  </div>
</template>

<script lang="ts" setup>
import useApis from "@/apis";
import {useRoute} from "vue-router";
import {onMounted, reactive, computed, ref} from "vue";
import type {IAssignment, engagementVO} from "@/types/vo";
import './homeworkDetail.scss'
import {useStore} from "@/store";
import router from "@/router";
import {ElMessage} from "element-plus";

const apis = useApis()
const store = useStore()
const route = useRoute()
const assignmentId = +route.params.assignmentId //string转number

let data = reactive<IAssignment>({
  assignmentId: null,
  assignmentName: "",
  description: "",
  descriptionFile: null,
  attachments: null,
  teacherId: null,
  teacherName: "",
  courseId: null,
  startTime: "",
  endTime: "",
  createTime: "",
  status: "",
  type:""
})

// 学生作业参与状态
const engagementStatus = ref<engagementVO | null>(null)

// 计算属性：判断作业是否应该禁用
const isAssignmentDisabled = computed(() => {
  const now = new Date()
  const startTime = new Date(data.startTime)
  const endTime = new Date(data.endTime)

  // 如果当前时间小于开始时间，则禁用
  if (now < startTime) {
    return true
  }

  // 如果当前时间大于结束时间
  if (now > endTime) {
    // 超过截止日期时，只有未完成状态的学生可以点击
    if (engagementStatus.value) {
      return engagementStatus.value.status !== 'NOT_SUBMITTED'
    }
    // 如果没有参与状态信息，允许点击（首次参与）
    return false
  }

  // 在作业时间范围内，不禁用
  return false
})

// 计算属性：按钮提示文本
const getButtonTooltip = computed(() => {
  const now = new Date()
  const startTime = new Date(data.startTime)
  const endTime = new Date(data.endTime)

  if (now < startTime) {
    return `作业尚未开始，开始时间：${startTime.toLocaleString()}`
  } else if (now > endTime) {
    if (engagementStatus.value) {
      const status = engagementStatus.value.status
      if (status === 'NOT_SUBMITTED') {
        return '作业已截止，但您可以继续完成作业'
      } else if (status === 'SUBMITTED') {
        return '作业已截止且已提交，无法再次编辑'
      } else if (status === 'CORRECTED') {
        return '作业已截止且已批改，无法再次编辑'
      }
    }
    return `作业已截止，截止时间：${endTime.toLocaleString()}`
  } else {
    return '点击开始作业'
  }
})

function handleStart(){
  apis.getEngagement(store.user.id, assignmentId)
      .then((_res:any) => {
        //还未参加作业，则先加入作业
        if(_res.data.data == null){
          apis.engageAssignment(assignmentId)
              .then((res:any) => {
                ElMessage({
                  message: '参加作业成功',
                  type: 'success',
                })
                // 加入作业后重新获取状态
                fetchEngagementStatus()
                if(data.type == 'writing' || data.type == '写作'){
                  router.push(`/home/assignment/${assignmentId}/edit`).then(() => {
                    window.location.reload()
                  })
                } else if(data.type == 'speaking' || data.type == 'AI口语'){
                  router.push(`/home/assignment/${assignmentId}/aispeaking`).then(() => {
                    window.location.reload()
                  })
                }
              })
              .catch((_err:any) => {
                console.log("参加做业的错误",_err)
                ElMessage({
                  message: '参加作业失败',
                  type: 'error',
                })
              })
        }
        else{
          if(data.type == 'writing' || data.type == '写作'){
            router.push(`/home/assignment/${assignmentId}/edit`).then(() => {
              window.location.reload()
            })
          } else if(data.type == 'speaking' || data.type == 'AI口语'){
            router.push(`/home/assignment/${assignmentId}/aispeaking`).then(() => {
              window.location.reload()
            })
          }
        }
      }).catch((_err:any) => {
    console.log(_err)
  })
  console.log(data.type)
}

function downloadFile(url:string, fileName:string) {
  const link = document.createElement('a');
  link.href = url;
  //link.download = fileName;
  //link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
  link.click();
}


// 获取学生作业参与状态（仅查询，不自动加入）
async function fetchEngagementStatus() {
  try {
    const response = await apis.getEngagement(store.user.id, assignmentId)
    if (response.data.code === 200 && response.data.data) {
      engagementStatus.value = response.data.data
    } else {
      engagementStatus.value = null
    }
  } catch (error) {
    console.log('获取作业参与状态失败:', error)
    engagementStatus.value = null
  }
}



const fetchData = () => {
  apis.getAssignmentById(assignmentId)
      .then((res: any) => {
        Object.assign(data, res.data.data)
      })
}

const handleBack = () => {
   // 跳转到我的作业页面，携带课程ID参数以便自动选中对应课程
  const { fromCourse} = route.query
  if (!fromCourse){
    router.push({
      name: 'myHomework',
      query: {
        courseId: data.courseId,
        fromAssignment: 'true'
      }
    }).then(() => {window.location.reload()})
  }
  else{
    router.back()
  }

}

onMounted(() => {
  fetchData()
  fetchEngagementStatus()
})
</script>

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

<style scoped>
  .button-container {
    display: flex;
  }

  .el-button {
    margin-right: 0px;
  }

  /* 禁用状态的开始按钮样式 */
  .el-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .el-button:disabled:hover {
    opacity: 0.6;
  }
</style>


