<template>
  <div>
    <div class="con-title">{{ $t('pages.feedback.feedbackCreate.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="$t('pages.feedback.feedbackCreate.probDesc')" prop="name">
              <el-input v-model="setApply.name" :placeholder="$t('pages.feedback.feedbackCreate.enterDesc')" type="text" />
            </el-form-item>
            <div style="width: 100%; height: 10px;"></div>
            <div class="label" style="font-size: 14px; line-height: 2;">{{ $t('pages.feedback.feedbackCreate.problemDetails') }}</div>
            <textarea id="editor"></textarea>
            <div style="width: 100%; height: 10px;"></div>
            <el-form-item :label="$t('pages.feedback.feedbackCreate.uploadAtta')" 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">{{ $t('pages.feedback.feedbackCreate.btnUpload') }}</el-button>
                <div slot="tip" class="el-upload__tip">{{ $t('pages.feedback.feedbackCreate.limit') }}</div>
                <template v-if="successFileUrl">
                  {{successFileUrl.replace(/.*\/([^\/]*\.[^.]+)$/gi, '$1')}}
                </template>
              </el-upload>
              <template v-if="successFileUrl">
                <a :href="successFileUrl">{{ $t('pages.feedback.feedbackCreate.downloadButtonText') }}</a>
              </template>
            </el-form-item>
            <el-form-item :label="$t('pages.feedback.feedbackCreate.submitTo')" prop="type_id">
              <el-select v-model="value">
                <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">{{$t('pages.feedback.feedbackCreate.subBtn')}}</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import cAction from '@action'

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: this.$t('pages.feedback.feedbackCreate.all') },
        { value: '1', label: this.$t('pages.feedback.feedbackCreate.administration') },
        { value: '2', label: this.$t('pages.feedback.feedbackCreate.technology') }
      ],
      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.Other.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.Feedback.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/feedback/feedback-list' })
            }
          }).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>
