<template>
  <el-dialog
    :class="['cur-material', { 'align-left': !isAlignCenter }]"
    :visible="dialogVisibleMaterial"
    :modal="false"
    width="900px"
    @close="dialogMaterialClose"
  >
    <div slot="title" class="dialog-header">
      <span class="dialog-header-title">当前推送资料</span>
      <span @click="isAlignCenter = !isAlignCenter">
        <svg-icon :icon-class="isAlignCenter ? 'align-left' : 'align-center'" />
      </span>
    </div>

    <div class="material-name">{{ materialName }}</div>

    <template v-if="materialType === 'COURSEWARE'">
      <bookquestion
        ref="courseware"
        :context="context"
        @handleBookUserAnswer="handleBookUserAnswer"
      />
    </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>

      <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 type="primary" @click="finishMyMaterial">完成</el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  components: {
    pdf
  },
  props: {
    dialogVisibleMaterial: {
      default: false,
      type: Boolean
    },
    taskId: {
      default: '',
      type: String
    },
    materialId: {
      default: '',
      type: String
    },
    materialName: {
      default: '',
      type: String
    },
    materialType: {
      default: '',
      type: String
    },
    materialPictureUrl: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      context: null,
      exam_answer: '',
      file_relative_path: '',
      file_url_https: '',
      pdfSrc: '',
      numPages: 1,
      isAlignCenter: true
    };
  },
  computed: {
    fileType() {
      return this.file_url_https.slice(
        this.file_url_https.lastIndexOf('.') + 1,
        this.file_url_https.length
      );
    }
  },
  watch: {
    dialogVisibleMaterial(newVal) {
      if (!newVal) {
        this.context = null;
        this.exam_answer = '';
        this.file_relative_path = '';
        this.file_url_https = '';
        this.pdfSrc = '';
        this.numPages = 1;
      }
    },
    materialId() {
      if (this.materialType === 'COURSEWARE') {
        this.getCoursewareContent_View();
      } else {
        this.getFileStoreInfo();
      }
    }
  },
  created() {
    this.uploadBookWriteParent();
  },
  methods: {
    dialogMaterialClose() {
      this.$emit('dialogMaterialClose');
    },

    getCoursewareContent_View() {
      GetCoursewareContent_View({ id: this.materialId }).then(({ content }) => {
        if (content) {
          this.context = {
            id: this.materialId,
            ui_type: JSON.parse(content).question.ui_type,
            content: JSON.parse(content)
          };
          this.$nextTick(() => {
            this.$refs.courseware.handleAnswerTimeStart();
          });
        } else {
          this.context = null;
        }
      });
    },

    getFileStoreInfo() {
      GetFileStoreInfo({ file_id: this.materialId }).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_url_https);
          }
        }
      );
    },

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

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

    finishMyMaterial() {
      if (this.materialType === 'COURSEWARE' && this.exam_answer.length === 0) {
        this.$message.warning('请完成课件');
        return;
      }
      const loading = this.$loading();
      FinishMyMaterial({
        task_id: this.taskId,
        material_id: this.materialId,
        material_type: this.materialType,
        exam_answer: this.exam_answer
      })
        .then(() => {
          this.$message.success('完成推送资料成功');
          this.$emit('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.scss';

.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-weight: bold;
        font-size: 18px;
        line-height: 24px;
      }

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

  .material-name {
    font-size: 16px;
    font-weight: 700;
    color: #000;
    margin-bottom: 16px;
  }
}
</style>
