<script setup lang="ts">
import type { SimplePulseModel } from '../../@types/pulse';

import { createReusableTemplate, tryOnMounted } from '@vueuse/core';
import { useRequest } from 'alova/client';
import { getPulseAgentMethod } from '@/request/api/pulse.api';

import { getURLSearchParamsByUrl } from '@/tools';

import HandLeft from '@/assets/images/pulse-hand-left.png?url';
import HandRight from '@/assets/images/pulse-hand-right.png?url';
import { useVisitor } from '@/stores';
import { Toast } from '@/platform';

type Props = Partial<SimplePulseModel> & { title?: string; results?: string; disabled?: boolean; simple?: boolean };

const { title = '分析', disabled = false, simple = false, results, ..._report } = defineProps<Props>();
const slots = defineSlots();

const Visitor = useVisitor();
const report = computed(() => (unref(results) ? Object.assign(_report, { results }) : Visitor.pulseReport));

const parseUrl = (value?: string) => {
  const [url, query = ''] = (value ?? report.value?.url)?.split('report.html') ?? [];
  const params = getURLSearchParamsByUrl(query);
  if (url && params.has('appId') && params.has('access_session')) {
    const replace /* 绘制 3D 跨域 */ = () => [
      `https://wx.hzliuzhi.com/mz/hybrid/`,
    ].includes(url) ? 'https://hybrid.reborn-tech.com/' : url;
    return {
      appId: params.get('appId')!!,
      token: params.get('access_session')!!,
      url: `${replace()}report.html#/`,
    };
  }
};

const stringifyUrl = (panel: 'left' | 'right', simple = false, overall = true) => {
  const fragment = overall ? [`overall-${panel}`] : [];
  if (!simple) fragment.push(`${panel}-hand`);

  if (!fragment.length) return '';

  const value = fragment.map((value) => `${value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())}=true`).join('&');
  return `${agent.value!.url}single?appId=${agent.value!.appId}&access_session=${agent.value!.token}&mid=${report.value?.measureId}&${value}`;
};

const { data: agent, loading, send: getPulseAgent } = useRequest(() => getPulseAgentMethod(), {
  initialData: parseUrl(report.value?.url),
  immediate: false,
});

const card = useTemplateRef('card');
const panelConfig = reactive({
  height: 0,
  anchors: [0],
});
const offset = computed(() => panelConfig.anchors[panelConfig.anchors.length - 1] - panelConfig.height);
const getHeightAndScrollTop = () => {
  const el = card.value;
  if (!el) return;
  el.scrollIntoView({ behavior: 'instant', block: 'start' });
  const rect = el.getBoundingClientRect();
  const maxHeight = window.innerHeight - rect.top;
  const height = maxHeight - rect.height;
  panelConfig.anchors = [0, height, maxHeight];
  panelConfig.height = height;
};

const preview = reactive({
  clickMainPanelPreviewable: true,
  leftUrl: void 0 as string | void,
  rightUrl: void 0 as string | void,
  leftPanelUrl: void 0 as string | void,
  rightPanelUrl: void 0 as string | void,
  showLeftPanel: false,
  showRightPanel: false,
});

const load = async (panel: 'left' | 'right' | boolean = true, simple = false) => {
  if (loading.value) return;

  if (!agent.value) {
    try {
      if (__FORBID_AUTO_PROCESS_PULSE_AGENCY__) throw { _: `禁止从设备中获取代理地址` };
      const { promise, ...resolvers } = Promise.withResolvers<string>();
      await window.bridge.postMessage('pulse:url:get', report.value?.measureId, resolvers);
      agent.value = parseUrl(await promise);
    } catch (e: any) {
      if (e._) console.info(`log: ${e._}`);
      agent.value = await getPulseAgent().catch(() => void 0);
    }
  }

  if (!agent.value) return;

  if (panel === false) {
    preview.leftUrl ??= stringifyUrl('left', simple);
    preview.rightUrl ??= stringifyUrl('right', simple);
  } else {
    if (!slots.exception) {
      preview.leftPanelUrl = void 0;
      preview.rightPanelUrl = void 0;
    }
    await nextTick();
    if (panel === true || panel === 'left') {
      preview.leftPanelUrl ??= stringifyUrl('left', simple);
      preview.showLeftPanel = true;
    } else {
      preview.showLeftPanel = false;
    }

    if (panel === true || panel === 'right') {
      preview.rightPanelUrl ??= stringifyUrl('right', simple);
      preview.showRightPanel = true;
    } else {
      preview.showRightPanel = false;
    }
  }
};

const panelWrapperRef = useTemplateRef('panel-wrapper-ref');
const open = async (panel?: 'left' | 'right', scroll = true) => {
  if (disabled) return;

  toast = Toast.loading(500);
  await load(panel);
  if (scroll) {
    const last = panelConfig.height;
    getHeightAndScrollTop();
    if (last === panelConfig.height) {
      const el = panelWrapperRef.value?.$el?.querySelector(`.van-floating-panel__content`);
      el.scroll({ top: 0, behavior: 'smooth' });
      console.log(panelWrapperRef.value.$el);
    }
  } else {
    const height = window.innerHeight * 0.8;
    panelConfig.anchors = [0, height];
    panelConfig.height = height;
  }
};

let toast;
function iframeLoaded() {
  toast?.close();
}

tryOnMounted(() => {
  if (!slots.exception) load(false, simple);
  preview.clickMainPanelPreviewable = !!slots.exception;
});

const { define: PreviewSlot, reuse: ReusePreview } = createReusableTemplate<{ src: string | void }>();

watchPostEffect(() => {
  if (panelConfig.height === 0) {
    preview.showLeftPanel = false;
    preview.showRightPanel = false;
  }
});
</script>

<template>
  <van-skeleton class="analysis" :row="5" :loading="report?.results == null" v-if="report?.results !== ''">
    <PreviewSlot v-slot="{ src }">
      <iframe v-if="src" :src="src" :class="{ simple: !src.includes('Hand=true') }" @load="iframeLoaded()"></iframe>
    </PreviewSlot>
    <slot>
      <div ref="card" class="card m-6 text-lg" @click="panelConfig.height = 0">
        <div v-if="title" class="card__title mb-3 text-primary text-2xl font-bold">{{ title }}</div>
        <slot name="content" :report="report">
          <div class="card__content">
            <div v-if="report?.summaryLabel" class="flex justify-evenly">
              <div v-if="report?.summaryLabel?.left" class="part flex flex-row-reverse justify-center" @click.stop="preview.clickMainPanelPreviewable && open('left')">
                <img style="width: 100px; height: 200px" :src="HandLeft" alt="左手" />
                <div class="flex flex-col justify-evenly translate-y-2 h-40 text-xl" :class="{ highlight: preview.showLeftPanel }">
                  <div>寸：<span style="letter-spacing: 4px">{{ report.summaryLabel.left.cun }}</span></div>
                  <div>关：<span style="letter-spacing: 4px">{{ report.summaryLabel.left.guan }}</span></div>
                  <div>尺：<span style="letter-spacing: 4px">{{ report.summaryLabel.left.chi }}</span>
                  </div>
                </div>
                <div v-if="!disabled && preview.clickMainPanelPreviewable" class="absolute bottom-2 text-primary text-sm">查看脉象详情</div>
              </div>
              <div v-if="report?.summaryLabel?.right" class="part flex justify-center" @click.stop="preview.clickMainPanelPreviewable && open('right')">
                <img style="width: 100px; height: 200px" :src="HandRight" alt="右手" />
                <div class="flex flex-col justify-evenly translate-y-2 h-40 text-xl" :class="{ highlight: preview.showRightPanel }">
                  <div>寸：<span style="letter-spacing: 4px">{{ report.summaryLabel.right.cun }}</span></div>
                  <div>关：<span style="letter-spacing: 4px">{{ report.summaryLabel.right.guan }}</span></div>
                  <div>尺：<span style="letter-spacing: 4px">{{ report.summaryLabel.right.chi }}</span></div>
                </div>
                <div v-if="!disabled && preview.clickMainPanelPreviewable" class="absolute bottom-2 text-primary text-sm">查看脉象详情</div>
              </div>
            </div>
            <p v-if="report?.results" class="text-2xl text-center" @click.stop="preview.clickMainPanelPreviewable && open()">
              总体脉象：<span class="text-primary-400" style="letter-spacing: 4px">{{ report.results }}</span>
            </p>
          </div>
        </slot>
      </div>
      <slot name="exception">
        <div v-if="agent" class="grid grid-rows-1 grid-cols-1 gap-8 m-6">
          <div class="card text-lg" v-if="report?.summaryLabel?.left" @click="panelConfig.height = 0">
            <div class="card__title mb-3 text-primary text-2xl font-bold flex justify-between" @click.stop="simple && open('left', false)">
              <div>左手脉象: {{ report.summaryLabel.left.summary?.join('、') }}</div>
              <van-icon v-if="simple" class="text-xl" name="arrow" />
            </div>
            <div class="card__content">
              <ReusePreview v-if="panelConfig.height < 100" :src="preview.leftUrl"></ReusePreview>
            </div>
          </div>
          <div class="card text-lg" v-if="report?.summaryLabel?.right" @click="panelConfig.height = 0">
            <div class="card__title mb-3 text-primary text-2xl font-bold flex justify-between" @click.stop="simple && open('right', false)">
              <div>右手脉象: {{ report.summaryLabel.right.summary?.join('、') }}</div>
              <van-icon v-if="simple" class="text-xl" name="arrow" />
            </div>
            <div class="card__content">
              <ReusePreview v-if="panelConfig.height < 100" :src="preview.rightUrl"></ReusePreview>
            </div>
          </div>
        </div>
      </slot>
    </slot>
    <van-floating-panel ref="panel-wrapper-ref" class="pulse-info-panel" :content-draggable="false" :lock-scroll="true" :anchors="panelConfig.anchors" v-model:height="panelConfig.height">
      <template #header>
        <div class="van-floating-panel__header !justify-between">
          <div></div>
          <div class="van-floating-panel__header-bar"></div>
          <van-icon class="pr-2" name="cross" @click="panelConfig.height = 0" />
        </div>
      </template>
      <div class="area" :class="{ last: !preview.showRightPanel }" v-if="preview.showLeftPanel && report?.summaryLabel?.left">
        <div class="title">左手脉象: {{ report.summaryLabel.left.summary?.join('、') }}</div>
        <ReusePreview :src="preview.leftPanelUrl"></ReusePreview>
      </div>
      <div class="area" v-if="preview.showRightPanel && report?.summaryLabel?.right">
        <div class="title">右手脉象: {{ report.summaryLabel.right.summary?.join('、') }}</div>
        <ReusePreview :src="preview.rightPanelUrl"></ReusePreview>
      </div>
    </van-floating-panel>
  </van-skeleton>
</template>

<style scoped lang="scss">
.part {
  position: relative;
  width: 50%;
}
.highlight {
  color: rgb(52 167 107 / var(--tw-text-opacity, 1));
  & + div {
    opacity: 0.5;
  }
}

$h: 1660px;

iframe {
  width: 100%;
  height: $h;
  border: none;

  &.simple {
    height: 432px;
  }
}

.pulse-info-panel {
  --van-floating-panel-background: #fff;

  .van-icon {
    color: var(--van-floating-panel-bar-color);
  }

  .area {
    margin: auto;
    padding-left: 12px;
    min-width: 320px;
    max-width: 1200px;

    .title {
      padding-left: 9px;
      font-family:
        Helvetica Neue,
        Helvetica,
        Roboto,
        Tahoma,
        Arial,
        PingFang SC,
        sans-serif;
      font-size: 18px;
      font-weight: 700;
      color: #1f2d3d;
      line-height: 36px;
    }

    &:last-of-type,
    &.last {
      iframe {
        height: calc(#{$h} + v-bind(offset) * 1px);
      }
    }
  }
}
</style>