<template>
  <div v-loading="loading" class="task-detail">
    <TaskTop :item-info="itemInfo" type="student" @viewFile="viewFile" />

    <div class="task-detail-main">
      <div class="time-type">{{ $t(timeType) }} {{ name }}</div>
      <div class="time-interval">
        {{ time_space_view_txt }}
      </div>
      <div class="task-require">
        <span class="label">{{ $t('Key326') }}</span>
        <span v-html="contentUrl"></span>
      </div>
      <div class="task-courseware">
        <span class="label">{{ $t('Key312') }}</span>
        <div>
          <el-tag
            v-for="{ courseware_id, courseware_name, is_finished, group_id_selected_info } in courseware_list"
            :key="courseware_id"
            color="#fff"
            :title="courseware_name"
            @click="finishTask(courseware_id, is_finished, group_id_selected_info)"
          >
            <svg-icon icon-class="courseware" /> <span>{{ courseware_name }}</span>
            <svg-icon v-if="is_finished === 'true'" class="check-mark" icon-class="check-mark" />
          </el-tag>
        </div>
      </div>
      <div class="accessory-list">
        <span class="label">{{ $t('Key313') }}</span>
        <div>
          <el-tag v-for="item in accessory_list" :key="item.file_id" color="#fff" :title="item.file_name">
            <span @click="viewFile(item.file_name, item.file_id)">{{ item.file_name }}</span>
          </el-tag>
        </div>
      </div>
      <!-- 完成评价 -->
      <template v-if="my_execute_info.is_finished === 'true'">
        <div class="teacher-commenting">
          <div v-if="is_enable_homework" class="single-line">
            <span class="label">{{ $t('Key327') }}</span>
            <div>
              <el-tag
                v-for="item in my_execute_info.homework_list"
                :key="item.file_id"
                color="#fff"
                :title="item.file_name"
              >
                <span @click="viewFile(item.file_name, item.file_id)">{{ item.file_name }}</span>
              </el-tag>
            </div>
          </div>

          <template v-if="teaching_type === 10 && is_enable_KHPJ">
            <div class="single-line">
              <span class="label">{{ $t('Key316') }}</span>
              <el-input
                v-model="my_execute_info.student_remark"
                maxlength="3000"
                disabled
                type="textarea"
                resize="none"
                :rows="6"
              />
            </div>
            <div class="single-line">
              <span class="label">{{ $t('Key317') }}</span>
              <el-rate v-model="my_execute_info.student_score" disabled />
            </div>
          </template>

          <div v-if="is_enable_message" class="single-line">
            <span class="label">{{ $t('Key328') }}</span>
            <el-input
              v-model="my_execute_info.student_message"
              maxlength="3000"
              disabled
              type="textarea"
              resize="none"
              :rows="6"
            />
          </div>
          <div class="single-line">
            <span class="label">{{ $t('Key318') }}</span>
            <el-rate v-model="my_execute_info.teacher_score" disabled />
            <span class="teacher_remark">{{ my_execute_info.teacher_remark }}</span>
          </div>
        </div>
      </template>
      <!-- 直播评价 -->
      <template v-else-if="teaching_type === 10">
        <div class="live-info">
          <div class="single-line">
            <span class="enter-live" @click="enterLive"><svg-icon icon-class="video-red" /> {{ $t('Key329') }}</span>
          </div>
          <template v-if="is_enable_KHPJ">
            <div class="single-line">
              <span class="label">{{ $t('Key316') }}</span>
              <el-input v-model="student_remark" maxlength="3000" type="textarea" resize="none" :rows="6" />
            </div>
            <div class="single-line">
              <span class="label">{{ $t('Key317') }}</span>
              <el-rate v-model="student_score" />
            </div>
            <div class="confirm single-line">
              <el-button type="primary" @click="fillTaskExecuteInfo_Student_live">
                {{ $t('Key319') }}
              </el-button>
            </div>
          </template>
        </div>
      </template>
      <template v-else>
        <div v-if="is_enable_homework" class="submit-homework">
          <span class="label">{{ $t('Key330') }}</span>
          <el-upload action="no" :http-request="upload" multiple :show-file-list="false">
            <el-button><svg-icon icon-class="upload" /> {{ $t('Key152') }}</el-button>
          </el-upload>
        </div>
        <div class="file-list">
          <el-tag
            v-for="(item, i) in file_list"
            :key="item.file_id"
            color="#fff"
            closable
            :title="item.file_name"
            @close="deleteFile(i)"
          >
            <span>{{ item.file_name }}</span>
          </el-tag>
        </div>
        <div v-if="is_enable_message" class="leave-message">
          <span class="label">{{ $t('Key328') }}</span>
          <el-input v-model="student_message" maxlength="3000" type="textarea" resize="none" :rows="6" />
        </div>
        <div v-if="is_enable_homework || is_enable_message" class="submit-button">
          <el-button type="primary" @click="fillTaskExecuteInfo_Student">
            {{ $t('Key331') }}
          </el-button>
        </div>
      </template>
    </div>

    <CompletionView
      :task-id="id"
      :cur-student-id="$store.state.user.user_code"
      :cur-courseware-id="curCoursewareId"
      :dialog-visible="dialogVisible_completion"
      :preview-group-id="previewGroupId"
      @dialogClose="dialogClose_completion"
    />

    <FinishCourseware
      :id="id"
      :courseware-id="coursewareId"
      :preview-group-id="previewGroupId"
      :dialog-visible="dialogVisible"
      @dialogClose="dialogClose"
    />

    <ShowFile :visible="visible" :file-name="showCurFileName" :file-id="showCurFileId" @close="dialogShowFileClose" />
  </div>
</template>

<script>
export default {
  name: 'TaskDetailsStudent'
};
</script>

<script setup>
import { ref, computed, inject } from 'vue';
import { fileUpload, FileDownload } from '@/api/app';
import { CreateEnterLiveRoomSession } from '@/api/live';
import { GetTaskInfo, FillMyTaskExecuteInfo_Student } from '@/api/course';
import { isAllowFileType, fileTypeSizeLimit } from '@/utils/validate';
import { useRoute, useRouter } from 'vue-router/composables';
import { Message } from 'element-ui';

import TaskTop from '../TaskTop.vue';
import FinishCourseware from '@/components/course/FinishCourseware.vue';
import CompletionView from '@/components/course/CompletionView.vue';
import ShowFile from '@/common/show_file/index.vue';

const $t = inject('$t');
const route = useRoute();
const router = useRouter();
// 任务 ID
const id = route.params.id;
let itemInfo = ref({
  course_name: '',
  cs_item_name: '',
  cs_item_learning_material_list: [],
  time_space_view_txt: ''
});
let student_message = ref('');
let name = ref('');
let teaching_type = ref('');
let time_type = ref('');
let content = ref('');
let time_space_view_txt = ref('');
let courseware_list = ref([]);
let accessory_list = ref([]);
let file_list = ref([]);
let dialogVisible = ref(false);
let previewGroupId = ref('[]');
let coursewareId = ref('');
let curCoursewareId = ref('');
let dialogVisible_completion = ref(false);
let my_execute_info = ref({});
let student_remark = ref('');
let student_score = ref(0);
let loading = ref(true);
let visible = ref(false);
let showCurFileName = ref('');
let showCurFileId = ref('');
// 开启课后评价
let is_enable_KHPJ = ref(false);
let is_enable_homework = ref(false);
let is_enable_message = ref(false);

let timeType = computed(() => {
  let val = '';
  switch (time_type.value) {
    case 0:
      val = 'Key353';
      break;
    case 1:
      val = 'Key354';
      break;
    case 2:
      val = 'Key355';
      break;
    default:
      break;
  }
  return val;
});

let contentUrl = computed(() => {
  const con = content.value;
  if (!con) return '';
  return con.replace(
    new RegExp(/((https?:\/\/)?[\w-]+\.[\w-]+\.[\w-,@?^=%&:/~\\+#]+)/, 'g'),
    '<a href="$1" target="_blank">$1</a>'
  );
});

GetTaskInfo({
  id,
  is_contain_cs_item_learning_material: true,
  is_contain_my_execute_info: true
})
  .then(
    ({
      name: na,
      teaching_type: teachingType,
      time_type: timeType,
      course_name,
      cs_item_name,
      courseware_list: courseList,
      accessory_list: accList,
      cs_item_learning_material_list,
      content: con,
      time_space_view_txt: view_txt,
      my_execute_info: executeInfo,
      is_enable_KHPJ: isKHPJ,
      is_enable_homework: isHomework,
      is_enable_message: isMessage,
      cs_item_begin_time,
      cs_item_end_time
    }) => {
      itemInfo.value = {
        name,
        time_space_view_txt: view_txt,
        course_name,
        cs_item_name,
        cs_item_learning_material_list,
        content,
        cs_item_time: `${cs_item_begin_time} ~ ${cs_item_end_time}`
      };

      name.value = na;
      content.value = con;
      teaching_type.value = teachingType;
      time_type.value = timeType;
      courseware_list.value = courseList;
      accessory_list.value = accList;
      time_space_view_txt.value = view_txt;
      my_execute_info.value = executeInfo;
      is_enable_KHPJ.value = isKHPJ === 'true';
      is_enable_homework.value = isHomework === 'true';
      is_enable_message.value = isMessage === 'true';
    }
  )
  .finally(() => {
    loading.value = false;
  });

function upload(file) {
  const fileName = file.file.name;
  if (!isAllowFileType(fileName)) {
    Message.error(`【${fileName}】${$t('Key335')}`);
    return;
  }

  if (fileTypeSizeLimit(file.file.name, file.file.size)) {
    return Message.error(`${fileName}文件大小超出限制`);
  }

  fileUpload('Open', file).then(({ file_info_list }) => {
    if (file_info_list.length > 0) {
      const { file_id, file_name, file_url } = file_info_list[0];
      file_list.value.push({ file_id, file_name, file_url });
    }
  });
}

function deleteFile(i) {
  file_list.value.splice(i, 1);
}

function download(FileID) {
  FileDownload(FileID).then((data) => {
    console.log(data);
  });
}

function viewFile(fileName, fileId) {
  showCurFileName.value = fileName;
  showCurFileId.value = fileId;
  visible.value = true;
}

function dialogShowFileClose() {
  visible.value = false;
  showCurFileName.value = '';
  showCurFileId.value = '';
}

function fillTaskExecuteInfo_Student() {
  // 基础任务，必须提交作业
  if (my_execute_info.value.is_finished === 'false' && teaching_type.value === 12 && file_list.value.length <= 0) {
    return Message.error('请先提交作业');
  }

  const homework_file_id_list = [];
  file_list.value.forEach((item) => {
    homework_file_id_list.push(item.file_id);
  });
  FillMyTaskExecuteInfo_Student({
    task_id: id,
    homework_file_id_list,
    student_message: student_message.value,
    is_finished: true
  }).then(() => {
    Message.success($t('Key337'));
    router.go(0);
  });
}

function fillTaskExecuteInfo_Student_live() {
  FillMyTaskExecuteInfo_Student({
    task_id: id,
    is_finished: true,
    student_remark: student_remark.value,
    student_score: student_score.value
  }).then(() => {
    Message.success($t('Key336'));
    router.go(0);
  });
}

function enterLive() {
  CreateEnterLiveRoomSession({
    task_id: id
  }).then(({ live_room_sys_user_id, room_id, session_id, room_user_id }) => {
    router.push({
      path: `/live/student`,
      query: { live_room_sys_user_id, room_id, session_id, task_id: id, room_user_id }
    });
  });
}

// 完成任务
function finishTask(id, is_finished, group_id_selected_info) {
  if (my_execute_info.value.is_finished === 'true' && is_finished === 'false') {
    return Message.error($t('Key338'));
  }
  previewGroupId.value = group_id_selected_info ?? '[]';
  if (is_finished === 'true') {
    dialogVisible_completion.value = true;
    curCoursewareId.value = id;
  } else {
    dialogVisible.value = true;
    coursewareId.value = id;
  }
}

function dialogClose() {
  dialogVisible.value = false;
  coursewareId.value = '';
}

function dialogClose_completion() {
  dialogVisible_completion.value = false;
  curCoursewareId.value = '';
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin';

$bor-color: #d9d9d9;

.task-detail {
  @include container;

  min-height: calc(100vh - 130px);

  .el-tag {
    @include el-tag;

    margin: 0 8px 6px 0;
    border-color: $bor-color;
    border-radius: 4px;

    > span {
      cursor: pointer;
    }
  }

  &-main {
    padding: 24px 32px;
    margin-top: 16px;
    background-color: #fff;
    border-radius: 8px;

    .time-type {
      font-size: 20px;
      font-weight: 500;
    }

    .time-interval {
      padding: 16px 0;
      color: #737373;
    }

    %submit-homework,
    .submit-homework {
      display: flex;
      align-items: center;
      padding-top: 24px;
      border-top: 1px solid $bor-color;
    }

    %teacher-commenting,
    .teacher-commenting {
      @extend %submit-homework;

      flex-direction: column;

      > .single-line {
        display: flex;
        width: 100%;

        + div {
          margin-top: 24px;
        }

        .teacher_remark {
          margin-left: 24px;
        }
      }
    }

    .live-info {
      @extend %teacher-commenting;

      .enter-live {
        padding: 8px 26px;
        color: #ff6868;
        cursor: pointer;
        border: 1px solid #ff6868;
        border-radius: 20px;
      }

      .confirm {
        padding-left: 120px;
      }
    }

    .file-list {
      padding-left: 120px;
      margin-bottom: 16px;

      > .el-tag {
        padding: 0 10px;
        color: #409eff;
        border-color: #d9ecff;
      }
    }

    .leave-message {
      display: flex;
      align-items: flex-start;

      .label {
        margin-top: 8px;
      }
    }

    .task-courseware .el-tag {
      cursor: pointer;

      .svg-icon {
        margin-right: 8px;
        font-size: 18px;
      }

      .check-mark {
        position: relative;
        top: 2px;
        right: -20px;
        margin-left: 12px;
      }
    }

    .task-require,
    .task-courseware,
    .accessory-list,
    .submit-homework,
    .leave-message,
    .live-info,
    .teacher-commenting {
      display: flex;
      margin-bottom: 16px;

      .label {
        display: inline-block;
        width: 120px;
        min-width: 120px;
      }
    }

    .task-require {
      white-space: pre-wrap;

      :deep a {
        color: #18a0fb;
      }
    }

    .submit-button {
      padding-left: 120px;
    }
  }
}
</style>
