import { postMessage } from '@/helpers/native-message';
import { browser } from '@/helpers/utils';
import { NavBar } from 'vant';
import { defineComponent, onMounted, reactive, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import styles from './index.module.less';

export default defineComponent({
  name: 'm-header',
  props: {
    title: {
      type: String,
      default: ''
    },
    isBack: {
      type: Boolean,
      default: true
    },
    border: {
      type: Boolean,
      default: false
    },
    isFixed: {
      type: Boolean,
      default: true
    },
    styleName: {
      type: Object,
      default: () => ({})
    },
    background: {
      type: String,
      default: 'white'
    },
    color: {
      type: String,
      default: '#323233'
    },
    rightText: {
      type: String,
      default: ''
    }
  },
  emits: ['rightClick'],
  setup(props, { emit, slots }) {
    const route = useRoute();
    const router = useRouter();
    const forms = reactive({
      title: '',
      navBarHeight: 0 // 顶部高度
    });

    const onClickLeft = () => {
      if (browser().isApp) {
        postMessage({
          api: 'goBack'
        });
      } else {
        router.back();
      }
    };
    const onClickRight = () => {
      emit('rightClick');
    };

    onMounted(() => {
      forms.title = props.title || (route.meta.title as string);
    });

    watch(
      () => props.title,
      () => {
        forms.title = props.title || (route.meta.title as string);
      }
    );
    return () => (
      <>
        {slots.content ? (
          <div
            style={{
              paddingTop: `${forms.navBarHeight}px`,
              background: props.background
            }}
            class={styles.headerSection}>
            {slots.content(forms.navBarHeight)}
          </div>
        ) : (
          <>
            <div
              style={{
                minHeight: `calc(var(--van-nav-bar-height) + ${forms.navBarHeight}px)`
              }}
              class={styles.headerSection}>
              <NavBar
                title={forms.title}
                class={[styles.colHeader]}
                style={{
                  background: props.background,
                  color: props.color,
                  paddingTop: `${forms.navBarHeight}px`
                }}
                left-arrow={props.isBack}
                rightText={props.rightText}
                fixed={props.isFixed}
                zIndex={2000}
                border={props.border}
                onClickLeft={onClickLeft}
                onClickRight={onClickRight}
                v-slots={{
                  right: () =>
                    (slots.right && slots.right()) || props.rightText,
                  title: () => (slots.title && slots.title()) || forms.title
                }}></NavBar>
            </div>
            {slots.default ? slots.default() : null}
          </>
        )}
      </>
    );
  }
});
