import { Injectable } from '@angular/core';
import { Platform, ActionSheetController, NavController } from '@ionic/angular';
import { AppEnvironment } from '../../environments/AppEnvironment';

@Injectable({ providedIn: 'root' })
export class App {

    /**
     * 视图回调
     *
     * @private
     * @memberof App
     */
    private $viewCallbacks: ((res: any) => void)[] = [];

    /**
     * 当前运行平台类型
     *
     * @private
     * @type {('ios' | 'android' | 'other')}
     * @memberof App
     */
    private $platFormType: 'ios' | 'android' | 'other' = 'other';

    /**
     * 应用功能页
     *
     * @private
     * @type {Map<string, string>}
     * @memberof App
     */
    private $functionPages: Map<string, string> = new Map();

    /**
     * 是否加载AppData数据
     *
     * @type {boolean}
     * @memberof App
     */
    public $isLoadAppData: boolean = true;

    /**
     * 应用数据
     *
     * @private
     * @type {*}
     * @memberof AppService
     */
    private $appdata: string = '';

    /**
     * 本地数据
     *
     * @private
     * @type {*}
     * @memberof AppService
     */
    private $localdata: any = {};

    /**
     * Creates an instance of App.
     * @param {Platform} platform
     * @memberof App
     */
    constructor(
        private platform: Platform,
        private actionSheetController: ActionSheetController,
        private navCtrl: NavController
    ) {
        const platforms: string[] = this.platform.platforms();
        const str: string = platforms.toString();
        if (str.indexOf('ios') !== -1) {
            this.$platFormType = 'ios';
        } else if (str.indexOf('android') !== -1) {
            this.$platFormType = 'android';
        }
    }

    /**
     * 获取当前运行平台类型
     *
     * @returns {('ios' | 'android')}
     * @memberof App
     */
    public getPlatFormType(): 'ios' | 'android' | 'other' {
        return this.$platFormType;
    }

    /**
     * 是否为ios平台
     *
     * @returns {boolean}
     * @memberof App
     */
    public isIos(): boolean {
        return Object.is(this.$platFormType, 'ios');
    }

    /**
     * 是否为Android平台
     *
     * @returns {boolean}
     * @memberof App
     */
    public isAndroid(): boolean {
        return Object.is(this.$platFormType, 'android');
    }

    /**
     * 返回回调关闭
     *
     * @param {*} res
     * @memberof App
     */
    public closeCallback(res: any): void {
        if (this.$viewCallbacks.length > 0) {
            const func = this.$viewCallbacks[this.$viewCallbacks.length - 1];
            func(res);
            this.$viewCallbacks.pop();
        }
    }

    /**
     * 设置回调
     *
     * @returns {Observable<any>}
     * @memberof App
     */
    public nextViewCloseCallback(func: (res: any) => void): void {
        this.$viewCallbacks.push(func);
    }

    /**
     * Ionic运行平台Api
     *
     * @returns {Platform}
     * @memberof App
     */
    public getPlatForm(): Platform {
        return this.platform;
    }

    /**
     * 应用底部悬浮工具栏
     *
     * @param {*} [opts={}] 数据
     * @param {string} [identification='tag'] 点击返回标识字段
     * @returns {Promise<string>}
     * @memberof App
     */
    public async openActionSheet(opts: any = {}, id: string = 'tag'): Promise<string> {
        if (opts.items) {
            const buttons: any[] = opts.items.map((item) => {
                const { text, icon, iconcls } = item;
                return { text: text, icon: iconcls ? iconcls : icon, role: item.id };
            });
            buttons.push({ text: '取消', role: 'cancel', color: 'red' });
            const actionSheet = await this.actionSheetController.create({
                header: opts.text,
                buttons
            });
            await actionSheet.present();
            const result = await actionSheet.onWillDismiss();
            return result.role;
        }
    }

    /**
     * 注册应用功能页
     *
     * @param {string} type 功能页类型
     * @param {string} url 功能页地址
     * @memberof App
     */
    public regFunctionPage(type: string, url: string): void {
        this.$functionPages.set(type, url);
    }

    /**
     * 获取登录页地址
     *
     * @returns {string} 登录页地址
     * @memberof App
     */
    public getLoginPage(): string {
        const loginUrl: string = this.$functionPages.get('login');
        if (!loginUrl) {
            alert('请在系统配置登录页！');
        }
        return loginUrl;
    }

    /**
     * 获取启动视图
     *
     * @returns {string}
     * @memberof App
     */
    public getStartPage(): string {
        return this.$functionPages.get('start');
    }

    /**
     * 获取应用默认页地址
     *
     * @returns {string} 默认页地址
     * @memberof App
     */
    public getDefaultPage(): string {
        return this.$functionPages.get('default');
    }

    /**
     * appdata添加数据
     *
     * @param {*} appdata
     * @memberof AppService
     */
    public setAppData(appdata: string): void {
        this.$appdata = appdata;
    }

    /**
     * 获取appdata数据
     *
     * @returns {*}
     * @memberof AppService
     */
    public getAppData(): string {
        return this.$appdata;
    }

    /**
     * 添加本地数据
     *
     * @param {*} data
     * @memberof AppService
     */
    public addLocalData(data: any): void {
        Object.assign(this.$localdata, data);
    }

    /**
     * 获取本地数据
     *
     * @memberof AppService
     */
    public getLocalData(): void {
        return this.$localdata;
    }

    /**
     * 去登录页
     *
     * @memberof App
     */
    public login(): void {
        const str: string = window.location.hash;
        this.navCtrl.navigateRoot([this.getLoginPage(), { url: str.slice(1, str.length) }]);
    }

    /**
     * 获取用户登录id
     *
     * @returns {string}
     * @memberof App
     */
    public getLoginKey(): string {
        return window.localStorage.getItem('srfloginkey');
    }

    /**
     * 清除认证信息
     *
     * @memberof App
     */
    public clearAccess(): void {
        window.localStorage.removeItem('srfloginkey');
        window.localStorage.removeItem('userInfo');
    }

    /**
     * 获取用户信息
     *
     * @returns {*}
     * @memberof App
     */
    public getUserInfo(): any {
        const userInfo: string = window.localStorage.getItem('userInfo');
        try {
            return JSON.parse(userInfo);
        } catch (error) {
            console.error(error);
        }
        return null;
    }

}