import $ from 'jquery';
import Vue from 'vue';
import HiydSdk from 'extSdk';
// import Vuex from 'vuex';
import App from './components/app.vue';
import lib from 'lib';
import BDY from 'BDY';
// import NProgress from './depend/nprogress/nprogress';

// import User from './store/user';
// Vue.use(Vuex);
// const store = new Vuex.Store({
//     mutations: {},
//     actions: {},
//     getters: {},
//     modules: {
//     }
// })

Vue.component('loading', resolve => require(['./components/loading.vue'], resolve));

Vue.component('share-moment',resolve => require(['./page/share/moment.vue'], resolve))
Vue.component('share-video',resolve => require(['./page/share/video.vue'], resolve))

Vue.component('download-index',resolve => require(['./page/download/index.vue'], resolve))
Vue.component('download-index2',resolve => require(['./page/download/index2.vue'], resolve))



var pages = {};
var oldPage;

var VM = new Vue({
    // store,
    el: "#app",
    data: {
        currentView: "",
        isForward: true,
        isInit: true,
        transitionName: "fade"
    },
    computed: {
        transitionMode () {
            return this.isForward ? "out-int" : "in-out";
        }
    },
    mounted() {
        var _self = this;
        var page = lib.getParam("page") || "share-moment";
        lib.setParam("page", page);
        _self._redirectPage(page);

        // 点击事件
        $('body').off(BDY.click + ".data-href").on(BDY.click + ".data-href", '[data-href]', function () {
            var $this = $(this);

            var href = $this.attr('data-href') || $this.attr('href');
            var clientParam = $this.attr('data-client');
            if (clientParam != null) {
                var title = $this.attr('data-title');
                _self.redirectClient(href, clientParam, title);
            } else {
                _self.redirect(href);
            }

            return false;
        });

        $('body').off(BDY.click + ".data-url").on(BDY.click + ".data-url", '[data-url]', function () {
            var $this = $(this);

            var href = $this.attr('data-url');
            if (window.Hiyd) {
                if (href.indexOf('http') !== 0) {
                    href = location.protocol + '//' + location.host + href;
                }
                var title = $this.attr('data-title');
                HiydSdk.openUrl(href, title, true);
            } else {
                location.href = href;
            }

            return false;
        });

        window.onpopstate = function (event) {
            // 支持onpopstate
            var count = 0;
            for (var page in pages) {
                if (count++ > 1) {
                    break;
                };
            }

            // 防止首次进入就触发onpopstate导致再次刷新
            if (count > 1) {
                var newPage = lib.getParam('page') || 'share-moment';
                _self._redirectPage(newPage);
            }
        }

        initActiveEvent();
    },
    methods: {
        afterEnter: function () {
            if (VM.isForward) {
                scrollTo(0, 0);
            } else {
                var scrollTop = pages[lib.getParam("page")]['scrollTop'] || 0;
                scrollTo(0, scrollTop);
            }
            VM.isForward = false;
            // NProgress.done();
        },
        _redirectPage(_page) {
            var _self = this;

            /** 当前页面不重复请求 */
            if (_self.currentView == _page) {
                return;
            }

            pages[_page] = pages[_page] || {};
            // NProgress.start();

            if (oldPage) {
                pages[oldPage] = pages[oldPage] || {};
                //保存滚动条位置$pageswarp
                // pages[oldPage]['scrollTop'] = document.body.scrollTop;
                //console.log("oldPage:" + oldPage + ", scrollTop:" + pages[oldPage]['scrollTop']);
                // pages[oldPage]['height'] = $pageswarp.height();

                lib.clearRes();
            }

            _self.currentView = _page;

            $(document).trigger(BDY.pageChange, _page);

            oldPage = _page;
        },
        redirect(param) {
            this._redirect(param, true);
        },
        _redirect(param, causeHistory) {
            oldPage = this.currentView;
            pages[oldPage] = pages[oldPage] || {};
            pages[oldPage]['scrollTop'] = _getScrollTop();
            var values = lib.parseHash(param);
            this.isForward = true;
            lib.setParam(values, causeHistory);

            // 这里需要自己渲染
            this._redirectPage(values['page']);
        },
        redirect2(param) {
            var oldUrl = document.location.href;
            this._redirect(param, false);
            if (oldUrl != document.location.href) {
                var newPage = lib.getParam('page') || 'share-moment';
                this._redirectPage(newPage);
            }
        },
        redirectClient(param, clientParam, title) {
            var _self = this;
            oldPage = this.currentView;
            
            var values = lib.parseHash(param);
            if (window.Hiyd) {
                var search = document.location.search;
                search = lib.setParam2(values, search);
                if (clientParam) {
                    values = lib.parseHash(clientParam);
                    search = lib.setParam2(values, search);
                }

                HiydSdk.openUrl(location.origin + location.pathname + search, title, true);
            } else {
                _self.redirect(param);
            }
        },
        historyBack() {
            var curPage = this.currentView;
            pages[curPage] = pages[curPage] || {};
            pages[curPage]['scrollTop'] = 0;
            if (!HiydSdk.historyBack()) {
                history.back();
            }
        }
    }
})

function initActiveEvent() {
    var selector = "input[type='submit'], [data-active]";
    var $elem, $activeElem;
    var timeHandler = 0;
    var LONG_TAP_TIME = 500;

    $(document).off(BDY.touchstart + ".body").on(BDY.touchstart + ".body", function (e) {

        $elem = $(e.target);
        $activeElem = $elem;

        if (!$activeElem.filter(selector).length) {
            $activeElem = $activeElem.parents(selector);
        }

        var activeStyle = $activeElem.attr("data-active") || "active";
        $activeElem.addClass(activeStyle);

        timeHandler = lib.setTimeout(function () {
            $elem && $elem.trigger('longTap');
            _removeActive();
        }, LONG_TAP_TIME);
    });

    $(document).off("touchmove.body, scroll.body").on("touchmove.body, scroll.body", function (event) {
        clearTimeout(timeHandler);
        timeHandler = 0;

        _removeActive();
        $elem = null;
    });

    $(document).off("mouseout.body").on("mouseout.body", selector, function (event) {
        _removeActive();
        $elem = null;
    });

    window.onResume = document.createEvent('Event');
    window.onResume.initEvent('onResume', true, true);

    $(document).on('onResume', function () {
        console.log('onResume');
    });

    var lastTime = 0;
    $(document).off(BDY.touchend + ".body").on(BDY.touchend + ".body", function (e) {
        clearTimeout(timeHandler);
        timeHandler = 0;

        if ($elem) {
            var currentTime = (new Date()).getTime();
            var duration = currentTime - lastTime;
            var MIN_TRIGGER_INTERVAL = 300;

            if (duration > MIN_TRIGGER_INTERVAL) {
                $elem.trigger('touchclick');
                // 记录当前时间
                lastTime = currentTime;
            }
        }

        _removeActive();
    });

    function _removeActive() {
        if ($activeElem != null) {
            var activeStyle = $activeElem.attr("data-active") || "active";
            $activeElem.blur();
            $activeElem.removeClass(activeStyle);
            $activeElem = null;
        }
        $elem = null;
    }

    ['longTap', 'touchclick'].forEach(function (m) {
        $.fn[m] = function (callback) {
            return this.on(m, callback);
        };
    });
}


function _getScrollTop() {
    return document.documentElement.scrollTop || document.body && document.body.scrollTop;
}