<template>

    <section class="eye-viewport">

        <van-nav-bar
                v-if="hasHeader && !nativeHeader"
                :title="title"
                :left-text="leftArrow ? leftText : ''"
                :left-arrow="leftArrow"
                :fixed="fixed"
                @click-left="handlerToBack"
        >

            <e-icon v-show="!isEntry" slot="left" type="back"/>

        </van-nav-bar>


        <div class="eye-viewport__body"
             :class="[hasHeader && !nativeHeader && fixed ? 'eye-viewport__fixed' : '',
                      hasTabBar ? 'eye-viewport__tabbar' : '']">

            <van-pull-refresh :disabled="!isSupportPullRefresh"
                              v-model="isPullLoading"
                              @refresh="handlerToRefresh">
                <slot/>

            </van-pull-refresh>

            <van-tabbar v-if="hasTabBar"
                        v-model="selectTabBarIndex"
                        :style="{backgroundColor:configTabBar.backgroundColor,color:configTabBar.color}">

                <van-tabbar-item v-for="(v,i) in configTabBar.list"
                                 :key="i"
                                 :style="[
                                 selectTabBarIndex == i ? {backgroundColor:configTabBar.selectedBackgroundColor,color:configTabBar.selectedColor} : undefined]"
                                 :to="v.path">
                    <span>{{v.text}}</span>
                    <img
                            slot="icon"
                            :src="selectTabBarIndex == i ? v.selectedIconPath : v.iconPath"
                    />
                </van-tabbar-item>

            </van-tabbar>

        </div>

    </section>

</template>

<script type="text/babel">

  import  { Component,Core }  from 'eye-core';

  import scroll from 'vant/lib/utils/scroll';
  import {on, off} from 'vant/lib/utils/event';
  import util from '../../../src/utils/util'

  export default Component({

    name: 'EViewport',

    model: {
      prop: 'loading'
    },

    props: {

      finished: Boolean,

      fixed: {
        type: Boolean,
        default: true
      },

      hasHeader: {
        type: Boolean,
        default: true
      },

      offset: {
        type: Number,
        default: 30
      }
    },

    data() {
      return {
        title: '',
        leftArrow: false,
        loading: false,
        leftText: '',
        count: 0,
        isPullLoading: false,

        configTabBar: {},

        isEntry: true,

        hasTabBar: false,

        selectTabBarIndex: 0,

        nativeHeader: false // 使用原生的header，在微信和app环境下是true

        //isSupportPullRefresh:false,
      };
    },

    computed: {

      /**
       * 是否支持下拉刷新
       *
       * @returns {*|boolean}
       */
      isSupportPullRefresh() {
        const pageCtx = this.$rm.getCurrentPage();
        return pageCtx && Core._.isFunction(pageCtx.$onPullDownRefresh);
      },
    },

    onInit() {
      const { $config } = this;

      //const { isEntry } = $meta;
      const isEntry = false;

      const selectTabBarIndex = this.getTabBarIndex();

      this.hasTabBar = this.selectTabBarIndex != -1;
      this.isEntry = this.hasTabBar || isEntry;
      this.selectTabBarIndex = selectTabBarIndex;
      this.configTabBar = this.isEntry ? $config.tabBar : null;

      this.scroller = scroll.getScrollEventTarget(this.$el);
      this.pageCtx = this.$rm.getCurrentPage();
      this.bindScroll(true);

      this.setTitle();
    },

    onEntry() {
      this.selectTabBarIndex = this.getTabBarIndex();
      this.pageCtx = this.$rm.getCurrentPage();
      this.bindScroll(true);

      this.setTitle();
    },

    onHide() {
      this.bindScroll(false);
    },

    methods: {
      setTitle() {
          // 设置title

        const {title, meta} = this.$meta;
        this.title = title;
        document.title = title; // 在微信浏览器中，只会显示网页的title

        if (util.isWechat() || util.isQQ()) {
          this.nativeHeader = true;
        } else if (util.isApp()) {
          this.nativeHeader = true;
          this.$app.setTitle({
            show: 1,
            titleStr: title,
            share: meta && meta.share ? 1 : 0,
            shareStr: '',
            more: 0,
            search: 0,
            searchUrl: '',
            report: 0,
            deleteFCDynamic: 0
          });
        }
      },

      getTabBarIndex() {
          let list = this.$config.tabBar ? this.$config.tabBar.list : [];
          let path = this.$route.path;
          return Core.array.indexAt(list,path,'path');
      },

      handlerToBack() {
        0 === arguments.length ? history.back() : this.handlerToView.apply(this, arguments);
      },

      handlerToView() {},

      handlerToHome() {

      },

      doSupport(m, args = []) {
        const pageCtx = this.$rm.getCurrentPage();
        let _isSupport = false;
        let _results = false;
        return pageCtx && (_isSupport = Core._.isFunction(pageCtx[m])),
        _isSupport && (_results = pageCtx[m].apply(pageCtx, args),
          _results = _results instanceof Promise ? _results : Promise.resolve()),
          _results;
      },

      handlerToRefresh() {
        if (this.doSupport('$onPullDownRefresh')) {
          setTimeout(() => {
            this.isPullLoading = false;
          }, 500);
        }
      },

      handlerOnScroll() {
        const {scroller} = this;

        const el = this.$el;
        const scrollerHeight = scroll.getVisibleHeight(scroller);

        if (!scrollerHeight || scroll.getComputedStyle(el).display === 'none') {
          return;
        }

        const scrollTop = scroll.getScrollTop(scroller);

        this.pageOnScroll(scrollTop, scrollerHeight);
        this.reachBottomToScroll(scrollTop, scrollerHeight);

      },

      pageOnScroll(scrollTop, scrollerHeight) {
        this.doSupport('$onPageScroll', [scrollTop, scrollerHeight]);
      },

      reachBottomToScroll(scrollTop, scrollerHeight) {

        if (this.loading) {
          return;
        }

        const {scroller, pageCtx} = this;

        const el = this.$el;
        const targetBottom = scrollTop + scrollerHeight;
        let reachBottom = false;

        /* istanbul ignore next */
        if (el === scroller) {
          reachBottom = scroller.scrollHeight - targetBottom < this.offset;
        } else {

          const elTop = scroll.getElementTop(el);
          const scrollerTop = scroll.getElementTop(scroller);
          const visibleHeight = scroll.getVisibleHeight(el);
          const elBottom = elTop - scrollerTop + visibleHeight;
          reachBottom = elBottom - scrollerHeight < this.offset;
          //console.log('elBottom',elBottom,scrollerTop,scrollTop,visibleHeight,'targetBottom',scrollerHeight)
        }

        /* istanbul ignore else */
        if (reachBottom) {
          this.$emit('input', true);
          let promise = this.doSupport('$onReachBottom', [scrollTop, scrollerHeight]);
          promise && promise.then(() => {
            this.$emit('input', false);
          });

        }
      },

      bindScroll(bind) {
        if (this.binded !== bind) {
          this.binded = bind;
          (bind ? on : off)(this.scroller, 'scroll', this.handlerOnScroll);
        }
      }

    }

  });

</script>




