<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 urls = ref(props.urls);

    const download = () => {
      if (!urls.value.length) {
        ElMessage.error('没有可下载的文件');
        return;
      }
      const anchor = document.createElement('a');
      anchor.style.display = 'none';
      anchor.href = '#';
      document.body.appendChild(anchor);

      const formData = new FormData();
      urls.value.forEach(el => {
        axios
          .get(el.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);
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error('下载失败');
          });
      })

    };

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