import $ from 'jquery';
import Vue from 'vue';
import WjySdk 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: {
//     }
// })
import './sass/global.scss';

Vue.component('loading', resolve => require(['./components/loading.vue'], resolve));
Vue.component('dlfooter', resolve => require(['./components/dlfooter/dlfooter.vue'], resolve)); //通用底部下载栏
Vue.component('photoswipe', resolve => require(['./components/photoswipe.vue'], resolve)); 
Vue.component('comment', resolve => require(['./components/comment/comment.vue'], resolve));  //通用评论

Vue.component('home-index', resolve => require(['./page/home/index.vue'], resolve));        //首页
Vue.component('home-serve', resolve => require(['./page/home/serve.vue'], resolve));        //服务协议--要删掉

Vue.component('video-detail', resolve => require(['./page/video/detail.vue'], resolve));    //电影详情页
Vue.component('video-post', resolve => require(['./page/video/post.vue'], resolve));        //电影点评页
Vue.component('video-preview', resolve => require(['./page/video/preview.vue'], resolve));        //电影点评页

Vue.component('bbs-post', resolve => require(['./page/bbs/post.vue'], resolve));            //贴详情页
Vue.component('bbs-explain', resolve => require(['./page/bbs/explain.vue'], resolve));      //圈子说明

Vue.component('act-invite', resolve => require(['./page/act/invite.vue'], resolve)); //201710活动-邀请码
Vue.component('act-wzry', resolve => require(['./page/act/wzry.vue'], resolve)); //201710活动-王者荣耀公众号抽奖
// Vue.component('act-gorgelottery', resolve => require(['./page/act/gorgelottery.vue'], resolve));//201801活动-王者荣耀公众号-峡谷小助手导量
Vue.component('act-uplottory', resolve => require(['./page/act/uplottory.vue'], resolve)); //201712活动-关注up主抽奖

Vue.component('zt-rank', resolve => require(['./page/zt/rank.vue'], resolve)); //专题-豆瓣IMDb榜单
Vue.component('zt-blueray', resolve => require(['./page/zt/blueray.vue'], resolve)); //蓝光
Vue.component('zt-schedule', resolve => require(['./page/zt/schedule.vue'], resolve)); //上映表
// Vue.component('zt-boxoffice', resolve => require(['./page/zt/boxoffice.vue'], resolve)); //票房
Vue.component('zt-boxoffice', resolve => require(['./page/zt/boxofficePlus.vue'], resolve)); //票房
Vue.component('zt-boxofficeDetail', resolve => require(['./page/zt/boxofficeDetail.vue'], resolve)); //票房
Vue.component('zt-boxofficePlus', resolve => require(['./page/zt/boxofficePlus.vue'], resolve)); //票房榜-改版

Vue.component('answer-lastrank', resolve => require(['./page/answer/lastrank.vue'], resolve)); //201801答题-上周榜单
Vue.component('answer-totalrank', resolve => require(['./page/answer/totalrank.vue'], resolve)); //玩家总榜
Vue.component('answer-cashrecord', resolve => require(['./page/answer/cashrecord.vue'], resolve)); //提现记录
Vue.component('answer-awardrecord', resolve => require(['./page/answer/awardrecord.vue'], resolve)); //获奖记录
Vue.component('answer-cashapply', resolve => require(['./page/answer/cashapply.vue'], resolve)); //申请提现
Vue.component('answer-invite', resolve => require(['./page/answer/invite.vue'], resolve)); //申请提现

Vue.component('test-links', resolve => require(['./page/test/links.vue'], resolve)); //测试App Link


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") || "home-index";
        lib.setParam("page", page);
        _self._getWxSign();
        _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.Wjy) {
                if (href.indexOf('http') !== 0) {
                    href = location.protocol + '//' + location.host + href;
                }
                var title = $this.attr('data-title');
                WjySdk.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') || 'home-index';
                _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();
        },
        _getWxSign: function(){

            if (!lib.checkWXAgent()) return;

            $.ajax({
                url : "//h5game.duowan.com/weixin/getJsSign",
                type : "GET",
                dataType: "jsonp", 
                data : {
                    url : location.href,
                    appid : 22
                },
                success: function(ret){
                    ret.data.debug = false;
                    ret.data.jsApiList = [
                        "onMenuShareTimeline",
                        "onMenuShareAppMessage"
                    ];
                    wx.config(ret.data);
                }
            });
        },
        _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') || 'home-index';
                this._redirectPage(newPage);
            }
        },
        redirectClient(param, clientParam, title) {
            var _self = this;
            oldPage = this.currentView;
            
            var values = lib.parseHash(param);
            if (window.Wjy) {
                var search = document.location.search;
                search = lib.setParam2(values, search);
                if (clientParam) {
                    values = lib.parseHash(clientParam);
                    search = lib.setParam2(values, search);
                }

                WjySdk.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 (!WjySdk.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;
}