<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').value = ''; // 清空是为了解决，连续上传同一张图片时，后续图片上传失效问题
                    document.querySelector('#file').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            },
            // 禁止粘贴图片
            clipboard: {
              matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
            }
          }
        },
        index: 0,
        indexall: 0,
      };
    },
    components: {},
    mounted() {
      this.$refs.myTextEditor.quill.enable(false);
      setTimeout(() => {
        this.$refs.myTextEditor.quill.enable(true)  //两秒后点击可获取焦点
      }, 1000)
      if( this.imgdata ) {
        this.goodsDeForm = this.imgdata;
      }
    },
    watch: {
      'goodsDeForm.description': {
        handler: function() {
          // console.log(99,this.goodsDetailsImgFileList);
          // console.log(100,this.goodsDeForm.description);
        },
        deep: true
      }
    },
    methods: {
      handleCustomMatcher(node, Delta) {
        let ops = []
        Delta.ops.forEach(op => {
          // 如果粘贴了图片，这里会是一个对象，所以可以这样处理
          if (op.insert && typeof op.insert === 'object' && op.insert.image.indexOf('base64') > -1) {
            ops.push({
              insert: ''
            })
            Delta.ops = ops;
          }
        })
        //
        return Delta
      },

      /** 初始化 商品详情 */
      initInfo() {
        this.goodsDeForm.description = '';
        this.goodsDetailsImgFileList = [];
      },
      // 通过原生 input上传 图片
      fileChange() {
        const list = this.$refs.file.files;
        this.indexall = list.length
        if (list.type !== "image/png" && list.type !== "image/jpg" && list.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持png/png格式',
            type: "warning"
          });
          return false;
        }
        let isImgSize = (list.size / 1024 ) > 500;
        if (isImgSize) {
          this.$message({
            message: '上传图片大小不能超过500k',
            type: "warning"
          });
          return false;
        }
        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}
          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){
                debugger
                this.uploadImgs()
              }else{
                this.index = 0
              }
            }else {
              this.$message({ message:'上传失败，请重新上传',type:'error'});
            }
            //this.loading = false;
          })
        });
      },
      //
      onEditorChange({editor, html, text}) {
        this.goodsDeForm.description = html;
        // if( this.goodsDeForm.description.indexOf('img') < -1 ) {
        //   this.goodsDetailsImgFileList = [];
        // }
      },
      //失去焦点事件
      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;
}

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

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

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


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