import {Vue} from "vue-class-component";
export enum LocationMode {
    open='open',
    replace='replace',
    href='href'
}

export interface LocationConfig {
    // 跳转方式
    mode?: LocationMode,
}

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

// 如果为函数触发
interface LocationFunction {
    (item: LibData, index:number, Location:Vue): LocationUseDefaultParams
}

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

// 如果为异步函数触发
interface LocationAsyncFunction {
    (item: LibData, index:number, Location:Vue): AsyncExport
}
// 可传入的参数列表
type LocationUseParams = LocationUseDefaultParams | LocationFunction | LocationAsyncFunction;

export default class Location implements Trigger {

    /* 跳转方式 */
    static LocationMode = LocationMode;

    // 跳转的方式
    private readonly config:LocationConfig | undefined;

    // 跳转路由的参数
    private readonly LocationParams: LocationUseParams;

    // 构造器
    constructor(LocationParams: LocationUseParams,config:LocationConfig | undefined = undefined){
        /* 初始化设置 */
        this.config = config;
        this.LocationParams = LocationParams;
    }

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

        let LocationParams:LocationUseDefaultParams | AsyncExport = this.getLocationParams(item,index,Location);

        /* 如果为异步触发 */
        if (LocationParams instanceof Promise) {
            LocationParams.then((LocationParams:LocationUseDefaultParams)=> this.triggerLocation(LocationParams,Location)).catch((LocationParams:LocationUseDefaultParams)=> this.triggerLocation(LocationParams,Location));
        } else {
            return this.triggerLocation(LocationParams,Location);
        }


    }

    // 获取参数
    getLocationParams(item:LibData, index:number, Location:Vue):LocationUseDefaultParams | AsyncExport{

        let LocationParams:LocationUseDefaultParams | AsyncExport;

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

        return LocationParams;


    }

    // 执行跳转
    triggerLocation(params:LocationUseDefaultParams,Location:Vue) : void{

        let mode:LocationMode = this.getLocationMode();
        if (mode === LocationMode.open) {
            window[mode](params);
        } else {
            // @ts-ignore
            window.location[mode] = params;
        }

    }

    // 获取跳转方式
    getLocationMode():LocationMode{
        return  this.config && this.config.mode ? this.config.mode : LocationMode.open;
    }

}
