<template>
  <div class="ant-upload-list ant-upload-list-text">
    <div class="ant-upload-list-text-container">
      <div class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-text" v-if="getFilePath()">
        <div class="ant-upload-list-item-info">
          <span class="ant-upload-span">
            <div class="ant-upload-text-icon">
              <Icon icon="ant-design:paper-clip-outlined"/>
            </div>
<!--            <a target="_blank" rel="noopener noreferrer" class="ant-upload-list-item-name" :title="getFileName()" :href="getFilePath()">{{ getFileName() }}</a>-->
            <a rel="noopener noreferrer" class="ant-upload-list-item-name" :title="getFileName()" @click="downLoadFile()">{{ getFileName() }}</a>
          </span>
        </div>
        <div class="ant-upload-list-item-progress" style="display: none;"></div>
      </div>
      <a-empty v-else/>
    </div>
  </div>
  <div class="example">
    <a-spin :spinning="spinning" size="large" tip="下载中..." />
  </div>
</template>
<script lang="ts" name="jiaoXueDanYuanNeiRongIndexDownload" setup>
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils'
  import {ref} from "vue";
  import {useMessage} from "/@/hooks/web/useMessage";
  const { createMessage } = useMessage();
  const spinning = ref<boolean>(false);
  const props = defineProps({
    filePath: { type: String },
    fileName: { type: String },
  });

  function getFileName(){
    if(props.fileName){
      return props.fileName;
    }else{
      if(!props.filePath) return '';
      let pathList = props.filePath?.replaceAll('\\','/').split('/');
      if(pathList.length){
        return pathList[pathList.length-1] || '';
      }
      return '';
    }
  }

  function getFilePath(){
    if(!props.filePath) return null;
    return getFileAccessHttpUrl(props.filePath);
  }

  function downLoadFile(){
    if(!props.filePath) return null;
    let url = getFileAccessHttpUrl(props.filePath);
    openWindowWithLoading(url);
  }

  function openWindowWithLoading(url){
    let xhr = new XMLHttpRequest();
    spinning.value = true;
    xhr.open('GET',url,true);
    xhr.send();
    xhr.responseType = "arraybuffer";
    xhr.onreadystatechange = event =>{
      if(xhr.readyState == 4){
        if(xhr.status == 200){
          let fileName = url.substring(url.lastIndexOf("/")+1);
          let blob = new Blob([xhr.response]);
          const downLoadLink = document.createElement('a');
          downLoadLink.download = fileName;
          downLoadLink.href = URL.createObjectURL(blob);
          downLoadLink.click();
        }else if (xhr.status == 404){
          createMessage.warning('没有找到可下载的资源！');
        }
      }
      spinning.value = false;
    }
  }

</script>

<style lang="less" scoped>
.example {
  text-align: center;
  background: rgba(0, 0, 0, 0);
  border-radius: 4px;
  position: absolute;
  left: 50%;
  top: 50%;
}
</style>
