<style lang="less">
  .page-top {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: transparent;
    z-index: 1;

    .page-title {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      height: 48rpx;
      line-height: 48rpx;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
</style>

<template>
  <div class="page-top" :style="{'top': pageTopBarTop + 'px'}">
    <slot></slot>
    <div class="page-title">
      <span v-show="isViewPageTitle" :style="{'color': pageTitleColor}">{{pageTitle}}</span>
    </div>
  </div>
</template>

<script>
  import wepy from '@wepy/core';

  let menuButtonBoundingClientRect;
  wepy.component({
    props: {
      pageTitle: String,
      pageTitleColor: String,
      observeTarget: String
    },
    data: {
      isViewPageTitle: false,
      pageTopBarTop: 0
    },
    ready() {
      menuButtonBoundingClientRect = wx.getMenuButtonBoundingClientRect();
      this.pageTopBarTop =
        menuButtonBoundingClientRect.top +
        menuButtonBoundingClientRect.height / 2;
      this.observePageTitle();
    },
    methods: {
      observePageTitle() {
        let top = menuButtonBoundingClientRect.top + menuButtonBoundingClientRect.bottom + menuButtonBoundingClientRect.height;
        var query = wx.createSelectorQuery();
        query.select(this.observeTarget).boundingClientRect();
        query.exec(res => {
          top -= res[0].height;
          wx.createIntersectionObserver()
            .relativeToViewport({
              top: -top
            })
            .observe(this.observeTarget, res => {
              if (res.intersectionRatio === 0) {
                this.isViewPageTitle = true;
              } else {
                this.isViewPageTitle = false;
              }
            });
        });
      }
    }
  });
</script>