import axios from 'axios';
import { authDB } from '@/db'
import { Message } from 'element-ui';

import fileDownload from 'js-file-download'

export async function download(  url, cb  ) {
    axios({
       method: 'get',
       url: url,
       headers:{
         'Content-Type': 'application/json',
         'x-token': authDB.get('token'),
         'x-user-id': authDB.get('uid')
       },
        responseType: 'blob'
     }).then(res => {
        let filename=res.headers['filename'];
        console.log( res.headers  )
        if( res.headers['success'] == "true" ){
          filename = decodeURI( filename )
          fileDownload(res.data, filename);
          cb&&cb( {code:200})
        }else{
          Message({
              duration:2000,
              showClose: true,
              message: "文件下载失败",
              type: 'error'
          })
          cb&&cb( {code:7})
        }
        
     });

    // const res = await axios({
    //     baseURL: process.env.VUE_APP_BASE_API,
    //     timeout: 2 * 60 * 60 * 1000,
    //     headers:{
    //       'Content-Type': 'application/json',
    //       'x-token': authDB.get('token'),
    //       'x-user-id': authDB.get('uid')
    //     },
    //     url:url,
    //     method:"get",
    //     responseType: "blob"
    // });
    // let disposition = res.headers['content-disposition'];
    // disposition= disposition.replace("attachment; filename=", "")
    // disposition= disposition.replace(" ", "")
    // let filename = decodeURI( disposition );
    // let fileType=res.headers['content-type'];

    // let resBlob = res.data;
    // let resData = null;
    // try {
    //     let resText = await new Promise((resolve, reject) => {
    //         // 通过 FileReader 接受并解析
    //         let reader = new FileReader();
    //         reader.addEventListener('abort', reject);
    //         reader.addEventListener('error', reject);
    //         reader.addEventListener('loadend', () => {
    //             resolve(reader.result);
    //         });
    //         // 文件
    //         reader.readAsText(resBlob);
    //     });
    //     resData = JSON.parse(resText);
    // } catch (err) {

    // }
    // cb && cb( resData )

    // if (resData) {

    // } else {
    //     fileDownload(resBlob, filename);
    // }
}
