<script setup lang="ts">
import RecordsAnalysisPreview  from '@/components/RecordsAnalysisPreview.vue';
import RecordsIndicatorPreview from '@/components/RecordsIndicatorPreview.vue';
import RecordsPatientPreview   from '@/components/RecordsPatientPreview.vue';
import ReportPreview           from '@/components/ReportPreview.vue';
import ReportSchemePreview     from '@/components/ReportSchemePreview.vue';

import type { PatientModel, ReportModel, ReportSchemeItemModel }        from '@/model';
import { patientMethod, patientTags }                                   from '@/request/api/patient.api';
import { indicatorByPatientIdMethod, reportMethod, reportSchemeMethod } from '@/request/api/report.api';

import PatientCardWidget      from '@/widgets/PatientCardWidget.vue';
import PatientTagWidget       from '@/widgets/PatientTagWidget.vue';
import ReportIndicatorWidget  from '@/widgets/ReportIndicatorWidget.vue';
import ReportSchemeCardWidget from '@/widgets/ReportSchemeCardWidget.vue';
import { useElementSize }     from '@vueuse/core';
import { useWatcher }         from 'alova/client';
import { Button }             from 'ant-design-vue';
import { h }                  from 'vue';
import { VxeUI }              from 'vxe-pc-ui';


const props = defineProps<{
  patient: Partial<PatientModel>;
  report: Partial<ReportModel>;
}>();
const emits = defineEmits<{
  destroy: [];
}>();
const patientId = computed(() => props.patient?.id);
const reportId = computed(() => props.report?.id);
const { data: patient, loading: patientLoading } = useWatcher(
  () => patientMethod(patientId.value!),
  [ () => props.patient?.id ],
  {
    initialData: { ...props.patient }, immediate: true,
    middleware: (_, next) => { if ( patientId.value ) next(); },
  },
);

const { data: tags, loading: tagsLoading, send: loadTags } = useWatcher(
  () => patientTags(patientId.value!),
  [ patientId ],
  {
    initialData: [], immediate: true,
    middleware: (_, next) => { if ( patientId.value ) next(); },
  },
);
const { data: report, loading: reportLoading } = useWatcher(
  () => reportMethod(reportId.value!),
  [ reportId ],
  {
    initialData: { ...props.report }, immediate: true,
    middleware: (_, next) => { if ( reportId.value ) next(); },
  },
);
const { data: scheme, loading: schemeLoading } = useWatcher(
  () => reportSchemeMethod(reportId.value!),
  [ reportId ],
  {
    initialData: {}, immediate: true,
    middleware: (_, next) => { if ( reportId.value ) next(); },
  },
);
const { data: indicator, loading: indicatorLoading } = useWatcher(
  () => indicatorByPatientIdMethod(patientId.value!),
  [ () => props.patient?.id ],
  {
    initialData: [], immediate: true,
    middleware: (_, next) => { if ( patientId.value ) next(); },
  },
);

function openPatientRecordsPreviewHandle() {
  const id = `modal:record-patient:preview`;
  const onDestroy = () => { VxeUI.modal.close(id); };
  onDestroy();
  VxeUI.modal.open({
    id, remember: true,
    showMaximize: true, mask: false, lockView: false, padding: false,
    resize: true, width: Math.floor(window.innerWidth * 0.5), height: Math.floor(window.innerHeight * 0.5),
    escClosable: true, maskClosable: true,
    title: `基础信息更新记录`,
    slots: {
      default() {
        return h(RecordsPatientPreview, {
          patient: patient.value,
          onDestroy,
        });
      },
    },
  });
}

function openAnalysisRecordsPreviewHandle() {
  const id = `modal:record-analysis:preview`;
  const onDestroy = () => { VxeUI.modal.close(id); };
  onDestroy();
  VxeUI.modal.open({
    id, remember: true,
    showMaximize: true, mask: false, lockView: false, padding: false,
    resize: true, width: Math.floor(window.innerWidth * 0.5), height: Math.floor(window.innerHeight * 0.5),
    escClosable: true, maskClosable: true,
    title: `健康状况更新记录`,
    slots: {
      default() {
        return h(RecordsAnalysisPreview, {
          patient: patient.value,
          onDestroy,
        });
      },
    },
  });
}

function openIndicatorRecordsPreviewHandle() {
  const id = `modal:record-indicator:preview`;
  const onDestroy = () => { VxeUI.modal.close(id); };
  onDestroy();
  VxeUI.modal.open({
    id, remember: true,
    showMaximize: true, mask: false, lockView: false, padding: false,
    resize: true, width: Math.floor(window.innerWidth * 0.5), height: Math.floor(window.innerHeight * 0.5),
    escClosable: true, maskClosable: true,
    title: `指标信息更新记录`,
    slots: {
      default() {
        return h(RecordsIndicatorPreview, {
          patient: patient.value,
          onDestroy,
        });
      },
    },
  });
}

function openSchemeItemPreviewHandle(value: ReportSchemeItemModel) {
  const id = `drawer:scheme:preview`;
  const onDestroy = () => { VxeUI.drawer.close(id); };
  onDestroy();
  VxeUI.drawer.open({
    id,
    title: [ value.category, value.name ].filter(Boolean).join(': '),
    maskClosable: true,
    escClosable: true,
    padding: false,
    slots: {
      default() {
        return h(ReportSchemePreview, {
          value,
          onDestroy,
        });
      },
    },
  });
}

const reportType = ref<'analysis' | 'scheme'>('analysis');
const analysisReportPreviewOpening = ref(false);
const schemeReportPreviewOpening = ref(false);

function openReportPreviewHandle(type: 'analysis' | 'scheme') {
  reportType.value = type;
  const id = `drawer:report:preview`;
  const onDestroy = () => { VxeUI.drawer.close(id); };
  VxeUI.drawer.open({
    id,
    maskClosable: true,
    escClosable: true,
    padding: false,
    width: window.innerWidth - 256,
    slots: {
      title() {
        switch ( reportType.value ) {
          case 'analysis':
            return `${ patient.value.name } 的健康分析报告`;
          case 'scheme':
            return `${ patient.value.name } 的调理方案`;
          default:
            return '';
        }
      },
      default() {
        return h(ReportPreview, {
          patient: patient.value,
          report: report.value,
          scheme: scheme.value,
          type: reportType.value,
          'onUpdate:reportId': (value: string) => {},
          'onUpdate:type': (value: 'analysis' | 'scheme') => { reportType.value = value; },
          onDestroy,
        });
      },
      corner() {
        const { next, label } = {
          analysis: { next: 'scheme' as const, label: '调理方案' },
          scheme: { next: 'analysis' as const, label: '健康分析报告' },
        }[ reportType.value ];
        return h(Button, {
            type: 'primary', size: 'small',
            onClick() { reportType.value = next; },
          }, label,
        );
      },
    },
    onHide() {
      VxeUI.modal.close();
      analysisReportPreviewOpening.value = false;
      schemeReportPreviewOpening.value = false;
    },
  });
}

const patientCardRef = ref<HTMLElement>();
const { height } = useElementSize(patientCardRef);
</script>
<template>
  <div id="page-container-scroller" class="page-container flex flex-col">
    <div style="display: flex">
      <PatientCardWidget style="flex: auto" ref="patientCardRef" :dataset="patient" :loading="patientLoading">
        <template #tool-bar>
          <a-button type="primary" size="small" :disabled="!patientId" @click="openPatientRecordsPreviewHandle()">
            更新记录
          </a-button>
        </template>
      </PatientCardWidget>
      <PatientTagWidget
        :style="{height: `${height}px`, minHeight: '112px'}" style="flex: none;width: 256px"
        :dataset="tags" :loading="tagsLoading"
        editable @refresh="loadTags()"
      />
    </div>
    <div class="card report-card" ref="container">
      <div class="card__header sticky flex justify-between items-center">
        <div class="card__title">
          <span>健康状况</span>
          <a-spin v-if="reportLoading" size="small" style="margin-left: 4px;" />
          <a-space style="margin-left: 8px">
            <a-button type="primary" size="small" :disabled="!reportId" @click="openAnalysisRecordsPreviewHandle()">
              更新记录
            </a-button>
          </a-space>
        </div>
      </div>
      <div class="card__content">
        <a-row>
          <a-col :span="12">
            <a-card class="card no-bordered" size="small" style="background-color: #f7f7f7">
              <a-descriptions :column="1">
                <a-descriptions-item v-if="report?.pickedSymptom" label="症状信息">
                  {{ report.pickedSymptom }}
                </a-descriptions-item>
                <a-descriptions-item v-if="report?.algorithmInferSymptom" label="联想症状">
                  {{ report.algorithmInferSymptom }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-space style="margin-left: 8px;">
              <a-image v-if="report?.upImg" :width="200" :height="200" :src="report.upImg" :preview="true" />
              <a-image v-if="report?.downImg" :width="200" :height="200" :src="report.downImg" :preview="true" />
              <a-image v-if="report?.faceImg" :width="200" :height="200" :src="report.faceImg" :preview="true" />
            </a-space>
          </a-col>
        </a-row>
      </div>
    </div>
    <div class="card report-card" ref="container">
      <div class="card__header sticky flex justify-between items-center">
        <div class="card__title">
          <span>健康分析报告</span>
          <a-spin v-if="reportLoading" size="small" style="margin-left: 4px;" />
          <a-space style="margin-left: 8px">
            <a-button
              type="primary" size="small" :disabled="!reportId" :loading="schemeReportPreviewOpening"
              @click="schemeReportPreviewOpening = true; openReportPreviewHandle('analysis');"
            >报告详情
            </a-button>
          </a-space>
        </div>
      </div>
      <div class="card__content">
        <a-row>
          <a-col :span="12">
            <a-card class="card no-bordered" size="small" style="background-color: #f7f7f7">
              <a-descriptions :column="3">
                <a-descriptions-item v-if="report?.willillStateName" label="健康状态">
                  {{ report.willillStateName }}
                </a-descriptions-item>
                <a-descriptions-item v-if="report?.willillDegreeName" label="程度" :span="2">
                  {{ report.willillDegreeName }}
                </a-descriptions-item>
                <a-descriptions-item v-if="report?.willillFunctionName" label="表现">
                  {{ report.willillFunctionName }}
                </a-descriptions-item>
                <a-descriptions-item v-if="report?.constitutionGroupName" label="体质" :span="2">
                  {{ report.constitutionGroupName }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
    <ReportSchemeCardWidget :dataset="scheme" :loading="schemeLoading" :editable="false" />
    <ReportIndicatorWidget :dataset="indicator" :loading="indicatorLoading">
      <template #tool-bar>
        <a-button type="primary" size="small" :disabled="!patientId" @click="openIndicatorRecordsPreviewHandle()">
          更新记录
        </a-button>
      </template>
    </ReportIndicatorWidget>
  </div>
</template>
<style scoped lang="scss">
@import "@/themes/report-card";

.scheme-tag-item {
  margin-right: 0;
  cursor: pointer;

  span:nth-of-type(2)::before {
    content: ":";
    margin-left: 2px;
    margin-right: 4px;
  }
}
</style>
