// 将页面dom生成图片并保存在本地
import * as htmlToImage from 'html-to-image';
import FileSaver from 'file-saver';

export default {
  mounted(el, binding) {
    const options = binding.value;
    let pressTimer = null;

    const cancelTimer = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };

    el.addEventListener('mousedown', () => {
      pressTimer = setTimeout(() => {
        const targetEl = document.querySelector(options.target);
        if (targetEl) {
          htmlToImage.toBlob(targetEl, options).then(function (blob) {
            FileSaver.saveAs(blob, options.filename);
          });
        }
      }, 1000);
    });

    el.addEventListener('touchstart', () => {
      pressTimer = setTimeout(() => {
        const targetEl = document.querySelector(options.target);
        if (targetEl) {
          htmlToImage.toBlob(targetEl, options).then(function (blob) {
            FileSaver.saveAs(blob, options.filename);
          });
        }
      }, 1000);
    });

    el.addEventListener('mouseup', cancelTimer);
    el.addEventListener('touchend', cancelTimer);
  }
};

