import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import { useResizeObserver } from '@vueuse/core';

export default defineComponent({
  name: 'm-sticky',
  props: {
    position: {
      type: String as PropType<'top' | 'bottom'>,
      default: 'top'
    },
    mode: {
      type: String as PropType<'fixed' | 'sticky'>,
      default: 'fixed'
    },
    offsetTop: {
      type: String,
      default: '0px'
    },
    offsetBottom: {
      default: '0px'
    },
    // 变量名
    varName: {
      type: String,
      default: '--header-height'
    }
  },
  emits: ['barHeight'],
  setup(props, { slots, emit }) {
    const forms = reactive({
      divStyle: {} as any,
      heightV: 0,
      sectionStyle: {
        width: '100%',
        height: 'auto',
        left: '0'
      }
    });

    const __initHeight = (height: any) => {
      forms.sectionStyle.height = `${height}px`;
      forms.heightV = height;
      // 设置名称
      document.documentElement.style.setProperty(props.varName, `${height}px`);
      emit('barHeight', height);
    };

    const divRef = ref();
    const div2Ref = ref();
    onMounted(() => {
      if (props.position === 'top') {
        forms.divStyle.top = props.offsetTop || '0px';
      } else {
        forms.divStyle.bottom = props.offsetBottom || '0px';
      }
      try {
        useResizeObserver(divRef.value, (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          if (Math.abs(height - forms.heightV) > 1) {
            setTimeout(() => {
              __initHeight(height);
            }, 10);
          }
        });
      } catch {
        //
      }
    });

    watch(
      () => props.offsetTop,
      () => {
        forms.divStyle.top = props.offsetTop;
      }
    );
    watch(
      () => props.offsetBottom,
      () => {
        forms.divStyle.bottom = props.offsetBottom;
      }
    );
    return () => (
      <div
        style={[forms.sectionStyle]}
        class={props.mode === 'sticky' && styles.sticky}>
        <div
          ref={divRef}
          class={[
            'van-sticky',
            props.mode === 'fixed' ? 'van-sticky--fixed' : ''
          ]}
          style={[forms.divStyle, forms.sectionStyle]}>
          <div ref={div2Ref}>{slots.default && slots.default()}</div>
        </div>
      </div>
    );
  }
});
