<template>
  <div class="qrcode">
    <div class="top">
      <div class="left">
        <el-input-number
          class="input"
          size="small"
          v-model="number"
          :min="0"
          :max="200"
          @change="changeNumber"
        ></el-input-number>
        <el-button type="primary" size="small" @click="downloadQrcode" plain
          >批量下载</el-button
        >
      </div>
      <div class="right"></div>
      <el-button type="primary" size="small" @click="clearQrcode" plain
        >清空界面</el-button
      >
    </div>
    <img v-for="obj in urls" :key="obj.uuid" :src="obj.url" alt="" />
  </div>
</template>
<script>
import QRCode from "qrcode";
import { v4 as uuidv4 } from "uuid";
import JSZip from "jszip";
import { saveAs } from "file-saver";
export default {
  data() {
    return {
      urls: [],
      number: 0,
    };
  },
  mounted() {},
  methods: {
    // 改变数量
    changeNumber(val) {
      if (val == undefined) {
        this.number = 0;
      } else {
        this.number = val;
      }
      if (this.number) {
        this.DracodeList();
      }
    },
    // 绘制Qrcode
    DracodeList() {
      this.urls = [];
      for (let i = 0; i < this.number; i++) {
        const uuid = uuidv4();
        QRCode.toDataURL(uuid)
          .then((url) => {
            this.urls.push({
              url,
              uuid,
            });
          })
          .catch((err) => {
            console.error(err);
          });
      }
    },
    //清空界面
    clearQrcode() {
      this.urls = [];
    },
    //下载二维码
    downloadQrcode() {
      if (!this.urls.length) {
        return;
      }
      var zip = new JSZip();
      var img = zip.folder("QRcode");
      const urls = this.urls;

      setTimeout(function () {
        for (var i = 0; i < urls.length; i++) {
          img.file(urls[i].uuid + ".png", urls[i].url.substring(22), {
            base64: true,
          });
        }
        zip.generateAsync({ type: "blob" }).then(function (content) {
          saveAs(content, "QRcode.zip");
        });
      }, 100);
    },
  },
};
</script>
<style lang="less" scoped>
.qrcode {
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      .input {
        margin-right: 12px;
      }
    }
  }
}
</style>
