<template>
  <el-dialog
    :class="['complete-list', { 'align-left': !isAlignCenter }]"
    :visible="dialogVisibleComplete"
    :width="dialogWidth + 'px'"
    :modal="false"
    :close-on-click-modal="false"
    @close="dialogCompleteClose"
  >
    <div slot="title" class="dialog-header">
      <span class="dialog-header-title">
        {{ $t('Key274') }} - {{ material_type === 'COURSEWARE' ? $t('Key309') : $t('Key244') }} - {{ material_name }}
      </span>
      <span @click="isAlignCenter = !isAlignCenter">
        <svg-icon :icon-class="isAlignCenter ? 'align-left' : 'align-center'" />
      </span>
    </div>

    <div class="complete-list-top">
      <div class="student-list">
        <i class="el-icon-arrow-left" @click="listMove('left')"></i>
        <div ref="avatar" class="avatar-list">
          <div ref="list" class="avatar-list-wrapper" :style="{ 'margin-left': marginLeft + 'px' }">
            <span
              v-for="item in student_list"
              :key="item.student_id"
              :class="{ active: curStudentID === item.student_id }"
            >
              <el-avatar
                icon="el-icon-user"
                :src="item.student_image_url"
                @click.native="getStudentExamAnswer_FinishMaterial(item.student_id, item.student_name)"
              />
            </span>
          </div>
        </div>
        <i class="el-icon-arrow-right" @click="listMove('right')"></i>
      </div>
      <div v-show="isStudent" class="answer-info">
        <span class="current-student-name">{{ curStudentName }}:</span>
        <template v-if="material_type === 'COURSEWARE'">
          <template v-if="category !== 'NPC'">
            <span>{{ $t('Key320') }}</span>
            <span class="answer-info-duration">{{ duration }}{{ $t('Key321') }}</span>
          </template>
          <span class="answer-info-label">{{ $t('Key194') }}</span>
          <span class="answer-info-count-right">{{ count_right }}</span>
          <span class="answer-info-label">{{ $t('Key195') }}</span>
          <span class="answer-info-count-error">{{ count_error }}</span>
        </template>
      </div>
    </div>

    <div class="complete-list-container">
      <template v-if="material_type === 'COURSEWARE'">
        <template v-if="category === 'NPC'">
          <booknpc
            v-if="context && refresh"
            task-model="ANSWER"
            :is-show-save="false"
            :book-answer-content="bookAnswerContent"
            :context="context"
            :theme-color="themeColor"
            :preview-type="previewType"
            :preview-group-id="courseware_group_id_selected_info"
            :current-tree-i-d="material_id"
            :submit-cn="$store.getters.submitCn"
          />
        </template>
        <template v-if="category === 'NNPE'">
          <booknnpe
            v-if="context && refresh"
            :context="context"
            :theme-color="themeColor"
            :is-show-title="true"
            task-model="ANSWER"
            :is-show-save="false"
            :book-answer-content="bookAnswerContent"
            :preview-type="previewType"
            :preview-group-id="courseware_group_id_selected_info"
            :current-tree-i-d="material_id"
          />
        </template>
        <template v-if="category === 'RLC'">
          <bookrlc
            v-if="context"
            :context="context"
            :theme-color="themeColor"
            :book-font-size="bookFontSize"
            :current-tree-i-d="material_id"
            :preview-type="previewType"
            :preview-group-id="courseware_group_id_selected_info"
            :is-show-title="false"
            task-model="ANSWER"
            :is-show-save="false"
            :book-answer-content="bookAnswerContent"
          />
        </template>
        <template v-if="category === 'NEW'">
          <BookNew
            v-if="context"
            ref="book"
            :context="context"
            :current-tree-i-d="material_id"
            task-model="ANSWER"
            :is-show-save="false"
            :book-answer-content="bookAnswerContent"
          />
        </template>
      </template>
      <template v-else>
        <div v-loading="file_loading">
          <iframe
            v-if="fileUrl.length > 0"
            id="iframe"
            :src="`${$store.state.app.config.doc_preview_service_address}/onlinePreview?url=${fileUrl}`"
            width="100%"
            height="540px"
          ></iframe>
        </div>
      </template>
    </div>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import { GetCurMaterialSent, GetStudentList_FinishMaterial, GetStudentExamAnswer_FinishMaterial } from '@/api/live';
import { GetCoursewareContent_View, GetMaterialInfo } from '@/api/course';
import { GetFileStoreInfo, getContentFile } from '@/api/app';
import { encode } from 'js-base64';

export default {
  props: {
    dialogVisibleComplete: {
      default: false,
      type: Boolean
    },
    taskId: {
      default: '',
      type: String
    },
    materialId: {
      default: '',
      type: String
    },
    materialType: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      material_id: '',
      material_name: '',
      material_type: '',
      material_picture_url: '',
      previewType: 'previewCheckShow',
      courseware_group_id_selected_info: '[]',
      context: null,
      category: '',
      themeColor: '',
      bookFontSize: '',
      dialogWidth: '900',
      bookAnswerContent: '',
      duration: 0,
      count_not_done: 0,
      count_right: 0,
      count_error: 0,
      file_loading: false,
      fileUrl: '',
      file_url_https: '',
      student_list: [],
      curStudentID: '',
      curStudentName: '',
      listTimer: null,
      marginLeft: 0,
      isAlignCenter: true,
      text: '',
      refresh: true
    };
  },
  computed: {
    fileType() {
      return this.file_url_https.slice(this.file_url_https.lastIndexOf('.') + 1, this.file_url_https.length);
    },
    isStudent() {
      return this.curStudentID.length > 0;
    }
  },
  watch: {
    dialogVisibleComplete(newVal) {
      if (newVal && this.materialId.length === 0) {
        this.getCurMaterialSent();
      }

      if (newVal && this.materialId.length > 0) {
        this.getMaterialInfo();
      }

      // 对话框，关闭时清理
      if (!newVal) {
        clearInterval(this.listTimer);
        this.material_id = '';
        this.fileUrl = '';
        this.material_name = '';
        this.student_list = [];
        this.marginLeft = 0;
        this.context = null;
        this.curStudentID = '';
        this.bookAnswerContent = '';
        this.text = '';
      }
    },

    material_id(newVal) {
      if (newVal) {
        this.listTimer = setInterval(() => {
          this.getStudentList_FinishMaterial();
        }, 3000);

        if (this.material_type === 'COURSEWARE') {
          this.getCoursewareContent_View();
        } else {
          this.getFileStoreInfo();
        }
      }
    }
  },
  methods: {
    getCurMaterialSent() {
      GetCurMaterialSent({ task_id: this.taskId }).then(
        ({ material_id, material_name, material_type, material_picture_url, courseware_group_id_selected_info }) => {
          if (material_id !== undefined && material_id.length > 0) {
            this.material_id = material_id;
            this.material_name = material_name;
            this.material_type = material_type;
            this.material_picture_url = material_picture_url;
            this.courseware_group_id_selected_info =
              courseware_group_id_selected_info.length <= 0 ? '[]' : courseware_group_id_selected_info;
          }
        }
      );
    },

    getMaterialInfo() {
      GetMaterialInfo({ task_id: this.taskId, material_id: this.materialId, material_type: this.materialType }).then(
        ({ material_id, material_name, material_type }) => {
          this.material_id = material_id;
          this.material_name = material_name;
          this.material_type = material_type;
        }
      );
    },

    getStudentList_FinishMaterial() {
      GetStudentList_FinishMaterial({
        task_id: this.taskId,
        material_id: this.material_id,
        material_type: this.material_type
      })
        .then(({ student_list }) => {
          this.student_list = student_list;
        })
        .catch(() => {
          clearInterval(this.listTimer);
        });
    },

    getCoursewareContent_View() {
      GetCoursewareContent_View({ id: this.material_id }).then(
        ({ content, category, book_theme_color, book_font_size }) => {
          if (!content) {
            this.context = null;
            return;
          }
          this.category = category;

          if (category === 'OC' || category.length === 0 || category === 'AILP') {
            return this.$message.warning('该课件类型已被废弃');
          }
          if (category === 'NPC') {
            this.themeColor = book_theme_color;
            this.dialogWidth = '920';
            this.context = JSON.parse(content);
            return;
          }
          if (category === 'NNPE') {
            this.dialogWidth = '920';
            this.themeColor = book_theme_color;
            this.context = JSON.parse(content);
            return;
          }

          if (category === 'RLC') {
            this.dialogWidth = '920';
            this.themeColor = book_theme_color;
            this.bookFontSize = book_font_size;
            this.context = JSON.parse(content);
            return;
          }

          if (category === 'NEW') {
            this.context = JSON.parse(content);
            return;
          }
        }
      );
    },

    getFileStoreInfo() {
      GetFileStoreInfo({ file_id: this.material_id }).then(({ file_url_https }) => {
        this.file_url_https = file_url_https;
        this.fileUrl = encodeURIComponent(encode(file_url_https));
        this.file_loading = true;
        this.$nextTick(() => {
          document.getElementById('iframe').onload = () => {
            this.file_loading = false;
          };
        });
      });
    },

    dialogCompleteClose() {
      this.$emit('dialogCompleteClose');
    },

    // 下载文件zip
    downloadBookWriteParent(idList) {
      getContentFile('file_store_manager-StartCreateFileCompressPack', {
        file_id_list: JSON.parse(idList)
      }).then((res) => {
        const id = res.file_compress_task_id;
        this.bookDownTimer = setInterval(() => {
          this.checkTaskProgress(id);
        }, 2000);
      });
    },

    listMove(direction) {
      const w = this.$refs.list.clientWidth - this.$refs.avatar.clientWidth;
      if (w > 60) {
        const left = Number(this.$refs.list.style['margin-left'].slice(0, -2));
        let width = direction === 'right' ? left - 60 : left + 60;
        if (Math.abs(width) > w) width = -w;
        this.marginLeft = width > 0 ? 0 : width;
      }
    },

    getStudentExamAnswer_FinishMaterial(student_id, student_name) {
      GetStudentExamAnswer_FinishMaterial({
        task_id: this.taskId,
        material_id: this.material_id,
        material_type: this.material_type,
        student_id
      }).then(({ content, duration, count_not_done, count_right, count_error }) => {
        this.bookAnswerContent = content;
        this.duration = duration;
        this.count_not_done = count_not_done;
        this.count_right = count_right;
        this.count_error = count_error;

        this.curStudentID = '';
        this.refresh = false;
        this.$nextTick(() => {
          this.refresh = true;
          this.curStudentID = student_id;
        });
        this.curStudentName = student_name;
      });
    }
  }
};
</script>

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

.complete-list {
  @include dialog;

  &.align-left {
    .el-dialog {
      margin-left: 20px;
    }
  }

  .el-dialog__header {
    .dialog-header {
      display: flex;
      justify-content: space-between;
      padding-right: 24px;

      &-title {
        font-size: 18px;
        font-weight: bold;
        line-height: 24px;
      }

      .svg-icon {
        cursor: pointer;
      }
    }
  }

  &-top {
    .student-list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 66px;
      margin-bottom: 12px;
      overflow: hidden;

      .avatar-list {
        width: calc(100% - 48px);
        height: 100%;
        overflow: hidden;

        &-wrapper {
          display: inline-block;
          white-space: nowrap;

          .active {
            position: relative;
            display: inline-block;
            width: 58px;

            &::after {
              position: absolute;
              top: 58px;
              left: 24px;
              display: inline-block;
              width: 8px;
              height: 8px;
              content: '';
              background-color: #2ece5b;
              border-radius: 50%;
            }
          }

          .el-avatar {
            margin: 0 9px;
            cursor: pointer;
          }
        }
      }

      > i {
        margin-top: -24px;
        font-size: 18px;
        cursor: pointer;
      }
    }

    .answer-info {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      font-size: 16px;

      .current-student-name {
        margin-right: 24px;
        font-weight: 700;
      }

      &-label {
        margin-left: 24px;
      }

      &-duration,
      &-count-right,
      &-count-error {
        min-width: 60px;
        padding: 0 24px;
        text-align: center;
        border-right: 2px solid #dfdfdf;
      }

      &-count-error {
        border-right-width: 0;
      }
    }
  }

  &-container {
    max-height: calc(55vh - 117px);
    overflow: auto;

    .el-image {
      width: 100%;
      height: calc(100% - 4px);
    }

    .audio-file {
      display: flex;
      justify-content: center;
    }

    .video-file {
      display: flex;
      justify-content: center;
      height: 100%;
    }

    .text-file {
      height: calc(55vh - 117px);

      .el-textarea,
      textarea {
        height: 100%;
      }
    }
  }
}
</style>
