<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')" />
        <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')" />
      </div>
      <div v-show="isStudent" class="answer-info">
        <span class="current-student-name">{{ curStudentName }}:</span>
        <template v-if="material_type === 'COURSEWARE'">
          <span>{{ $t('Key320') }}</span>
          <span class="answer-info-duration">{{ duration }}{{ $t('Key321') }}</span>
          <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 === 'OC' || category.length === 0">
          <bookreport
            v-if="isStudent"
            :context="context"
            :book-client-width="800"
            :book-answer-content="bookAnswerContent"
          />
          <bookquestion v-else :context="context" />
        </template>
        <template v-else-if="category === 'AILP'">
          <bookailp :context="context" :ui-type="ui_type" :preview-width="800" :preview-height="450" />
        </template>
        <template v-else-if="category === 'NPC'">
          <booknpc v-if="context" ref="previewAnswer" :theme-color="themeColor" :context="context" />
        </template>
        <template v-if="category == 'NNPE'">
          <booknnpe v-if="context" :context="context" :theme-color="themeColor" />
        </template>
      </template>
      <template v-else>
        <!-- pdf -->
        <template v-if="fileType === 'pdf'">
          <pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i" />
        </template>

        <template v-else-if="isImage(fileType)">
          <el-image fit="contain" :src="file_url_https" />
        </template>

        <div v-else-if="fileType === 'mp3'" class="audio-file">
          <audio :src="file_url_https" controls />
        </div>

        <div v-else-if="fileType === 'mp4'" class="video-file">
          <video :src="file_url_https" controls />
        </div>

        <div v-else-if="fileType === 'txt'" class="text-file">
          <el-input v-model="text" type="textarea" :readonly="true" resize="none" />
        </div>

        <template v-else-if="fileType !== 'pdf'">
          <iframe
            :src="'https://view.officeapps.live.com/op/view.aspx?src=' + `${file_url_https}`"
            width="100%"
            height="490px"
            scrolling="no"
          />
        </template>
      </template>
    </div>

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

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

export default {
  components: {
    pdf
  },
  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: '',
      context: null,
      ui_type: '',
      category: '',
      themeColor: '',
      dialogWidth: '900',
      bookAnswerContent: '',
      duration: 0,
      count_not_done: 0,
      count_right: 0,
      count_error: 0,
      file_relative_path: '',
      file_url_https: '',
      pdfSrc: '',
      numPages: 1,
      student_list: [],
      curStudentID: '',
      curStudentName: '',
      listTimer: null,
      marginLeft: 0,
      isAlignCenter: true,
      text: ''
    };
  },
  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.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();
        }
      }
    }
  },
  created() {
    this.updateWordPack({
      word_key_list: ['Key274', 'Key309', 'Key244', 'Key320', 'Key321', 'Key194', 'Key195']
    });
  },
  methods: {
    getCurMaterialSent() {
      GetCurMaterialSent({ task_id: this.taskId }).then(
        ({ material_id, material_name, material_type, material_picture_url }) => {
          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;
          }
        }
      );
    },

    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 }) => {
        if (!content) {
          this.context = null;
          return;
        }
        this.category = category;
        if (category === 'OC' || category.length === 0) {
          this.dialogWidth = '900';
          this.context = {
            id: this.material_id,
            ui_type: JSON.parse(content).question.ui_type,
            content: JSON.parse(content)
          };
          return;
        }
        if (category === 'AILP') {
          this.dialogWidth = '900';
          const contents = JSON.parse(content);
          if (contents.question && contents.question.length > 0) {
            this.context = JSON.parse(contents.question);
            this.ui_type = contents.ui_type ? contents.ui_type : '';
          }
          return;
        }
        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);
        }
      });
    },

    getFileStoreInfo() {
      GetFileStoreInfo({ file_id: this.material_id }).then(({ file_relative_path, file_url_https }) => {
        this.file_relative_path = file_relative_path;
        this.file_url_https = file_url_https;
        let fileType = file_url_https.slice(file_url_https.lastIndexOf('.') + 1, file_url_https.length);
        if (fileType === 'pdf') {
          this.getNumPages(file_relative_path);
        }

        if (fileType === 'txt') {
          fetch(`${process.env.VUE_APP_PDF}${file_relative_path}`).then(async res => {
            if (!res.ok) return;
            this.text = await res.text();
          });
        }
      });
    },

    getNumPages(url) {
      let loadingTask = pdf.createLoadingTask(`${process.env.VUE_APP_PDF}${url}`);
      loadingTask.promise
        .then(pdf => {
          this.pdfSrc = loadingTask;
          this.numPages = pdf.numPages;
        })
        .catch(err => {
          console.error('pdf加载失败', err);
        });
    },

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

    isImage(type) {
      return ['jpeg', 'gif', 'jpg', 'png', 'bmp', 'pic', 'svg'].includes(type);
    },

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

    listMove(direction) {
      let w = this.$refs.list.clientWidth - this.$refs.avatar.clientWidth;
      if (w > 60) {
        let 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.$nextTick(() => {
          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>
