<script setup lang="ts">
import NavHomeSelect     from '@/assets/images/nav-home.select.png?url';
import NavPrint          from '@/assets/images/nav-print.png?url';
import NavScheme         from '@/assets/images/nav-scheme.png?url';

import PhysiqueChart                           from '@/modules/report/PhysiqueChart.vue';
import SyndromeChart                           from '@/modules/report/SyndromeChart.vue';
import { Notify, platformIsAIO, Toast } from '@/platform';
import { getReportMethod, updateReportMethod } from '@/request/api';

import { useRouteParams }         from '@vueuse/router';
import { useRequest, useWatcher } from 'alova/client';

import MiniProgram from '@/components/MiniProgram.vue';
import { useFlowStore, useVisitor } from '@/stores';
const miniProgramRef = useTemplateRef<InstanceType<typeof MiniProgram>>('mini-program');

const hidePulseExceptionTemplate = computed(() => platformIsAIO())

const Visitor = useVisitor();
const id = useRouteParams<string>('id', Visitor.reportId);
const scrollable = ref(true);
const closeable = computed(() => !data.value.payLock || data.value.page.printable || data.value.page.jumpable);
const { data, loading } = useWatcher(() => getReportMethod(id.value), [ id ], {
  initialData: {
    descriptionsTable: { column: [], data: [] },
    tongue: {},
    face: {},
    pulse: {},
  },
  immediate: true,
}).onSuccess(({ data }) => {
  if ( data?.miniProgramURL && data.payLock ) {
    scrollable.value = false;
    nextTick(() => miniProgramRef.value?.open());
  }
  printDisable.value = !(data.reportURL && data.page?.printable);
})

const printDisable = ref(true);
let uploaded: ReturnType<typeof setTimeout>;
const { loading: uploading, send: upload } = useRequest(() => updateReportMethod(id.value, data.value), {
  immediate: false,
  middleware(_, next) {
    if (data.value.reportURL || !data.value.page?.printable) return;
    clearTimeout(uploaded);
    uploaded = setTimeout(() => { uploading.value = true; }, 100);
    const hasConstitutionGroupImg = data.value.constitutionGroupImg;
    const hasFactorItemRadarImg = data.value[ '中医证素' ]?.length ? data.value.factorItemRadarImg : true;
    if ( hasConstitutionGroupImg && hasFactorItemRadarImg ) { next(); }
    else { clearTimeout(uploaded); }
  },
}).onSuccess(({ data: url }) => {
  clearTimeout(uploaded);
  data.value.reportURL = url;
}).onComplete(() => { printDisable.value = false ; });

let ReportPreview: Component;
const reportPreviewProps = reactive({
  show: false,
  title: '',
  url: '',
  mode: '' as 'img' | 'qr',
});
async function print() {
  let url = data.value.reportURL;
  if (!url) url = await upload().catch(() => void 0);
  if (!url) {
    Notify.warning(`未获取到报告地址，请联系管理员或重试`);
    return;
  }

  try {
    try {
      await Bridge.print({ url });
    } catch (e) {
      window.AIO?.print?.(url)
    }
    Toast.success(`开始打印`);
  } catch ( e ) {
    Notify.warning(`打印失败 (${ e.message })`, { duration: 1500 });
    setTimeout(() => {
      ReportPreview = defineAsyncComponent(() => import('./ReportPreview.vue'));
      reportPreviewProps.mode = 'qr';
      reportPreviewProps.title = '扫一扫 获取报告';
      reportPreviewProps.url = url;
      reportPreviewProps.show = true;
    }, 1500);
  }
}

const Flow = useFlowStore();
function toggle() {
  const path = `${Flow.current}/${id.value}/scheme`.replace(/\/{2,}/g, '/') as any
  Flow.router.push(path);
}
</script>
<template>
  <div class="report-wrapper">
    <div class="page-header flex py-4 px-4">
      <div class="grow shrink-0 h-full min-w-16"></div>
      <div class="grow-[3] shrink mx-2 flex flex-col justify-center overflow-hidden">
        <div class="font-bold text-3xl text-nowrap text-center tracking-wide overflow-ellipsis overflow-hidden">
          健康分析报告
        </div>
      </div>
      <div class="grow shrink-0 h-full min-w-16">
        <router-link :to="{ path: '/screen' }" replace>
          <img class="size-8 object-scale-down" :src="NavHomeSelect" alt="返回首页" />
        </router-link>
      </div>
    </div>
    <div class="page-content flex flex-col overflow-hidden">
      <van-skeleton class="flex-auto" title :row="3" :loading>
        <div class="flex-auto" :class="[scrollable ? 'overflow-y-auto' : 'overflow-hidden']">
          <div class="my-6 text-primary text-2xl text-center">报告日期：{{ data.date }}</div>
          <div class="card m-6 text-lg">
            <div class="card__title text-primary text-3xl font-bold"></div>
            <div class="card__content flex">
              <div class="flex-auto">
                <div class="flex items-center my-2">
                  <span class="text-primary">结果显示您是：</span>
                  <van-button class="decorate !text-primary-400">{{ data[ '结果' ] }}</van-button>
                </div>
                <div class="flex items-center my-2" v-if="data[ '程度' ]">
                  <span class="text-grey">程度：</span>
                  <span class="px-4 py-2 rounded-lg border border-primary-400 text-primary">{{ data[ '程度' ] }}</span>
                </div>
                <div class="my-2 text-grey" v-if="data[ '表现' ]">表现：{{ data[ '表现' ] }}</div>
                <div class="my-2 text-grey" v-if="data[ '体质' ]">体质：{{ data[ '体质' ] }}</div>
              </div>
              <div class="flex-none size-48 ml-4">
                <img class="size-full object-cover" src="@/assets/images/report-cover.png" alt="封面">
              </div>
            </div>
          </div>
          <div class="card m-6 text-lg">
            <div class="card__title mb-3 text-primary text-2xl font-bold">体质分析</div>
            <div class="card__content">
              <PhysiqueChart
                :dataset="data['体质图表']"
                v-model:snapshot="data.constitutionGroupImg"
                @update:snapshot="upload()"
              />
              <div class="my-2 text-primary" v-if="data[ '体质描述' ]">{{ data[ '体质描述' ] }}</div>
              <table class="mt-8 mb-2 w-full table-auto border border-collapse  border-primary">
                <thead>
                <tr>
                  <th class="border border-primary min-w-[140px]"
                      v-for="(value, i) in data.descriptionsTable.column" :key="i"
                      v-html="value"
                  ></th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in data.descriptionsTable?.data" :key="item[0]">
                  <td class="py-4 px-2 border border-primary min-w-[140px]"
                      :class="{'text-grey': i, 'text-primary': !i}"
                      v-for="(value, i) in item" :key="i"
                      v-html="value"
                  ></td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
          <AnalysisComponent title="舌象分析" v-bind="data.tongue" :cover="[]"></AnalysisComponent>
          <AnalysisComponent title="面象分析" v-bind="data.face">
            <template #content="{result, cover}">
              <div class="card__content flex">
                <div class="flex-auto text-grey mt-6">{{ result }}</div>
                <div class="flex-none w-2/4 max-h-96 ml-4">
                  <img class="size-full object-scale-down"  v-for="src in cover" :key="src" :src="src" alt="面象">
                </div>
              </div>
            </template>
            <template #exception><div><!--空占位符--></div></template>
          </AnalysisComponent>
          <AnalysisPulseComponent title="脉象分析" v-bind="data.pulse" simple>
            <template #exception v-if="hidePulseExceptionTemplate"><div><!--空占位符--></div></template>
          </AnalysisPulseComponent>
          <div class="card m-6 text-lg" v-if="data['中医证素']?.length">
            <div class="card__title mb-3 text-primary text-2xl font-bold">中医证素</div>
            <div class="card__content">
              <SyndromeChart
                :dataset="data['中医证素']"
                v-model:snapshot="data.factorItemRadarImg"
                @update:snapshot="upload()"
              />
              <table class="mt-8 mb-2 w-full table-auto border border-collapse  border-primary">
                <tbody>
                <tr v-for="item in data['中医证素']" :key="item.label">
                  <td class="py-4 px-2 border border-primary text-primary text-center" v-html="item.label"></td>
                  <td class="py-4 px-2 border border-primary text-grey" v-html="item.value"></td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="card m-6 text-lg" v-if="data['中医证型']?.length">
            <div class="card__title mb-3 text-primary text-2xl font-bold">中医证型</div>
            <div class="card__content">
              <div class="my-6 text-grey" v-for="item in data['中医证型']" :key="item.label">
                <div class="my-2 text-primary" v-html="item.label"></div>
                <div style="text-indent: 2em;" v-html="item.value"></div>
              </div>
            </div>
          </div>
        </div>
      </van-skeleton>
      <div class="flex-none flex justify-between py-2 nav-wrapper" style="background-color: #12312c;">
        <div v-if="data.page?.jumpable && data.scheme" class="m-auto min-w-16 text-center hover:text-primary" @click="toggle()">
          <img class="nav-img" :src="NavScheme" alt="调理方案">
          <div class="mt-2">调理方案</div>
        </div>
        <mini-program ref="mini-program" :url="data.miniProgramURL" :closeable="closeable"></mini-program>
        <div v-if="data.page?.printable" class="m-auto min-w-16 text-center hover:text-primary" :class="{ disabled: printDisable }" @click="!printDisable && print()">
          <van-loading v-if="uploading" color="#38ff6e" style="font-size: 24px;" />
          <img class="nav-img" v-else :src="NavPrint" alt="打印">
          <div class="mt-2">打印</div>
        </div>
      </div>
      <Component :is="ReportPreview" v-bind="reportPreviewProps" v-model:show="reportPreviewProps.show"></Component>
    </div>
  </div>
</template>
<style scoped lang="scss">
.van-button.decorate {
  font-size: 20px;
  height: 62px;
  width: 240px;
  background-size: 80%;
  letter-spacing: 2px;
}

.text-grey {
  color: #e3e3e3;
}

.report-wrapper {
  .panel-content {
    padding: 0 var(--van-floating-panel-header-height) var(--van-floating-panel-header-height);
  }

  .v-enter-active,
  .v-leave-active {
    transition: opacity 0.5s ease;
  }

  .v-enter-from,
  .v-leave-to {
    opacity: 0;
  }
}

.overflow-y-auto {
  overflow-y: auto;
}

.disabled {
  pointer-events:none;
  cursor: not-allowed;
  opacity: 0.6;
}
</style>
<style lang="scss">
.report-wrapper .card {
  padding: 24px;
  border-radius: 24px;
  box-shadow: inset 0 0 80px 0 #34a76b60;
}

.nav-wrapper {
  .nav-img {
    margin: auto;
    width: 36px;
    height: 36px;
    object-fit: scale-down;
  }
}
</style>
