<template>
  <div>
    <div class="con-title">系统反馈</div>
    <div class="con-box">
      <el-row type="flex" justify="center">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form ref="setApplyForm" :model="setApply" :rules="applyRules">
            <el-form-item label="问题描述" prop="name">
              <el-input v-model="setApply.name" placeholder="请输入问题描述" type="text" />
            </el-form-item>
            <div style="width: 100%; height: 10px;"></div>
            <div class="label" style="font-size: 14px; line-height: 2;">问题详情：</div>
            <textarea id="editor"></textarea>
            <div style="width: 100%; height: 10px;"></div>
            <el-form-item label="上传附件" prop="file">
              <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 size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">（可以上传 word、ppt、png、jpg、zip、rar等资源，多文件请先压缩打包成一个文件后，再上传）</div>
                <template v-if="successFileUrl">
                  {{successFileUrl.replace(/.*\/([^\/]*\.[^.]+)$/gi, '$1')}}
                </template>
              </el-upload>
              <template v-if="successFileUrl">
                <a :href="successFileUrl">下载已上传附件</a>
              </template>
            </el-form-item>
            <el-form-item label="提交给" prop="type_id">
              <el-select v-model="value" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onApplyFrom">提交</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import cAction from '@actions'

import CKEDITOR from 'CKEDITOR'

export default {
  components: {},
  data () {
    return {
      ckeditor: null,
      setApply: {
        name: '',
        content: ''
      },
      applyRules: {
        'name': [
          { required: true, message: '问题描述不能为空', trigger: 'blur' }
        ]
      },
      successFileUrl: '',
      filesArr: [],
      file: {
        id: 'WU_FILE_0',
        name: '',
        type: '',
        lastModifiedDate: '',
        size: '',
        file: ''
      },
      options: [
        { value: '0', label: '全部' },
        { value: '1', label: '教务' },
        { value: '2', label: '技术' }
      ],
      value: '2'
    }
  },
  mounted () {
    this.initckeditor()
  },
  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
    },
    uploadFile () {
      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() })
    },
    onApplyFrom () {
      this.$refs['setApplyForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
          cAction.scoreAction.feedbackCommit({
            title: this.setApply.name,
            contents: this.ckeditor.getData(),
            type_id: this.value,
            attachments: JSON.stringify([{
              name: this.file.name,
              url: this.successFileUrl
            }])
          }).then(data => {
            if (data.success) {
              this.$message({ type: 'success', message: '提交成功，等待反馈' })
              this.ckeditor.setData('')
              this.$refs['setApplyForm'].resetFields()
              this.$router.push({ path: '/app/account/feedbackList' })
            }
          }).catch(e => { this.filesArr.pop(); this.$message.error(e.message) }).finally(() => { loading.close() })
        } else {
          this.$message.error('请检查输入项，确认无误后，重新提交')
          return false
        }
      })
    },
    /* 初始化 ckeditor */
    initckeditor () {
      !this.ckeditor && (this.ckeditor = CKEDITOR.replace('editor', {
        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' ] }
        ]
      }))
    }
  }
}
</script>


<style lang="scss" scoped>
/* 申请 */
.el-date-editor.el-input {
  width: 100%;
}
.el-upload__tip {
  line-height: 1.5;
}
</style>
