<template>
<div class="play-paper">
  <div class="play-paper-body">
    <div class="play-paper-title"><div><h3>{{chapterName}}</h3></div></div>
    <div class="play-paper-content play-chapter-work">
      <template v-if="chapterWork.questions && chapterWork.questions.length" >
        <ul>
          <template v-for="(item, index) in chapterWork.questions">
            <li v-bind:key="index">
              <div class="work-number">{{index + 1}}.</div>
              <div class="work-title">
                <div class="edit_html" v-html="item.question_content"></div>
              </div>
              <textarea id="editor-chapterWork"></textarea>
              <div style="height: 20px;"></div>
              <!-- <el-upload
                ref="upFile"
                class="upload-demo"
                action=""
                :multiple="false"
                :limit="1"
                :show-file-list="false"
                :on-change="handleChange"
                :http-request="uploadFile"
                :file-list="filesArr">
                请上传对应的文件附件：<el-button type="text">点击上传</el-button>
                <template v-if="successFileUrl">
                  {{successFileUrl.replace(/.*\/([^\/]*\.docx)$/gi, '$1')}}
                </template>
              </el-upload> -->
              <template v-if="successFileUrl">
                <a :href="successFileUrl">下载已上传文件</a>
              </template>
              <!-- <div style="height: 20px;"></div> -->
              <!-- <p class="help help-file">只支持docx格式的文件，文件小于10M</p> -->

              <!-- {answer.file_url && <a style={{display: 'block', marginBottom: '20px', color: 'blue'}} href={answer.file_url} >下载附件</a> } -->
          </li>
          </template>
        </ul>
      </template>
      <template v-else>
        <!-- <p class="no-data">暂无数据</p> -->
      </template>
      <!-- <p class="text-danger">{this.state.error}</p> -->
      <div class="area-btns">
        <el-button type="primary" @click="submitWork" :disabled="homeData.checker_time">{{homeData.checker_time ? '已批改' : '提交'}}</el-button>
        <span class="help-info">&emsp;&emsp;在获老师批改之前，可以多次提交，将以最后一次提交为准</span>
        <template v-if="homeData.checker_time">
          <div class="play-paper-check">
            <h4>已获批改 <small>批改于{{homeData.checker_time}}</small></h4>
            <div class="play-paper-check-item"><b>评分：</b>{{homeData.score}}</div>
            <div class="play-paper-check-item">
              <b>评语：</b>
              <div class="edit_html" v-html="homeData.check_comments"></div>
            </div>
          </div>
        </template>
        <template v-else-if="homeData.created_time">
          <p class="help">已于 {{homeData.created_time}} 提交，等待批改中</p>
        </template>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import cAction from '@actions'
import Base64 from 'Base64'

import CKEDITOR from 'CKEDITOR'

export default {
  props: {
    chapterId: { type: String, require: false },
    chapterWork: { type: Object, require: false },
    chapterName: { type: String, require: false },
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false }
  },
  data () {
    return {
      ckeditor: null,
      successFileUrl: '',
      filesArr: [],
      file: {
        id: 'WU_FILE_0',
        name: '',
        type: '',
        lastModifiedDate: '',
        size: '',
        file: ''
      },
      homeData: {},
      /* 设置是否可以初始化 ckeditor */
      setTime: null,
      isInit: false
    }
  },
  /* 本组件 仅支持 单个 ckeditor 存在 */
  mounted () {
    this.loadAjax()
  },
  updated () {},
  destroyed () {
    /* 清空 ckeditor 需要调用方法删除 并 在DOM结构中也移除 */
    this.ckeditor && this.ckeditor.destroy(true)
    this.ckeditor = null
  },
  methods: {
    handleChange (file, filelist) {
      this.file.name = file.raw.name
      this.file.type = file.raw.type
      this.file.lastModifiedDate = file.raw.lastModifiedDate
      this.file.size = file.raw.size
      this.file.file = file.raw
    },
    loadAjax () {
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.chapterAction.getHomework(this.sid, this.cid, this.id).then(data => {
        this.homeData = data
      }).catch(e => { this.filesArr.pop(); this.$message.error(e.message) }).finally(() => {
        this.setTime = setInterval(() => {
          if (document.querySelector('#editor-chapterWork')) {
            this.initckeditor()
            if (this.homeData.work_contents) {
              let json = JSON.parse(this.homeData.work_contents)
              if (json[0].is_encoded) {
                json[0].descreption = Base64.decode(json[0].descreption)
              }
              this.successFileUrl = json[0].file_url
              this.ckeditor.setData(json[0].descreption)
            } else {
              this.successFileUrl = ''
              this.ckeditor.setData('')
            }
            /* 滚动到头部 */
            document.querySelector('.play-paper').scrollTop = 0
            clearInterval(this.setTime)
          }
        }, 50)
        loading.close()
      })
    },
    submitWork () {
      if (!this.ckeditor.getData()) {
        this.$message.error('请填写内容')
        return
      }
      /* 只能提交 单个问题 */
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      let str = JSON.stringify([{
        question_id: this.chapterWork.questions[0].id,
        descreption: Base64.encode(this.ckeditor.getData()),
        file_url: this.successFileUrl,
        is_encoded: 1
      }])
      cAction.chapterAction.updateHomework({
        semester_id: this.sid,
        course_id: this.cid,
        chapter_id: this.chapterId,
        work_id: this.id,
        work_contents: str,
        duration: 30 + Math.floor(Math.random() * 1000)
      }).then(data => {
        if (data.status) {
          this.$message({ type: 'success', message: '提交成功，等待批改' })
          this.loadAjax()
        }
      }).catch(e => { this.filesArr.pop(); this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    uploadFile () {
      if (!/\.(docx)$/gi.test(this.file.name)) {
        this.$message.error('文件格式不对，请重新上传')
        this.filesArr.pop()
        return
      }
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.chapterAction.uploadFile(this.file).then(data => {
        this.successFileUrl = data.url
        this.filesArr.pop()
      }).catch(e => { this.filesArr.pop(); this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    /* 初始化 ckeditor */
    initckeditor () {
      !this.ckeditor && (this.ckeditor = CKEDITOR.replace('editor-chapterWork', {
        height: 300,
        uiColor: '#eeeeee',
        filebrowserImageUploadUrl: '/api/ckeditor/img/upload',
        // resize_enabled: typeof this.props.resizable === 'boolean' ? this.props.resizable : true,
        toolbar: [
          // { name: 'document', items: [ 'Source', '-', 'Save', 'NewPage', 'Preview' ] },
          { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
          { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
          { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
          // { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
          { name: 'editing', items: [ 'Find', 'Replace' ] },
          // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
          '/',
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
          { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] },
          { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
          { name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule' ] }
        ]
      }))
    }
  },
  watch: {
    id: {
      handler () {
        this.loadAjax()
      }
    }
  }
}
</script>
