<template>
  <div class="goods-img">
    <el-form ref="goodsDeForm" :model="goodsDeForm" label-width="150px" size="small">
      <el-form-item label="商品详情：" prop="description">
        <span class="tip-span  up-img-tip" style="display: block;line-height: 34px;">上传图片详情，用于商品详情页展示</span>
        <el-upload
          class="avatar-uploader2"
          action="#"
          name="file"
          auto-upload
          :show-file-list="false"
          multiple
          :file-list="goodsDetailsImgFileList"
        ><i class="el-icon-plus" />
        </el-upload>
        <input class="uploadImg"  style="display: none;" type="file" ref="file" accept="image/*"  @change="fileChange($event)" name="file" multiple id="file">
        <quill-editor class="quill-editor-class" ref="myTextEditor" v-model="goodsDeForm.description" :options="editorOption" @change="onEditorChange" style="height:500px;margin-bottom:20px;"></quill-editor>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {UploadImg} from '@/api/module/goods'
  // 工具栏配置
  const toolbarOptions = [ ['image'] ];
  export default {
    name: "Goodsimg",
    props: {
      imgdata: {
        type: Object,
        required: true
      }
    },
    data() {
      // let checkImg = (rule, value, callback) => {
      //   if (this.goodsDetailsImgFileList.length < 1) {
      //     callback(new Error("请上传商品详情的图片"));
      //   } else {
      //     callback();
      //   }
      // };
      return {
        loading: false,
        goodsDeForm: {
          description: '',

        },
        // goodsDeRules: {
        //   description:[{required: true, message: '请上传商品详情图片', validator: checkImg}]
        // },

        goodsDetailsImgFileList: [],
        editorOption: {
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            toolbar: {
              container: toolbarOptions,  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector('#file').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            },
            // 禁止粘贴图片
            clipboard: {
              matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
            }
          }
        },
        index: 0,
        indexall: 0,
      };
    },
    components: {},
    mounted() {
      this.goodsDeForm = this.imgdata;
      //console.log("详情：",this.imgdata);
    },
    watch: {},
    methods: {
      handleCustomMatcher(node, Delta) {
        let ops = []
        //debugger
        console.log(123);
        Delta.ops.forEach(op => {
          if (op.insert && typeof op.insert === 'string') {// 如果粘贴了图片，这里会是一个对象，所以可以这样处理
            ops.push({
              insert: op.insert,
            })
          }
        })
        Delta.ops = ops
        return Delta
      },

      /** 初始化 商品详情 */
      initInfo() {
        this.goodsDeForm.description = '';
        this.goodsDetailsImgFileList = [];
      },
      // 通过原生 input上传 图片
      fileChange() {
        const list = this.$refs.file.files;
        this.indexall = list.length
        this.uploadImgs()
      },
      // 向后台 传输 base64的图片数据
      uploadImgs() {
        this.getBase64(this.$refs.file.files[this.index]).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data": this.Base64img}
          //debugger
         // this.loading = true;
          UploadImg(data).then(res => {
            //debugger
            if (res && res.code === 1) {
              this.index++;
              this.goodsDetailsImgFileList.push({'url': res.data.image_url});
              this.$message({ message:'上传成功',type:'success'});
              // 获取富文本组件实例
              let quill = this.$refs.myTextEditor.quill;
              let length = quill.getSelection().index;
              // 插入图片  res.data.url为服务器返回的图片地址
              quill.insertEmbed(length, 'image', res.data.image_url)
              // 调整光标到最后
              quill.setSelection(length + 1)
              if(this.index < this.indexall){
                this.uploadImgs()
              }else{
                this.index = 0
              }
            }else {
              this.$message({ message:'上传失败，请重新上传',type:'error'});
            }
            //this.loading = false;
          })
        });
      },
      //
      onEditorChange({editor, html, text}) {
        this.goodsDeForm.description = html;
      },

      onEditorBlur(){//失去焦点事件

      },

      // 商品详情 子组件 form表单校验, 在父组件中被调用
      // validateGoodsDeImgForm() {
      //   let flag = null
      //   this.$refs['goodsDeForm'].validate(valid => {
      //     if (valid) {
      //       flag = true
      //     } else {
      //       flag = false
      //     }
      //   })
      //   return flag
      // },
      // -------------------------通用
      // 图片转换为 base64
      getBase64(file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function () {
            imgResult = reader.result;
          };
          reader.onerror = function (error) {
            reject(error);
          };
          reader.onloadend = function () {
            resolve(imgResult);
          };
        });
      },
    },
  };
</script>
<style lang="scss" type="text/stylus" scoped>
.goods-img {
  padding: 20px;
}
.avatar-uploader2 {
  display : none;
}
.quill-editor-class {
  position: relative;
}
.up-img-tip {
  position: absolute;
  top: 0;
  left: 60px;
}

/deep/.ql-toolbar.ql-snow {
  border: none;
  border-bottom: 1px solid #ccc;
  padding: 5px 8px;
}

/deep/.ql-toolbar.ql-snow .ql-formats {
  vertical-align : baseline;
  margin: 0;
  padding: 0 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

/deep/.ql-toolbar.ql-snow .ql-formats:hover {
  background-color : #00afff;
  border-color: #00afff;
}


/* 一般提示性文字 */
.tip-span {
  color: #909399;
  font-size: 12px;
}
</style>
