import ImgPreview from "./ImgPreview.vue";
function setPreview(Vue, el) {
  if (el.nodeName.toLowerCase() === "img") {
    let imgUrl = el.src;
    if (imgUrl) {
      el.style.cursor = "pointer";
      el.onclick = () => {
        let _ImgPreview = Vue.extend(ImgPreview);
        const instance = new _ImgPreview({
          propsData: {
            images: [imgUrl]
          }
        });
        instance.$mount();
        document.body.appendChild(instance.$el);
        instance.previewIndex = 0;
        instance.currentSrc = imgUrl;
        instance.showPreview = true;
      };
    }
  } else {
    let imgEls = el.getElementsByTagName("img");
    let imgUrls = [];
    for (let imgIndex = 0; imgIndex < imgEls.length; imgIndex++) {
      let imgEl = imgEls[imgIndex];
      imgEl.setAttribute("preview_index", imgIndex);
      let imgUrl = imgEl.src;
      if (imgUrl) {
        imgUrls.push(imgUrl);
      }
    }
    for (const imgEl of imgEls) {
      let imgIndex = imgEl.getAttribute("preview_index");
      let imgUrl = imgEl.src;
      if (imgUrl) {
        imgEl.style.cursor = "pointer";
        imgEl.onclick = () => {
          let _ImgPreview = Vue.extend(ImgPreview);
          const instance = new _ImgPreview({
            propsData: {
              images: imgUrls
            }
          });
          instance.$mount();
          document.body.appendChild(instance.$el);
          instance.$nextTick(() => {
            instance.currentSrc = imgUrl;
            instance.previewIndex = Number(imgIndex);
            instance.showPreview = true;
          });
        };
      }
    }
  }
}
const installObj = {
  install: function (Vue) {
    Vue.component("ImgPreview", ImgPreview);
    Vue.directive("preview", {
      inserted: function (el) {
        setPreview(Vue, el);
      },
      componentUpdated: function (el) {
        setPreview(Vue, el);
      }
    });
  }
};
export default installObj;
