<template>
<div class="play-paper">
  <div class="play-paper-body">
    <div class="play-paper-title"><div><h3>课程大作业</h3></div></div>
    <div class="play-paper-content">
      <div class="play-paper-step">&#9312; 阅读大作业要求</div>
      <div class="edit_html" v-html="courseWork.curriculum_essay || ''"></div>
      <p>截止日期：{{courseWork.essay_date || ''}}</p>
      <div class="play-paper-step">&#9313; 填写作业主题、正文，上传附件（点击“提交”保存）</div>
      <template v-if="courseWork.curriculum_name">
        <div style="font-size: 20px;">主题<em style="font-size: 12px;">（最长不超过50个字）</em></div>
        <el-input v-model="title" type="text" placeholder="主题" maxlength='100'></el-input>
        <div style="font-size: 20px;">正文</div>
        <textarea id="editor-courseWork"></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> } -->
      </template>
      <template v-else>
        <!-- <p class="no-data">暂无数据</p> -->
      </template>
      <!-- <p class="text-danger">{this.state.error}</p> -->
      <div class="area-btns">
        <div class="play-paper-step">&#9314; 截止日期前提交</div>
        <el-button type="primary" @click="submitWork" :disabled="homeData.check_date">{{homeData.check_date ? '已批改' : '提交'}}</el-button>
        <span class="help-info">&emsp;&emsp;在获老师批改之前，可以多次提交，将以最后一次提交为准</span>
        <template v-if="homeData.check_date">
          <div class="play-paper-check">
            <h4>已获批改 <small>批改于{{homeData.check_date}}</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" dangerouslySetInnerHTML={{__html:work.check_comments}}></div>
            </div> -->
          </div>
        </template>
        <template v-else-if="homeData.created_time">
          <p class="help">已于 {{homeData.created_time}} 提交，等待批改中</p>
          <template v-if="homeData.updated_time !== homeData.created_time">
            <p class="help">（最后一次提交时间： {{homeData.updated_time}}）</p>
          </template>
        </template>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import cAction from '@actions'

import CKEDITOR from 'CKEDITOR'

export default {
  props: {
    courseWork: { type: Object, require: false },
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false }
  },
  data () {
    return {
      ckeditor: null,
      successFileUrl: '',
      title: '',
      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.getCourseHomework(this.sid, this.cid).then(data => {
        this.homeData = data
      }).catch(e => { this.filesArr.pop(); this.$message.error(e.message) }).finally(() => {
        this.setTime = setInterval(() => {
          if (document.querySelector('#editor-courseWork')) {
            this.initckeditor()
            if (this.homeData.course_id) {
              let json = this.homeData
              this.successFileUrl = json.file_url
              this.ckeditor.setData(json.essay_description)
              this.title = json.essay_name
            }
            clearInterval(this.setTime)
          }
        }, 50)
        loading.close()
      })
    },
    submitWork () {
      if (!this.title) {
        this.$message.error('请输入主题')
        return
      }
      // if (!this.successFileUrl) {
      //   this.$message.error('请上传附件')
      //   return
      // }
      if (!this.ckeditor.getData()) {
        this.$message.error('请填写内容')
        return
      }
      /* 只能提交 单个问题 */
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.chapterAction.updateCourseHomework(this.sid, this.cid, {
        essay_name: this.title,
        essay_description: this.ckeditor.getData(),
        url: this.successFileUrl,
        course_id: this.cid,
        semester_id: this.sid
      }).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-courseWork', {
        height: 600,
        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' ] }
        ]
      }))
    }
  }
}
</script>
