<template>
  <div class="bg-layout-card" :style="style">
    <div class="card-title">
      <h3 class="title-text text-clip">{{ title }}</h3>
      <ul class="filter-list" v-if="btns.length > 0">
        <li
          v-for="(item, index) in btns"
          :key="item"
          :class="{ current: index === btn }"
          @click="$emit('update:btn', index)">
          {{ item }}
        </li>
      </ul>
      <div
        class="download-btn"
        @click="downloadAction"
        v-loading="downloading"
        element-loading-spinner="el-icon-loading"
        v-if="download">
        <img src="./imgs/btn_daochu.png" />
      </div>
    </div>
    <div class="card-content" ref="content">
      <slot />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs, computed, nextTick } from "vue";
import html2canvas from "html2canvas";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "25%",
  },
  height: {
    type: String,
    default: "278px",
  },
  btn: {
    type: Number,
    default: 0,
  },
  btns: {
    type: Array,
    default: () => [],
  },
  download: {
    type: Boolean,
    default: false,
  },
});

const style = computed(() => {
  return {
    width: `calc(${props.width} - 20px)`,
    height: props.height,
  };
});

const downloading = ref(false);

const content = ref(null);

const getScrollTop = () => {
  let scrollTop = 0;

  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
  } else if (document.body) {
    scrollTop = document.body.scrollTop;
  }

  return scrollTop;
};

const downloadAction = () => {
  if (downloading.value) {
    return;
  }

  let { top, left } = content.value.getBoundingClientRect();
  let scrollTop = getScrollTop();

  downloading.value = true;

  html2canvas(content.value, { x: left, y: top + scrollTop }).then((canvas) => {
    let imgUrl = canvas.toDataURL("image/png");
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件

    nextTick().then(() => {
      a.download = props.title; // 设置图片名称
      a.href = imgUrl; // 将生成的URL设置为a.href属性
      a.dispatchEvent(event); // 触发a的单击事件

      downloading.value = false;
    });
  });
};
</script>
