import components from '../components';
import parseQuery from './lib/parse-query';
import { showSystemLog } from './nativeApi/util';
import * as eventHandlers from './nativeApi/util/eventHandlers';
import {debounce} from 'throttle-debounce';

Vue.use(components);

var onLoadTimeStamp = +new Date();

export default class Page {
    /**
     * page作为一个页面所有组件的容器，包括page顶层组件
     * native在新建一个webview时会生成一个id
     * @param {string} id
     * @param {string} uri
     */
    constructor(id, uri) {
        onLoadTimeStamp = +new Date();
        showSystemLog && console.log('new Page(%s, %s)', id, uri);
        // 实例化页面时记录当前路径，需要配合onShow再记录一次，因为后退页面栈不涉及实例化页面
        Service.location.href = uri;

        this._uid = 0;
        this.id = id;
        this.uri = uri;
        this.name = uri.split('?')[0];
        // 新建webview的时候还拿不到page顶层组件的id，
        let App = Service.componentsOptions[this.name];

        // 当前页面ID
        global.__biliCacheData.currentPageId = id;
        global.__biliCacheData.pageIdStatus = 'beforeVue'

        this.root = new Vue({
            el: '#app',
            render: h => h(App),
            $page: this
        });
        this.components = this.root.$vmMap[this.id];
        this.root.$page = this;
        this.root.route = this.name;

        // 判断降级，window和Service，如果存在就赋值。
        if (global.window) global.window.components = this.components;
        if (global.Service) global.Service.components = this.components;

        // 部分对齐微信getCurrentPages返回的对象
        this.data = this.root.$data.data;
        this.options = this.getQuery();
        this.pageVm = this.root.$children[0];
        this.pageVm.route = this.pageVm.__route__ = this.name;
        Service.location.currentPage = this.pageVm;
        global.__biliCacheData.pageIdStatus = 'setVue'

        // showSystemLog && console.log('page constructor end', this.components);
    }

    // 部分对齐微信getCurrentPages返回的对象
    setData(params) {
        this.pageVm.setData(params);
    }

    handleMessage(message) {
        if (message.type === 'method') {
            this.handleMethod(message);
        } else if (message.type === 'lifecycle') {
            this.handleLifecycle(message);
        } else if (message.type === 'page-event') {
            this.handlePageEvent(message);
        }
    }

    handleMethod(message) {
        showSystemLog && console.log('Page.handleMethod', message);
        try {
            const component = this.components[message.id];
            const handler = message.handler;
            if (typeof component[handler] === 'function') {
                component[handler].apply(component, JSON.parse(message.args));
            }
        } catch (e) {
            Service.onError(e, true);
            showSystemLog && console.error(e);
        }
    }

    /**
     * 处理lifecycle类型的消息
     *
     * @param {Object} message 消息对象
     * @param {string} message.type 类型 lifecycle
     * @param {string} message.event 事件 onLoad/onShow/onHide/onUnload/onReady
     */
    handleLifecycle(message) {
        showSystemLog && console.log('Page.handleLifecycle', message);
        const options = this.components[1].$options;
        const event = message.event;

        // 实例化页面时记录当前路径，需要配合onShow再记录一次，因为后退页面栈不涉及实例化页面
        if (event === 'onShow') {
            if (typeof window !== 'undefined') {
                window.components = this.components;
            } else {
                Service.components = this.components;
            }

            Service.location.href = this.uri;
            Service.location.currentPage = this.pageVm;

            // 兼容处理 ios9 字体加载问题，因为ios处理不了（后台webview加载字体问题，大概率加载不到文件）
            if (global.__biliCacheData.font.openGlobal) {
                Service.postMessage(JSON.stringify({
                    type: 'lifecycle',
                    event: 'onShow'
                }), global.__biliCacheData.getCurrentPageId())
            }
        }

        // 页面销毁，做一些删除todo..
        if (event === 'onUnload') {
            let _pageId = global.__biliCacheData.getCurrentPageId();
            // 删除缓存数据
            if (eventHandlers.accelerometerChangeHandlers[_pageId])  delete eventHandlers.accelerometerChangeHandlers[_pageId];
            if (eventHandlers.compassChangeHandlers[_pageId]) delete eventHandlers.compassChangeHandlers[_pageId];
        }

        if (options && typeof options[event] === 'function') {
            options[event].call(this.components[1], parseQuery(this.uri));
        }
    }

    /**
     * 处理页面事件
     *
     * @param {Object} message 消息对象
     * @param {string} message.type 消息类型 page-event
     * @param {string} message.event 事件 onPullDownRefresh/onReachBottom/onPageScroll/onShareAppMessage/onTabItemTap
     */
    handlePageEvent(message) {
        showSystemLog && console.log('Page.handlePageEvent', message);
        const options = this.components[1].$options;
        const event = message.event;
        let result;

        if (event === 'onPageScroll') {
            result = {
                scrollTop: message.scrollTop
            };
        } else {
            result = message.data;
        }

        if (event === 'onReachBottom') {
            // ios 一进来即触发onReachBottom的情况须过滤
            if (new Date() - onLoadTimeStamp < 700) {
                return;
            }
        }
        if (options && typeof options[event] === 'function') {
            // if ((event || '').toLocaleLowerCase() === 'onpagescroll') {
            //     /* 修复 component.onPageScroll 频繁触发问题
            //      * 问题描述：
            //      * 当 component.onPageScroll中做一些比较耗时的操作时，例如：this.array.splice(this.current, 1, scrollTop)
            //      * 会造成 Service 队列阻塞，影响页面性能
            //      *
            //      * 修复方案：
            //      * 将component.onPageScroll debounce 化，放入options[onPageScroll_debounced]
            //      * 触发延迟设置 16ms
            //      */
            //     if (!options[event + '_debounced']) {
            //         options[event + '_debounced'] = debounce(16, (result) => {
            //             // Debounced function
            //             options[event].call(this.components[1], result);
            //
            //         });
            //     }
            //     options[event + '_debounced'](result);
            // } else {
            //     // 非 onPageScroll 事件，走原先逻辑
            //     options[event].call(this.components[1], result);
            // }
            options[event].call(this.components[1], result);
        }
        // if (options && typeof options[event] === 'function') {
        //     options[event].call(this.components[1], result);
        // }
    }

    getQuery() {
        return parseQuery(this.uri);
    }
}

Page.pages = {};
Page.componentsConfig = {};
