<template>
  <div>
    <el-button type="primary" @click="download">下载</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import { ElButton, ElMessage } from 'element-plus';
import axios from 'axios';

export default defineComponent({
  components: { ElButton },
  props: {
    urls: { type: Array, required: true },
    fileName: { type: String, default: '' },
  },
  setup(props) {

    const download = () => {
      const loadingInstance = ElLoading.service({
        text: "正在解析视频",
        background: "rgba(0,0,0,.2)",
      });
      if (!props.urls.length) {
        ElMessage.error('没有可下载的文件');
        return;
      }
      const anchor = document.createElement('a');
      anchor.style.display = 'none';
      anchor.href = '#';
      document.body.appendChild(anchor);
      props.urls.forEach(el => {
        axios
          .get(el.download_video_url, {
            responseType: 'blob',
          })
          .then((response) => {
            anchor.download = `《${props.fileName}》${el.series_name}.mp4`;
            const blob = new Blob([response.data]);
            const objectUrl = URL.createObjectURL(blob);
            anchor.href = objectUrl;
            anchor.click();
            URL.revokeObjectURL(objectUrl);
            loadingInstance.close()
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error('下载失败');
            loadingInstance.close()
          });
      })

    };

    return { download };
  },
});
</script>
