<template>
  <el-dialog
    :class="['cur-material', { 'align-left': !isAlignCenter }]"
    :visible="visible"
    :modal="false"
    width="900px"
    @close="dialogMaterialClose"
  >
    <div slot="title" class="dialog-header">
      <span class="dialog-header-title">
        {{
          isCurMaterial
            ? `当前推送资料 - ${material_name}`
            : `${$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 v-show="!isCurMaterial && material_type === 'COURSEWARE'" class="answer-data">
      <span>{{ $t('Key320') }}</span>
      <span class="answer-data-duration">{{ answerData.duration }}{{ $t('Key321') }}</span>
      <span class="answer-data-label">{{ $t('Key194') }}</span>
      <span class="answer-data-count-right">{{ answerData.count_right }}</span>
      <span class="answer-data-label">{{ $t('Key195') }}</span>
      <span class="answer-data-count-error">{{ answerData.count_error }}</span>
    </div>

    <template v-if="material_type === 'COURSEWARE' && visible">
      <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 ref="courseware" :context="context" @handleBookUserAnswer="handleBookUserAnswer" />
      </template>
      <template v-else-if="category === 'AILP'">
        <bookailp
          :context="context"
          :ui-type="ui_type"
          :preview-width="800"
          :preview-height="450"
          @handleBookUserAnswer="handleBookUserAnswer"
        />
      </template>
      <template v-else-if="category === 'NPC'">
        <booknpc v-if="context" ref="previewAnswer" :context="context" :theme-color="themeColor" />
      </template>
      <template v-if="category == 'NNPE'">
        <booknnpe v-if="context" :context="context" :theme-color="themeColor" />
      </template>
    </template>

    <template v-else>
      <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>
        <iframe
          :src="'https://view.officeapps.live.com/op/view.aspx?src=' + `${file_url_https}`"
          width="100%"
          height="490px"
          scrolling="no"
        />
      </template>
    </template>

    <div slot="footer">
      <el-button
        v-if="isCurMaterial || (!isFinished && material_type === 'COURSEWARE')"
        type="primary"
        @click="finishMyMaterial"
      >
        {{ $t('Key82') }}
      </el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  name: 'CurMaterial',
  components: {
    pdf
  },
  props: {
    taskId: {
      default: '',
      type: String
    },
    materialId: {
      default: '',
      type: String
    },
    materialType: {
      default: '',
      type: String
    },
    isFinished: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      visible: false,
      material_id: '',
      material_name: '',
      material_type: '',
      material_picture_url: '',
      context: null,
      exam_answer: '',
      ui_type: '',
      category: '',
      file_relative_path: '',
      file_url_https: '',
      pdfSrc: '',
      numPages: 1,
      curStudentID: '',
      bookAnswerContent: '',
      isAlignCenter: true,
      timer: null,
      isCurMaterial: true,
      answerData: {
        duration: 0,
        count_not_done: 0,
        count_right: 0,
        count_error: 0
      },
      text: '',
      themeColor: ''
    };
  },
  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: {
    visible(newVal) {
      if (newVal && !this.isCurMaterial) {
        this.getMaterialInfo();
      }

      if (!newVal) {
        this.context = null;
        this.exam_answer = '';
        this.file_relative_path = '';
        this.file_url_https = '';
        this.pdfSrc = '';
        this.numPages = 1;
        this.curStudentID = '';
        this.material_id = '';
        this.material_name = '';
        this.material_type = '';
        this.material_picture_url = '';
        this.text = '';
      }
    },

    material_id(newVal) {
      if (newVal.length === 0) return;
      if (this.material_type === 'COURSEWARE') {
        this.getCoursewareContent_View();
      } else {
        this.getFileStoreInfo();
      }
    }
  },
  created() {
    this.uploadBookWriteParent();
    this.getCurMaterialSent();

    this.updateWordPack({
      word_key_list: ['Key274', 'Key309', 'Key244', 'Key320', 'Key321', 'Key194', 'Key195', 'Key82', 'Key333', 'Key323']
    });
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    dialogShow() {
      this.isCurMaterial = false;
      this.visible = true;
    },

    dialogMaterialClose() {
      this.visible = false;
      if (!this.timer) this.getCurMaterialSent();
      this.$emit('dialogMaterialClose');
    },

    getCurMaterialSent() {
      this.timer = setInterval(() => {
        GetCurMaterialSent({ task_id: this.taskId }).then(
          ({ material_id, material_name, material_type, material_picture_url }) => {
            if (material_id !== undefined && material_id.length > 0) {
              this.visible = true;

              this.isCurMaterial = true;
              this.material_id = material_id;
              this.material_name = material_name;
              this.material_type = material_type;
              this.material_picture_url = material_picture_url;
              clearInterval(this.timer);
              this.timer = null;
              this.curStudentID = '-';
              this.$nextTick(() => {
                this.curStudentID = '';
              });
            }
          }
        );
      }, 2000);
    },

    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;
        }
      );
    },

    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.context = {
              id: this.material_id,
              ui_type: JSON.parse(content).question.ui_type,
              content: JSON.parse(content)
            };
            this.$nextTick(() => {
              this.$refs.courseware.handleAnswerTimeStart();
            });
            return;
          }
          if (category === 'AILP') {
            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.context = JSON.parse(content);
            return;
          }
          if (category === 'NNPE') {
            this.themeColor = book_theme_color;
            this.context = JSON.parse(content);
          }
        })
        .then(() => {
          if (this.isFinished && !this.isCurMaterial) {
            this.getStudentExamAnswer_FinishMaterial();
          }
        });
    },

    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();
          });
        }
      });
    },

    getStudentExamAnswer_FinishMaterial() {
      let student_id = this.$store.state.user.user_code;
      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.answerData = { duration, count_not_done, count_right, count_error };

        this.curStudentID = '';
        this.$nextTick(() => {
          this.curStudentID = student_id;
        });
      });
    },

    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);
          this.$message.error(this.$i18n.t('Key323'));
        });
    },

    handleBookUserAnswer(data) {
      this.exam_answer = data;
    },

    finishMyMaterial() {
      if (this.material_type === 'COURSEWARE' && this.exam_answer.length === 0 && this.sys_type === 'GCLS') {
        this.$message.warning(this.$i18n.t('Key333'));
        return;
      }
      const loading = this.$loading();
      FinishMyMaterial({
        task_id: this.taskId,
        material_id: this.material_id,
        material_type: this.material_type,
        exam_answer: this.exam_answer
      })
        .then(() => {
          this.$message.success('已完成');
          this.dialogMaterialClose();
        })
        .finally(() => {
          loading.close();
          this.exam_answer = '';
        });
    },

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

    /**
     * 课件方法
     */
    // 上传文件
    uploadBookWriteParent() {
      const { token, isHas } = getToken();
      let UserCode = isHas ? token.user_code : '';
      let UserType = isHas ? token.user_type : '';
      let SessionID = isHas ? token.session_id : '';
      this.bookuploadUrl = `${process.env.VUE_APP_BASE_API}/GCLSFileServer/WebFileUpload?UserCode=${UserCode}&UserType=${UserType}&SessionID=${SessionID}&SecurityLevel=Mid`;
    },

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

    // 成功后调用打包进度
    checkTaskProgress(taskId) {
      const { token, isHas } = getToken();
      let UserCode = isHas ? token.user_code : '';
      let UserType = isHas ? token.user_type : '';
      let SessionID = isHas ? token.session_id : '';

      let MethodName = 'file_store_manager-GetFileCompressTaskProgress';
      let data = {
        file_compress_task_id: taskId
      };
      getContentFile(MethodName, data).then(res => {
        if (res.is_finish === 'true') {
          clearInterval(this.bookDownTimer);
          window.open(
            `${process.env.VUE_APP_BASE_API}/GCLSFileServer/WebFileDownload?UserCode=${UserCode}&UserType=${UserType}&SessionID=${SessionID}&FileID=${res.compress_pack_file_id}`
          );
        }
      });
    }
  }
};
</script>

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

.cur-material {
  @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;
      }
    }
  }

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

    &-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;
    }
  }

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

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

  .text-file {
    height: calc(60vh - 50px);

    .el-textarea,
    textarea {
      height: 100%;
    }
  }

  .el-dialog__body {
    max-height: 60vh;

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