import {Vue} from "vue-class-component";

// 常规使用的参数
type DownUseDefaultParams = string;

// 如果为函数触发
interface DownFunction {
    (item: LibData, index:number, Down:Vue): DownUseDefaultParams
}

// 作为异步导出的函数
type AsyncExport = Promise<DownUseDefaultParams>;

// 如果为异步函数触发
interface DownAsyncFunction {
    (item: LibData, index:number, Down:Vue): AsyncExport
}
// 可传入的参数列表
type DownUseParams = DownUseDefaultParams | DownFunction | DownAsyncFunction;

export default class Down implements Trigger {


    // 跳转路由的参数
    private readonly DownParams: DownUseParams;

    // 构造器
    constructor(DownParams: DownUseParams){
        this.DownParams = DownParams;
    }

    // 触发
    trigger(item:LibData, index:number, Down:Vue): void {

        let DownParams:DownUseDefaultParams | AsyncExport = this.getDownParams(item,index,Down);

        /* 如果为异步触发 */
        if (DownParams instanceof Promise) {
            DownParams.then((DownParams:DownUseDefaultParams)=> this.triggerDown(DownParams,Down)).catch((DownParams:DownUseDefaultParams)=> this.triggerDown(DownParams,Down));
        } else {
            return this.triggerDown(DownParams,Down);
        }


    }

    // 获取参数
    getDownParams(item:LibData, index:number, Down:Vue):DownUseDefaultParams | AsyncExport{

        let DownParams:DownUseDefaultParams | AsyncExport;

        if (typeof this.DownParams === 'function') {
            DownParams = this.DownParams(item,index,Down);
        } else {
            DownParams = this.DownParams;
        }

        return DownParams;


    }

    // 执行跳转
    triggerDown(params:DownUseDefaultParams,Down:Vue) : void{
        let aEl = document.createElement("a");
        aEl.download = params.split('/').pop();
        aEl.href = params;
        aEl.setAttribute('style','display:none');
        document.body.appendChild(aEl);
        aEl.click();
        aEl.parentNode.removeChild(aEl);
    }

}
