<template>
  <el-dialog
    :title="!dataForm.productId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="handlereset"
    lock-scroll
    width="750px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="100px"
    >
      <el-form-item label="商品类型" prop="goodsType">
        <el-select v-model="dataForm.goodsType" placeholder="请选择">
          <el-option
            v-for="item in goodsTypeList"
            :key="item.dictType"
            :label="item.dictValue"
            :value="item.dictType"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="dataForm.productName"
          placeholder="商品名称"
        ></el-input>
      </el-form-item>

      <!-- 关联的图书ids -->

      <el-form-item label="商品图" prop="productImages">
        <el-upload
          :limit="dataForm.limitCountImg"
          class="el-uploadfeng "
          :class="{
            uoloadSty: dataForm.showBtnDealImg,
            disUoloadSty: dataForm.noneBtnImg
          }"
          :action="baseUrl + '/oss/fileoss'"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :file-list="fileList"
          :on-success="handlePicSuccess"
          accept=".jpeg,.jpg,.gif,.png"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.productImages" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="商品轮播图" prop="productImageList">
        <el-upload
          :limit="5"
          class="el-uploadfeng noneBtnImg"
          :class="{
            uoloadSty: dataForm.showBtnDealImg,
            disUoloadSty: dataForm.noneBtnImg
          }"
          :action="baseUrl + '/oss/fileoss'"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :file-list="swiperfileList"
          :on-success="bannerHandlePicSuccess"
          accept=".jpeg,.jpg,.gif,.png"
          :on-remove="bannerHandleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!-- <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
            <img width="100%" :src="dataForm.productImageList" alt="">
          </el-dialog> -->
        <span
          >图片尺寸：600*600px，支持图片类型：.jpeg,.jpg,.gif,.png，
          最多上传5张图片</span
        >
      </el-form-item>
      <div>
        <el-form-item
          label="商品价格"
          prop="price"
          style="width: 50%; float: left;"
        >
          <el-input v-model="dataForm.price" placeholder="活动价"></el-input>
        </el-form-item>
        <el-form-item
          label="活动价"
          prop="hDprice"
          style="width: 50%; float: left;"
        >
          <el-input
            v-model="dataForm.hDprice"
            placeholder="商品价格"
          ></el-input>
          <span style="color: #999;">值为0或者不填，则没有活动价格</span>
        </el-form-item>
        <el-form-item
          label="商品重量"
          prop="weight"
          style="width: 50%; float: right;"
        >
          <el-input
            style="width: 80%;"
            v-model="dataForm.weight"
            placeholder="商品重量"
          ></el-input
          ><span style="display: inline-block; float: right; width: 10%;"
            >克</span
          >
        </el-form-item>
        <el-form-item
          label="商品库存"
          prop="productStock"
          style="width: 50%; float: right;"
        >
          <el-input
            v-model="dataForm.productStock"
            placeholder="商品库存"
            :disabled="dataForm.goodsType !== '05'"
          ></el-input>
        </el-form-item>
      </div>
      <!-- <el-form-item label="上架状态" prop="publishStatus">
          <el-input v-model="dataForm.publishStatus" placeholder="上架状态"></el-input>
        </el-form-item> -->
      <!-- <div>
        <el-form-item label="出版社" prop="publisher" style="width: 50%; float: left;">
          <el-input placeholder="出版社" v-model="dataForm.publisher"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" style="width: 50%; float: right;">
          <el-input placeholder="作者" v-model="dataForm.author"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="出版时间" prop="pubDate" style="width: 50%; float: left;">
          <el-date-picker @change="changeTime" format="yyyy 年 MM 月 dd 日" v-model="dataForm.pubDate" type="date"
            placeholder="选择日期时间">
          </el-date-picker>
         
        </el-form-item>
        <el-form-item label="页数" prop="pageNum" style="width: 50%; float: right;">
          <el-input placeholder="页数" v-model="dataForm.pageNum"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="内文用纸材质" prop="quality" style="width: 50%; float: left;">
          <el-input v-model="dataForm.quality" placeholder="内文用纸材质"></el-input>
        </el-form-item>
        <el-form-item label="开本" prop="format" style="width: 50%; float: right;">
          <el-input v-model="dataForm.format" placeholder="16开或其他规格"></el-input>
        </el-form-item>
      </div> -->
      <!-- 关联的图书ids -->
      <!-- <div style="clear: both;">
        <el-form-item label="关联图书" prop="Books">
          
        </el-form-item>
      </div> -->
      <div style="clear: both;">
        <el-form-item label="是否包邮" prop="isFreeMail">
          <el-radio-group v-model="dataForm.isFreeMail">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="VIP优惠图书" prop="isVipPrice">
          <el-radio-group v-model="dataForm.isVipPrice">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付商户" prop="payMerchant">
          <el-radio-group v-model="dataForm.payMerchant">
            <el-radio :label="0">众妙之门</el-radio>
            <el-radio :label="1">灵枢教育科技</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <el-form-item label="商品详情" prop="productDetails">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/oss/fileoss'"
          accept=".jpeg,.jpg,.gif,.png"
          :show-file-list="false"
          :on-success="contentUploadSuccess"
        >
        </el-upload>
        <quill-editor
          v-loading="uploadLoading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          v-model="dataForm.productDetails"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @ready="onEditorReady($event)"
          class="shangpin_editor"
        >
        </quill-editor>
      </el-form-item>
      <!-- <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import global from "../../common/common.vue"; //引入共用组间
import axios from "axios";
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: [
        "SimSun",
        "SimHei",
        "Microsoft-YaHei",
        "KaiTi",
        "FangSong",
        "Arial"
      ]
    }
  ], // 字体
  [{ align: [] }], // 居中
  ["clean"], // 清除样式,
  ["link", "image"] // 上传图片、上传视频
];

export default {
  data() {
    return {
      quillEditorIndex: 0,
      uploadLoading: false,
      pointMemery: [], // 花生币操作记录
      baseUrl: global.baseUrl,
      goodsTypeList: [],
      visible: false,
      categorys: [],
      fileList: [], // 封面图
      swiperfileList: [],
      dialogVisible: false,
      props: {
        value: "catId",
        label: "name",
        children: "children",
        checkStrictly: true
      },
      dataForm: {
        tags: [], // 商品标签
        hDprice: 0, // 活动价
        productId: 0,
        limitCountImg: 1, // 图片数量
        productImageList: "", // 轮播图
        showBtnDealImg: true,
        noneBtnImg: false,
        productName: "",
        productStock: null, // 商品库存
        price: "",
        author: "",
        publisher: "",
        weight: "",
        pubDate: "",
        // format: '', // 开本
        isFreeMail: 1, // 是否包邮
        isVipPrice: 1,  //是否vip
        payMerchant: 0, // 支付商户
        // pageNum: '',
        // quality: '', // 内文用纸
        isNew: 0,
        sumSales: null, // 总销量
        publishStatus: "",
        productPid: "",
        productImages: "",
        createTime: "",
        updateTime: "",
        delFlag: "",
        sort: "",
        goodsType: "", // 商品类型
        poids: [],

        Books: [] // 关联的图书
      },
      bookidsd: [],
      dataRule: {
        productName: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "商品价格不能为空",
            trigger: "blur"
          }
        ],
        weight: [
          {
            required: true,
            message: "商品重量不能为空",
            trigger: "blur"
          }
        ],
        goodsType: [
          {
            required: true,
            message: "商品类型不能为空",
            trigger: "blur"
          }
        ],
        poids: [
          {
            required: true,
            message: "商品父id不能为空",
            trigger: "blur"
          }
        ],
        productImages: [
          {
            required: true,
            message: "商品图不能为空",
            trigger: "blur"
          }
        ],
        // productDetails: [{
        //   required: true,
        //   message: '商品详情不能为空',
        //   trigger: 'blur'
        // }],
        productStock: [
          {
            required: true,
            message: "商品库存不能为空",
            trigger: "blur"
          }
        ]
        // updateTime: [
        //   { required: true, message: '更新时间不能为空', trigger: 'blur' }
        // ],
        // delFlag: [
        //   { required: true, message: '删除标记不能为空', trigger: 'blur' }
        // ],
        // sort: [
        //   { required: true, message: '排序不能为空', trigger: 'blur' }
        // ]
      },
      urlList: {
        edit: "/master/shopProduct/editProductDetail",
        add: "/master/shopProduct/addProduct"
      },
      // 富文本编辑器配置
      editorOption: {
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          clipboard: {
            matchers: [["img", this.handlePasteImg]]
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                console.log("value at line 365:", value);
                if (value) {
                  this.uploadLoading = true;
                  // 调用element的图片上传组件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        },
        placeholder: "请输入正文"
      },
      tagList: []
    };
  },
  created() {
    this.getTreeList();
    this.getTags();
  },
  methods: {
    handlePasteImg(node, delta) {
      this.uploadLoading = true;
      var that = this;
      let ops = [];
      delta.ops.forEach(async (op, index) => {
        if (op.insert && typeof op.insert !== "string") {
          // 如果粘贴了图片，这里会是一个对象
          if (op.insert.image) {
            if (op.insert.image.includes(";base64")) {
              let file = that.dataURLtoFile(
                op.insert.image,
                `paste-${Math.random()
                  .toString(36)
                  .slice(-8)}.jpg`
              );
              console.log("file at line 397:", file);
              // key 值可以自己用当前日期生成
              let key = `detail/${new Date().getTime()}${Math.random()
                .toString(36)
                .slice(-8)}.jpg`;
              let formdata = new FormData();
              formdata.append("file", file);
              formdata.append("fileName", key);
              formdata.append("key", key);
              console.log("🚀 ~ handleRequest ~ formdata:", formdata);

              axios
                .post(this.baseUrl + "/oss/fileoss", formdata)
                .then(res => {
                  console.log("🚀 ~ this.$axios.post ~ res111:", res);
                  if (res.data.code == 0) {
                    // 如果上传成功
                    if (res.data.url) {
                      // 获取光标所在位置
                      var quill = that.$refs.myQuillEditor.quill;
                      var length = this.quillEditorIndex;

                      console.log("length at line 397:", length);

                      // 插入图片，res为服务器返回的图片链接地址
                      quill.insertEmbed(length, "image", res.data.url);
                      // 调整光标到最后
                      quill.setSelection(length + 1);
                      this.uploadLoading = false;
                    } else {
                      // 提示信息，需引入Message
                      this.$message.error("图片插入失败！");
                      this.uploadLoading = false;
                    }
                  } else {
                    this.$message.error("图片插入失败！");
                    this.uploadLoading = false;
                  }
                })
                .catch(err => {
                  this.$message.error("图片插入失败！");
                  this.uploadLoading = false;
                  console.log(err);
                });

              // const [res, err] = await apiService.getUploadToken();
              // if (err) return false;

              // let origin = res.data.picture.origin;
              // const fd = new FormData();
              // fd.append("key", key);
              // fd.append("token", res.data.picture.token);
              // fd.append("origin", origin);
              // fd.append("time", new Date().getTime());
              // fd.append("file", file);
              // apiService
              //   .uploadImage(fd)
              //   .then(res => {
              //     console.log(res, "res");
              //     let quill = this.$refs.myQuillEditor.quill; // 获取富文本对象
              //     let length = quill.getSelection().index; // 获取编辑器光标位置
              //     quill.insertEmbed(length, "image", `${origin}/${res.key}`); // 插入图片  图片地址
              //     quill.setSelection(length + 1); // 光标后移一位   调整光标到最后
              //   })
              //   .catch(err => {
              //     console.log(err);
              //   });
            } else {
              console.log("op.insert.image at line 407:", op.insert.image);
              // 获取光标所在位置
              var quill = that.$refs.myQuillEditor.quill;
              var length = this.quillEditorIndex;

              console.log("length at line 397:", length);

              // 插入图片，res为服务器返回的图片链接地址
              quill.insertEmbed(length, "image", op.insert.image);
              // 调整光标到最后
              quill.setSelection(length + 1);
              this.uploadLoading = false;
            }
          }
        }
      });

      delta.ops = ops; // 不加会报错
      return delta;
    },
    dataURLtoFile(dataurl, name) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], name, { type: mime });
    },
    // 提取富文本中image中的src
    extractImageSrc(htmlString) {
      let imgSrcArray = [];
      let imgTagRegex = /<img[^>]+src=['"]([^'"]+)['"][^>]*>/g;
      let match;

      while ((match = imgTagRegex.exec(htmlString)) !== null) {
        let src = match[1];
        imgSrcArray.push(src);
      }
      return imgSrcArray;
    },
    // ocr识别
    async handleImageOCR() {
      if (!this.quillContent) {
        this.$Message.error("请上传图片！");
        return false;
      }
      let imageList = this.extractImageSrc(this.quillContent);
      if (Array.isArray(imageList) && imageList.length) {
        const [res, err] = await service.ocrResult(imageList);
        if (err) return;
        if (res.ok && res.data) {
          this.ocrDescribe = res.data;
        }
      }
    },

    contentUploadSuccess(res, file) {
      // console.log(res)
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = this.quillEditorIndex;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
        this.uploadLoading = false;
      } else {
        this.uploadLoading = false;
        // 提示信息，需引入Message
        this.$message.error("图片插入失败！");
      }
    },
    handleCheckedCitiesChange(value) {
      // console.log(value, 'value')
    },
    // 获取商品标签
    getTags() {
      this.$http({
        url: this.$http.adornUrl("/book/label/getLabels"),
        method: "post"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.tagList = data.result.labels;
          // this.totalPage = data.page.totalCount
        } else {
          this.tagList = [];
          // this.totalPage = 0
        }
      });
    },
    showChooseBook() {
      // 显示图书列表
      this.$emit("showchooseBookf", { bookIds: this.dataForm.Books });
      // console.log('发送指令')
      this.$bus.$emit("showchooseBook", { bookIds: this.dataForm.Books });
    },
    init(id) {
      this.dataForm.productId = id || 0;
      this.visible = true;
      this.getTags();
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.productId) {
          this.$http
            .request({
              url: this.$http.adornUrl("/master/shopProduct/getProductDetail"),
              method: "POST",
              data: {
                productId: this.dataForm.productId
              },
              header: {
                //默认 无 说明：请求头
                "Content-Type": "application/json"
              }
            })

            .then(res => {
              console.log("result at line 452:", res);
              if (res && res.data.code === 0) {
                var data = res.data.detail.detail;
                console.log("data at line 357:", data);
                this.dataForm = {
                  ...data,

                  tags: data.labels,
                  hDprice: data.activityPrice
                };
                // if (data.goodsType) {
                //   this.dataForm.goodsType = Number(data.goodsType);
                // }
                this.dataForm.tags = data.labels;
                // console.log('收到的值', this.dataForm.tags)

                // this.dataForm.hDprice = data.shopProduct.activityPrice;
                let arrArr = [];

                if (data.bookidsimages !== "" && data.bookidsimages != null) {
                  this.dataForm.Books = data.bookidsimages;
                }

                sessionStorage.setItem(
                  "Books",
                  JSON.stringify(this.dataForm.Books)
                );

                if (data.productImages != "" && data.productImages != null) {
                  var img = {
                    name: "",
                    url: data.productImages
                  };
                  var attr = [];
                  attr.push(img);
                  this.fileList = attr;
                }

                if (
                  data.productImageList == null ||
                  data.productImageList[0] == "" ||
                  data.productImageList == ""
                ) {
                  this.swiperfileList = [];
                  // console.log('走这')
                } else {
                  // 有轮播图
                  // console.log(data.shopProduct.productImageList)
                  let arr = [];
                  let arr1 = [];

                  arr = data.productImageList.split(",");
                  // console.log(arr, '处理后得轮播图数组')
                  arr.forEach((item, index) => {
                    arr1.push({
                      name: index,
                      url: item
                    });
                  });
                  this.swiperfileList = arr1;
                }
              }
            });
        }
      });
    },
    // 获取商品类型
    getGoodsTypeList() {
      this.$http({
        url: this.$http.adornUrl("/book/sysdictdata/selectByType/goodsType"),
        method: "get"
      }).then(({ data }) => {
        // console.log(data.dataList)
        this.goodsTypeList = data.dataList;
      });
    },
    // 删除图书
    deliteBook(index) {
      this.dataForm.Books.splice(index, 1);
      sessionStorage.setItem("Books", JSON.stringify(this.dataForm.Books));
    },
    dealImgChange(file, fileList) {
      this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
    },
    // 表单提交
    dataFormSubmit() {
      // this.getBookIds();
      // console.log(this.bookidsd,'this.bookidsd')
      //    return false
      this.$refs["dataForm"].validate(valid => {
        this.dataForm.productImageList = this.getStringImgUrl();
        // var bookIDS = this.getBookIds();
        //  console.log(this.dataForm.productImageList)
        if (valid) {
          if (!this.dataForm.hDprice || this.dataForm.hDprice == 0) {
            // console.log('没有值')
            this.dataForm.hDprice = 0;
          }

          this.$http
            .request({
              url: this.$http.adornUrl(
                this.dataForm.productId ? this.urlList.edit : this.urlList.add
              ),
              method: "POST",
              data: {
                ...this.dataForm,
                product_details: this.dataForm.productDetails,
                activityPrice: this.dataForm.hDprice
              },
              header: {
                //默认 无 说明：请求头
                "Content-Type": "application/json"
              }
            })

            .then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$refs["dataForm"].resetFields();
                    // this.$refs['dataForm'].reset()
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
        }
      });
    },
    changeTime(e) {
      console.log(e);
    },
    getBookIds() {
      // 图书ids
      //  console.log(this.dataForm.Books,'Books')
      this.bookidsd = this.dataForm.Books.map(item => {
        return item.id;
      });
    },
    getTreeList() {
      this.$http({
        url: this.$http.adornUrl(`/book/shopcategory/listTree`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.categorys = data.data;
      });
    },
    handlePictureCardPreview(file) {
      this.dataForm.productImages = file.url;
      this.dialogVisible = true;
    },
    bannerHandlePicSuccess(res, file) {
      // 轮播图上传成功
      if (res.msg == "success") {
        this.swiperfileList.push({
          name: file.name,
          url: res.url
        });
        // console.log(this.swiperfileList)
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    // 字符串图片地址
    getStringImgUrl() {
      let arr = this.swiperfileList.map(item => item.url);
      if (arr.length <= 0) {
        return null;
      } else {
        return arr.toString();
      }
    },
    handlePicSuccess(res, file) {
      // console.log(res,'res')
      if (res.msg == "success") {
        this.dataForm.productImages = res.url;
        this.fileList.push({
          name: file.name,
          url: res.url
        });
        //  console.log(this.dataForm.productImages,'productImages')
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    bannerHandleRemove(file, fileList) {
      // 轮播图删除操作
      this.swiperfileList = fileList;
    },
    handleRemove(file, fileList) {
      this.dataForm.productImages = "";
      this.fileList = [];
      this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
    },
    handlereset() {
      (this.fileList = []), (this.visible = false);
      this.dataForm.tagList = [];
      this.dataForm.Books = [];
      this.swiperfileList = [];
      this.$refs["dataForm"].resetFields();
      sessionStorage.setItem("Books", JSON.stringify([]));
      // this.$refs['dataForm'].reset()
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      // console.log(".index at line 841:", quill.getSelection().index);
      //  console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      var index = quill.getSelection().index;
      this.quillEditorIndex = index;
      console.log("quill at line 839:", this.quillEditorIndex);
      //console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    }
  },
  components: {
    quillEditor
  },
  mounted() {
    this.$bus.$on("haveBookIds", data => {
      sessionStorage.setItem("Books", JSON.stringify(data.bookIds));
      //  console.log('haveBookIds',data)
      //console.log(data.bookIds, '收到的数据')
      var newarr = [];
      var ids = []; //哨兵数组
      if (data.bookIds && data.bookIds.length > 0) {
        ids[0] = data.bookIds[0].id;
        newarr[0] = data.bookIds[0];
        //   console.log(ids,'ids')
        //  newarr.push(data.bookIds[0])
        for (let index = 0; index < data.bookIds.length; index++) {
          if (!ids.includes(data.bookIds[index].id)) {
            // console.log(data.bookIds[index].id, 'data.bookIds[index].id')
            newarr.push(data.bookIds[index]);
            ids.push(data.bookIds[index].id);
          }
        }
      }
      //  console.log(newarr,'newarr',ids)
      data.bookIds.length > 0
        ? (this.dataForm.Books = newarr)
        : (this.dataForm.Books = []);
    });
  },

  watch: {
    visible: {
      handler(val, oldVal) {
        this.getGoodsTypeList();
      },
      deep: true
    }
  }
};
</script>

<style lang="less">
// .disUoloadSty {
//   .el-upload--picture-card {
//     display: none;
//     /* 上传按钮隐藏 */
//   }
// }

// .el-form-item {
//   /deep/ .el-form-item__label {
//     font-size: 12px;
//   }
// }

.el-uploadfeng {
  .el-upload-list__item {
    width: 95px;
    height: 95px;
  }

  .el-upload--picture-card {
    width: 95px;
    height: 95px;
    line-height: 95px;
  }
}

.shangpin_editor .ql-editor {
  height: 150px;
}
</style>
