import { useRect } from '@vant/use'
import { defineComponent, nextTick, PropType } from 'vue'
import styles from './index.module.less'

export default defineComponent({
  emits: ['getHeight'],
  name: 'o-sticky',
  props: {
    position: {
      type: String,
      default: 'top' as 'top' | 'bottom'
    },
    background: {
      type: String,
      default: ''
    },
    mode: {
      type: String as PropType<'fixed' | 'sticky'>,
      default: 'fixed'
    },
    offsetTop: {
      type: String,
      default: '0px'
    },
    offsetBottom: {
      default: '0px'
    }
  },
  data() {
    return {
      divStyle: {} as any,
      heightV: 0,
      sectionStyle: {
        width: '100%',
        height: 'auto',
        left: '0'
      }
    }
  },
  mounted() {
    if (this.position === 'top') {
      this.divStyle.top = this.offsetTop || '0px'
    } else {
      this.divStyle.bottom = this.offsetBottom || '0px'
    }

    nextTick(() => {
      // 为了处理刚开始头部高度为0的情况
      const { height } = useRect((this as any).$refs.div)
      this.__initHeight(height)

      setTimeout(() => {
        const { height } = useRect((this as any).$refs.div)
        this.__initHeight(height)
      }, 200)

      // 为了处理头部第一次获取高度不对的问题
      setTimeout(() => {
        const { height } = useRect((this as any).$refs.div2)
        if (height !== this.heightV && this.position === 'top') {
          this.__initHeight(height)
        }
      }, 1000)
    })
  },
  methods: {
    __initHeight(height: any) {
      this.sectionStyle.height = `${height}px`
      this.heightV = height
      this.$emit('getHeight', height)
    }
  },
  watch: {
    offsetTop() {
      this.divStyle.top = this.offsetTop
    },
    offsetBottom() {
      this.divStyle.bottom = this.offsetBottom
    }
  },
  render() {
    return (
      <div style={[this.sectionStyle]} class={this.mode === 'sticky' && styles.sticky}>
        <div
          ref="div"
          class={[
            'van-sticky',
            this.mode === 'fixed' ? 'van-sticky--fixed' : '',
            styles[this.background]
          ]}
          style={[this.divStyle, this.sectionStyle]}
        >
          <div ref="div2">{this.$slots.default && this.$slots.default()}</div>
        </div>
      </div>
    )
  }
})
