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'
    }
  },
  data() {
    return {
      divStyle: {} as any,
      sectionStyle: {
        width: '100%',
        height: 'auto'
      }
    }
  },
  mounted() {
    if (this.position === 'top') {
      this.divStyle.top = '0px'
    } else {
      this.divStyle.bottom = '0px'
    }

    // nextTick(() => {
    //   const { height } = useRect((this as any).$refs.div)
    //   this.sectionStyle.height = `${height}px`
    // })
    nextTick(() => {
      setTimeout(() => {
        const { height } = useRect((this as any).$refs.div)
        this.sectionStyle.height = `${height}px`
        this.$emit('getHeight', height)
      }, 100)
    })
  },
  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]}
        >
          {this.$slots.default && this.$slots.default()}
        </div>
      </div>
    )
  }
})
