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

export enum RouterMode {
    push,
    replace,
    go
}

export interface RouterConfig {
    // 跳转方式
    mode?: RouterMode,
}

// 常规使用的参数
type RouterUseDefaultParams = RouteRecordRaw | number | string;

// 如果为函数触发
interface RouterFunction {
    (item: LibData, index:number, router:Vue): RouterUseDefaultParams
}

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

// 如果为异步函数触发
interface RouterAsyncFunction {
    (item: LibData, index:number, router:Vue): AsyncExport
}
// 可传入的参数列表
type RouterUseParams = RouterUseDefaultParams | RouterFunction | RouterAsyncFunction;

export default class Router implements Trigger {

    /* 跳转方式 */
    static routerMode = RouterMode;

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

    // 跳转路由的参数
    private readonly routerParams: RouterUseParams;

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

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

        let routerParams:RouterUseDefaultParams | AsyncExport = this.getRouterParams(item,index,router);

        /* 如果为异步触发 */
        if (routerParams instanceof Promise) {
            routerParams.then((routerParams:RouterUseDefaultParams)=> this.triggerRouter(routerParams,router)).catch((routerParams:RouterUseDefaultParams)=> this.triggerRouter(routerParams,router));
        } else {
            return this.triggerRouter(routerParams,router);
        }


    }

    // 获取参数
    getRouterParams(item:LibData, index:number, router:Vue):RouterUseDefaultParams | AsyncExport{

        let routerParams:RouterUseDefaultParams | AsyncExport;

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

        return routerParams;


    }

    // 执行跳转
    triggerRouter(params:RouterUseDefaultParams,router:Vue) : void{
        // @ts-ignore
        params !== undefined && params !== null && router.$router[this.getRouterMode()](params);
    }

    // 获取跳转方式
    getRouterMode():string{
        if (this.config && this.config.mode) {
            return Router.getRouterMode(this.config.mode);
        } else {
            return Router.getRouterMode(RouterMode.push);
        }
    }

    // 根据 routerMode 返回跳转名称
    static getRouterMode(mode:RouterMode):string{

        switch (mode) {
            case RouterMode.go:return 'go';
            case RouterMode.push:return 'push';
            case RouterMode.replace:return 'replace';
        }

    }

}
