<template>
  <div class="app-container">
    <div class="title">公共内容<span>显示在所有商品详情</span></div>
    <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-width="80px" label-position="top">
      <el-form-item label="" prop="content">
        <el-upload
          ref="imageListUpload"
          class="avatar-uploader2"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          multiple
          name="file"
          :show-file-list="false"
          :on-success="uploadSuccess4"
          :on-error="uploadError4"
          :before-upload="beforeUpload4">
        </el-upload>
        <!--富文本编辑器组件-->
        <el-row v-loading="quillImgLoading">
          <quill-editor
            v-model="mainForm.content"
            ref="myQuillEditor"
            :options="editorOption">
          </quill-editor>
        </el-row>
      </el-form-item>
    </el-form>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="submitForm" :loading="formLoading">{{ formLoading ? '提交中 ...' : '提 交' }}</el-button>
        <el-popconfirm
          title="确定关闭吗？"
          @confirm="goBack"
          style="margin-left: 10px;"
        >
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>

  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getCommonModuleDetail, editCommonModule } from '@/api/goods'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{'header': 1}, {'header': 2}],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],
  [{'indent': '-1'}, {'indent': '+1'}],
  [{'direction': 'rtl'}],
  [{'size': ['small', false, 'large', 'huge']}],
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['link', 'image', 'video'],
  // ['clean']
]

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},

      mainForm: {
        content: '',
      },
      mainFormRules: {
        // content: [
        //   { required: true, message: '请输入公共内容', trigger: 'blur' }
        // ],
      },

      quillImgLoading: false, // 富文本上传图片loading
      editorOption: { // 富文本配置
        placeholder: '请输入公共内容',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.avatar-uploader2 input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      editorImages: [],

      formLoading: false,
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },

  created() {
    this.getCommonModuleDetail();
  },

  methods: {
    // 获取详情
    getCommonModuleDetail() {
      getCommonModuleDetail().then(res => {
        this.mainForm = {
          content: res.data.content,
        }
      })
    },

    submitForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          this.formLoading = true;

          editCommonModule({
            content: this.mainForm.content,
          }).then(res => {
            this.formLoading = false;
            this.$successMsg('编辑成功');
            setTimeout(()=>{
              this.goBack();
            }, 1000)
          }).catch(err => {
            this.formLoading = false;
          })

        }
      })
    },

    goBack() {
      this.$router.go(-1);
    },

    // 富文本图片上传前
    beforeUpload4() {
      this.quillImgLoading = true;
    },

    // 富文本图片上传成功
    uploadSuccess4(res, file, fileList) {
      console.log(fileList);
      fileList.forEach(item => {
        if(this.editorImages.indexOf(item.response.data.url) < 0) {
          this.editorImages.push(item.response.data.url);
        }
      })
      this.showImage()
      this.quillImgLoading = false;
    },

    showImage() {
      console.log(this.editorImages);
      let quill = this.$refs.myQuillEditor.quill;
      this.editorImages.forEach(item => {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        console.log(item);
        quill.insertEmbed(length, 'image', item);
        // this.$refs.imageListUpload.clearFiles()
        // 调整光标到最后
        quill.setSelection(length + 1);
      })
      this.editorImages = [];
      this.$refs.imageListUpload.clearFiles();
    },

    // 富文本图片上传失败
    uploadError4() {
      this.quillImgLoading = false;
      this.$errorMsg('图片插入失败');
    },
  }
}
</script>

<style lang="scss" scoped>
  .title {
    font-size: 16px;
    color: #333333;
    margin-bottom: 20px;
    span {
      font-size: 14px;
      color: #999999;
      margin-left: 10px;
    }
  }
</style>