<script setup lang="ts">
import NavMiniProgram from '@/assets/images/mini-program.svg?url';
import { Notify } from '@/platform';

const props = defineProps<{ url?: string; closeable?: boolean; forcedShow?: boolean }>();

const panelHeight = ref(0);
const panelProps = reactive({
  anchors: [0, window.innerWidth],
  contentDraggable: false,
  lockScroll: true,
});
const showOverlay = computed(() => panelHeight.value >= panelProps.anchors[0] && panelHeight.value > 0)

watchEffect(() => {
  panelProps.anchors[0] = props.closeable ? 0 : 100;
});

const handle = () => {
  if (!props.url) {
    Notify.warning(`未获取到小程序地址，请联系管理员或重试`);
    return;
  }
  panelOpen();
};

const panelOpen = (min?: number) => {
  if (min) panelProps.anchors[0] = min;
  panelHeight.value = panelProps.anchors[1];
};

defineExpose({
  open: handle,
});
</script>

<template>
  <div class="nav m-auto min-w-16 text-center hover:text-primary" v-if="url || props.forcedShow" @click="handle()">
    <img class="nav-img" :src="NavMiniProgram" alt="小程序" />
    <div class="mt-2">小程序</div>
  </div>
  <van-overlay :show="showOverlay" class="panel-mask"></van-overlay>
  <van-floating-panel v-model:height="panelHeight" v-bind="panelProps">
    <template #header>
      <div class="van-floating-panel__header !justify-between">
        <div></div>
        <div class="van-floating-panel__header-bar"></div>
        <div>
          <van-icon v-if="props.closeable" name="cross" @click.stop="panelHeight = panelProps.anchors[0]" />
        </div>
      </div>
    </template>
    <Transition>
      <div class="panel-content">
        <img class="size-full object-contain" v-if="panelHeight === panelProps.anchors[1] || panelHeight > panelProps.anchors[0] * 1.5" :src="url" alt="小程序码" />
        <div class="flex justify-center items-center" v-else @click="panelOpen()">
          <img class="h-10 w-10" src="@/assets/images/mini-program.svg" alt="小程序" />
          <span class="text-lg ml-2">小程序</span>
        </div>
      </div>
    </Transition>
  </van-floating-panel>
</template>

<style scoped lang="scss">
.nav-img {
  margin: auto;
  width: 36px;
  height: 36px;
  object-fit: scale-down;
}

.panel-mask {
  --van-overlay-background: transparent;
}

.panel-content {
  padding: 0 var(--van-floating-panel-header-height) var(--van-floating-panel-header-height);
}
</style>
