<style lang="less">
.page-pull-down-animation {
  width: 100%;
  .page-top-pic {
    width: 100%;
    // overflow-x: hidden;
    overflow: hidden;
    image {
      width: 100%;
      height: 100%;
      transition: all 0.1s;
      transform-origin: bottom center;
    }
  }
  .page-content {
    width: 100%;
  }
}
</style>

<template>
  <!-- <div class="page-pull-down-animation" v-on:touchstart="pageTouchStart" v-on:touchmove="pageTouchMove" v-on:touchend="pageTouchEnd"> -->
  <div class="page-pull-down-animation">
    <div class="page-top-pic" :style="{'margin-top': picTop+'rpx', 'height': picHeight+'rpx', 'background-color': bgColor}">
      <image :style="{'transform': 'scale('+picScale+')'}" src="{{pic}}" />
    </div>
    <div class="page-content">
      <slot></slot>
    </div>
  </div>
</template>

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

let pageTouchStartY = 0;
let isPageTouchStart = false;
let picTop = 0;
let picHeight = 0;
wepy.component({
  props: {
    // 顶部图片地址
    pic: String,
    // 图片尺寸-高，单位rpx
    height: Number,
    // 顶部图片超出上边界的距离，单位rpx
    top: Number,
    // 组件id
    elementId: String,
    // 背景颜色
    bgColor: String
  },
  data: {
    picScale: 1,
    picHeight: 0,
    picTop: 0,
    pageContentPaddingTop: 0
  },
  ready() {
    picHeight = Number(this.height || 0);
    if (!this.top && this.top != 0) {
      picTop = -(picHeight / 3);
    } else {
      picTop = Number(this.top);
    }
    this.picTop = picTop;
    this.picHeight = picHeight;
    this.pageContentPaddingTop = picHeight + picTop;
    if(!this.bgColor){
      this.bgColor = "transparent"
    }
  },
  methods: {
    pageTouchStart(e) {
      wx.createSelectorQuery()
        .select('#' + this.elementId)
        .boundingClientRect(function(rect) {
          let top = rect.top;
          if (top >= 0) {
            try {
              let touch = e.touches[0]; //获取第一个触点
              //记录触点初始位置
              pageTouchStartY = Number(touch.pageY); //页面触点Y坐标
              isPageTouchStart = true;
            } catch (err) {
              console.log(err.message);
            }
          }
        })
        .exec();
    },
    pageTouchMove(e) {
      if (!isPageTouchStart) {
        return;
      }
      try {
        let touch = e.touches[0], //获取第一个触点
          y = Number(touch.pageY); //页面触点Y坐标
        let touchLength = (y - pageTouchStartY);
        if (touchLength >= 0) {
          this.picScale = (touchLength * 2 + picHeight) / picHeight;
        } else {
          this.picScale = 1;
        }
      } catch (err) {
        console.log(err.message);
      }
    },
    pageTouchEnd(e) {
      isPageTouchStart = false;
      this.picScale = 1;
    }
  }
});
</script>