<template>
  <div class="h-full w-full flex">
    <div class="h-full p-4">
      <div
        class="h-full bg-white p-4 rounded shadow border border-solid border-gray-200"
      >
        <component
          :is="gender != '女' ? bodyManImg : bodyWomanImg"
          class="w-auto h-full"
        ></component>
      </div>
    </div>
    <div class="flex-1 h-full overflow-y-auto p-4 pl-0">
      <div
        class="bg-white border border-solid border-gray-200 shadow p-2 rounded mb-4"
      >
        <div class="p-2 font-bold">时间线</div>
        <div class="overflow-x-auto">
          <table class="min-w-full">
            <tr class="border-b border-solid border-gray-200">
              <td class="whitespace-nowrap p-2">家族史</td>
              <td
                v-if="timeline && timeline[0]"
                :colspan="Object.keys(timeline[0]?.list).length"
                class="p-2 py-4"
              >
                <el-tag
                  v-for="(item, index) in portrait.find(v => v.sort == 6)
                    ?.list || []"
                  :key="index"
                  class="mr-2 text-sm"
                  type="danger"
                  >{{ item.label }}：{{ item.value }}</el-tag
                >
              </td>
            </tr>
            <tr
              v-for="(item, index) in timeline"
              :key="index"
              class="border-b border-solid border-gray-200"
            >
              <td class="whitespace-nowrap p-2 py-3 pr-4">{{ item.label }}</td>
              <td
                v-for="(time, timeIdx) in item.list"
                :key="timeIdx"
                class="px-2 py-4"
                :class="{
                  'dotted-column': time?.length
                }"
              >
                <div v-if="time?.length" class="space-y-2">
                  <div
                    v-for="(sub, subIdx) in time"
                    :key="subIdx"
                    class="whitespace-nowrap"
                  >
                    <span>{{ sub.label }}</span>
                    <el-tag class="ml-1">
                      <span
                        >{{ sub.startAge
                        }}{{
                          sub.startAge && sub.startAge != "至今" ? "岁" : ""
                        }}</span
                      >
                      <span v-if="sub.startAge && sub.endAge">-</span>
                      <span
                        >{{ sub.endAge
                        }}{{
                          sub.endAge && sub.endAge != "至今" ? "岁" : ""
                        }}</span
                      >
                    </el-tag>
                  </div>
                </div>
              </td>
            </tr>
            <tr class="whitespace-nowrap">
              <td class="p-2"></td>
              <td
                v-for="(item, index) in Object.keys(timeline[0]?.list || [])"
                :key="index"
                class="px-2 py-4 text-sm text-gray-500 text-center"
              >
                {{
                  timeline.find(v => v.list[item]?.length) ? `${item}年` : ""
                }}
              </td>
            </tr>
          </table>
          <el-skeleton v-if="!timeline.length" :rows="5" />
        </div>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div
          v-for="(item, index) in portrait"
          :key="item.sort"
          class="text-sm bg-white border border-solid border-gray-200 shadow p-2 rounded"
        >
          <div class="text-base p-2 font-bold text-gray-800">
            {{ item.label }}
          </div>
          <div
            class="p-2"
            :class="portraitClass[item.sort] || portraitClass.default"
          >
            <template v-if="item.type == 'additionalInfo'">
              <div class="h-[150px] overflow-y-auto">
                <div v-if="additionalInfo" v-html="additionalInfo"></div>
                <div v-else class="text-sm text-gray-500">暂未填写</div>
              </div>
            </template>
            <template v-else-if="item.type == 'etiologies'">
              <div v-if="etiologies.length">
                <el-tag
                  v-for="(child, childIdx) in etiologies"
                  :key="childIdx"
                  class="m-1"
                  type="danger"
                  >{{ child.label }}</el-tag
                >
              </div>
              <div v-else class="text-sm text-gray-500">暂未选择</div>
            </template>
            <template v-else-if="item.type == 'lifeHabit'">
              <div class="max-h-[150px] overflow-auto">
                <component
                  v-if="item.type == 'lifeHabit' && lifeHabitTransferRawJson && HealthArchivesModuleView"
                  :is="HealthArchivesModuleView"
                  :form="lifeHabitFields"
                  :transferRawJson="lifeHabitTransferRawJson"
                  class="text-sm"
                ></component>
              </div>
            </template>
            <div
              v-else
              v-for="(child, childIdx) in item.list"
              :key="childIdx"
              class="flex items-start"
            >
              <div v-if="child.label" class="mr-2 whitespace-nowrap">
                {{ child.label }}:
              </div>
              <div
                class="text-gray-600"
                :class="{
                  'flex flex-wrap': item.sort == 4 || item.sort == 5
                }"
              >
                <template v-if="child.list?.length">
                  <div
                    v-for="(child, childIdx) in child.list"
                    :key="childIdx"
                    class="flex items-start"
                  >
                    <div v-if="child.label" class="mr-2 whitespace-nowrap">
                      {{ child.label }}:
                    </div>
                    <template v-if="Array.isArray(child.value)">
                      <el-tag
                        v-for="(t, tIdx) in child.value"
                        :key="tIdx"
                        :class="{
                          'mr-1 mb-1': item.sort == 4 || item.sort == 5
                        }"
                      >
                        <span class="inline-block align-middle">{{ t }} </span>
                        <QuestionFilled
                          v-if="medicineDetail[child.key]"
                          :key="child.key"
                          class="w-4 ml-2 cursor-pointer inline-block align-middle"
                          @click="openMedicineDetail(child.key)"
                        />
                      </el-tag>
                    </template>
                    <span v-else>{{ child.value }}</span>
                  </div>
                </template>
                <span v-else>{{ child.value }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div  v-if="!portrait.length" class="p-4">
        <el-skeleton :rows="5" />
      </div>
      <div
        v-for="(item, index) in keyIndictorChartData"
        :key="index"
        class="bg-white border border-solid border-gray-200 shadow p-2 rounded mt-4"
      >
        <div class="p-2 font-bold">关键指标-{{ item.name }}</div>
        <div>
          <div v-if="item.isBodyMatter" class="h-64">
            <Chart
              :ref="
                r => {
                  chartRefs[index] = r;
                }
              "
            />
          </div>
          <div v-else class="w-full overflow-x-auto">
            <table class="min-w-full bg-white text-gray-700 table-fixed">
              <tr class="font-bold">
                <td class="border border-solid border-gray-100 p-2"></td>
                <td
                  class="border border-solid border-gray-100 p-2 whitespace-nowrap"
                  v-for="(col, index) in item.list"
                  :key="index"
                >
                  {{ dayjs(col.date * 1000).format("YYYY-MM-DD") }}
                </td>
              </tr>
              <tr>
                <td
                  class="border border-solid border-gray-100 p-2 whitespace-nowrap"
                >
                  {{ item.name }}
                </td>
                <td
                  v-for="(col, colIdx) in item.list"
                  :key="colIdx"
                  class="border border-solid border-gray-100"
                >
                  <div class="p-2 text-sm">
                    <span class="align-middle"
                      >{{ col.value }}
                      {{ col.unit && col.unit != "-" ? col.unit : "" }}
                    </span>
                    <template v-if="col.reference">
                      <el-tooltip>
                        <QuestionFilled
                          class="w-4 h-4 inline align-middle ml-1 cursor-pointer opacity-50"
                        />
                        <template #content>
                          <div class="text-sm">
                            参考范围：{{ col.reference }}
                          </div>
                        </template>
                      </el-tooltip>
                    </template>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="medicineDialogVisible" title="药品知识">
      <div class="flex items-start h-[600px]">
        <div class="h-full w-[200px] overflow-y-auto bg-gray-50 p-2">
          <div
            v-for="(item, index) in medicineDialogDetail.menus"
            :key="index"
            class="flex items-center justify-between cursor-pointer px-2 py-4 hover:bg-gray-100 border-b border-solid border-gray-200 last:border-b-0"
            :class="{
              'text-blue-500': index == medicineDialogDetail.active
            }"
            @click="medicineDialogDetail.active = index"
          >
            <span>{{ item.label }}</span>
            <ArrowRight class="w-4" />
          </div>
        </div>
        <div class="h-full flex-1 overflow-y-auto">
          <div class="whitespace-pre-wrap break-all p-4">
            {{
              medicineDialogDetail.detail[
                medicineDialogDetail.menus[medicineDialogDetail.active].label
              ] || '暂无数据'
            }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  markRaw,
  ref,
  inject,
  onMounted,
  provide,
  defineAsyncComponent,
  nextTick,
  shallowRef
} from "vue";
import { QuestionFilled, ArrowRight } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";

import bodyManImg from "@/assets/body-man.svg?component";
import bodyWomanImg from "@/assets/body-woman.svg?component";
import { request } from "@/utils";
import Chart from "@/components/Chart.vue";

const [route, router] = [useRoute(), useRouter()];

const parentState = inject("parentState");
const getNodes = inject("getNodes");
const getBatchNodeRelationships = inject("getBatchNodeRelationships");

const getFormFieldsSurveyIds = inject("getFormFieldsSurveyIds");
const getSurveyFormByCode = inject("getSurveyFormByCode");
const getFormAnswer = inject("getFormAnswer");
const diseaseMangeNode = inject("diseaseMangeNode");

const HealthArchivesModuleView = defineAsyncComponent(() =>
  import("./HealthArchivesModuleView.vue")
);
const gender = ref();
const portrait = ref([]);
const timeline = ref([]);
const portraitClass = {
  default: "space-y-2",
  1: "grid grid-cols-3 gap-2"
};
const keyIndictorList = ref([]);
const medicineDetail = ref({});
const init = async () => {
  const { data } = await request.get(
    `/archivesService/mechanism/archives/portrait`,
    {
      params: {
        archivesId: route.query.archivesId
      }
    }
  );
  data.list.splice(
    1,
    0,
    {
      label: "主要症状和体征描述",
      type: "additionalInfo",
      sort: 2
    },
    {
      label: "当前病因因素",
      type: "etiologies",
      sort: 3
    }
  );

  portrait.value = data.list;
  timeline.value = data.timeline || [];
  getLifeHabitDetail(data.lifeHabitIds);
  const medicineList =
    portrait.value
      .find(v => v.sort == 5)
      .list.map(v => v.list)
      .flat() || [];

  gender.value =
    portrait.value.find(v => v.sort == 1)?.list.find(v => v.sort == 2)?.value ||
    "男";
  if (medicineList.length) {
    console.log("medicineList", medicineList);
    getMedicineData(medicineList.filter(v => v.key).map(v => v.key));
  }
  const keyIndictor = await getBatchNodeRelationships(
    diseaseMangeNode.value,
    "关键管理指标"
  );
  keyIndictorList.value = keyIndictor.map(v => {
    return {
      id: v.mId,
      label: v.mProperties.name
    };
  });
  getKeyIndictorChartData();
};
const additionalInfo = computed(() => parentState.value.additionalInfo);
const etiologies = computed(() => parentState.value.etiologies);
onMounted(() => {
  init();
});

const lifeHabitFields = ref([])
const lifeHabitTransferRawJson = ref()
const getLifeHabitDetail = async lifeHabitIds => {
  const formFields = await getSurveyFormByCode(lifeHabitIds);
  lifeHabitFields.value = formFields
  const ids = getFormFieldsSurveyIds(formFields);
  if (ids.length) {
    lifeHabitTransferRawJson.value = await getFormAnswer(ids);
    portrait.value.splice(portrait.value.length, 0, {
      label: "生活习惯",
      type: "lifeHabit",
      sort: 9
    });
  }
};

const keyIndictorChartData = ref([]);
const getKeyIndictorChartData = async () => {
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/primaryIndicatorCharts/query",
    {
      archivesId: route.query.archivesId,
      nodeIds: keyIndictorList.value.map(v => v.id),
      dates: [],
      needCharts: true
    }
  );
  keyIndictorChartData.value = data.list;
  nextTick(() => {
    keyIndictorChartData.value.forEach((v, i) => {
      v.isBodyMatter && setOption(chartRefs.value[i], v);
    });
  });
};

const getMedicineData = async ids => {
  if (!ids.length) return
  const data = await getNodes({
    id: ids.join()
  });
  const result = {};
  (data.list || []).forEach(v => {
    result[v.id] = {
      id: v.id,
      ...v.properties
    };
  });
  medicineDetail.value = result;
  console.log("medicineDetail.value", medicineDetail.value);
};
const medicineDialogVisible = ref(false);
const medicineDialogDetail = ref({
  id: "",
  active: 0,
  menus: [
    {
      label: "副作用"
    },
    {
      label: "用药指导"
    },
    {
      label: "功效"
    }
  ],
  detail: {}
});
const openMedicineDetail = id => {
  medicineDialogDetail.value.id = id;
  medicineDialogDetail.value.active = 0;
  medicineDialogDetail.value.menus = (medicineDetail.value[id]?._keys || []).map(v => ({label: v}));
  medicineDialogDetail.value.detail = medicineDetail.value[id];

  medicineDialogVisible.value = true;
  // console.log('medicineDialogDetail.value.menus', medicineDialogDetail.value)
};
const chartRefs = ref([]);
const setOption = (cRef, item) => {
  console.log(cRef, item);
  const opt = {
    title: {
      text: item.name,
      top: "10",
      left: "10"
    },
    grid: {
      left: "5%",
      right: "5%",
      bottom: "20%"
    },
    legend: {
      top: "bottom"
    },
    xAxis: {
      type: "category",
      data: []
    },
    tooltip: {
      formatter(param) {
        return `${param.seriesName}: ${param.value}${param.data?.unit}`;
      }
    },
    yAxis: {
      type: "value",
      axisLine: { show: false },
      axisTick: { show: false }
      // axisLabel: { show: false }
    },
    series: []
  };
  if (item.name == "血压") {
    const arr1 = [];
    const arr2 = [];
    item.list.forEach(v => {
      const val = v.value.split("/");
      arr1.push({
        ...v,
        value: val[0]
      });
      arr2.push({
        ...v,
        value: val[1]
      });
    });

    opt.series = [
      {
        name: "收缩压",
        data: arr1,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      },
      {
        name: "舒张压",
        data: arr2,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      }
    ];
  } else {
    opt.series = [
      {
        name: item.name,
        data: item.list,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      }
    ];
  }
  opt.series.forEach(v => {
    v.data = v.data
      .map(d => {
        const val = /(\d+(\.\d+)?)/.exec(String(d.value));
        if (val) {
          d.value = val[0] || d.value;
        }
        if (isNaN(Number(d.value))) {
          d.value = null;
        }
        return d;
      })
      .filter(d => d.value != null);
  });
  opt.xAxis.data = opt.series[0].data.map(d =>
    dayjs(d.date * 1000).format("YYYY-MM-DD")
  );
  console.log(opt);

  cRef && cRef.setOption(opt);
};
</script>

<style lang="scss" scoped></style>
