<template>
  <div>
    <div class="mx-2 mb-6" v-for="item in basicData" :key="item.type">
      <DescCard
        :icon="item.icon"
        :title="item.title"
        :type="item.type"
        :data="item.data"
        @icon="callIcon"
        :id="info.id"
      />
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import DescCard from '/@/components/XTCard/src/DescCard.vue';
  import { BasicData } from './data';
  import { onMounted } from 'vue';
  import { useModal } from '/@/components/Modal';
  import FormModal from './FormModal.vue';
  import { archivesPatientBasicDetail } from '/@/api/biz/archives/patientBasicApi';
  import { archivesVascularAccessQueryCurrent } from '/@/api/biz/archives/vascularAccessApi';
  import {
    archivesDiagnosisHistoryQueryListSingle,
    archivesDiagnosisHistoryQueryListMulti,
  } from '@/api/biz/archives/diagnosisHistoryApi';
  import { listDictModelBatch } from '/@/api/common';
  import { formatDictColor, formatDictFontColor, formatDictTags, formatDictValue } from '/@/utils';
  import dayjs from 'dayjs';
  import { nanoid } from 'nanoid';
  import { DiagnosisEnum } from '../diagnosisHistory/data';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    } as any,
  });
  const bizDictOptions = reactive({
    gender: [],
    cardType: [],
    bloodType: [],
    type: [],
    infectiousDiseases: [],
    accessType: [],
  });
  const bizDictData = ref([
    { key: 'gender', dictCode: 'pb_sex' },
    { key: 'cardType', dictCode: 'pb_card' },
    { key: 'bloodType', dictCode: 'pb_blood' },
    { key: 'type', dictCode: 'pb_type' },
    { key: 'infectiousDiseases', dictCode: 'pb_epidemic' },
    { key: 'accessType', dictCode: 'va_type' },
    { key: 'dt', dictCode: 'dt' },
    { key: 'allergic', dictCode: 'allergic' },
    { key: 'allergic_food', dictCode: 'allergic_food' },
    { key: 'allergic_touch', dictCode: 'allergic_touch' },
    { key: 'allergic_air', dictCode: 'allergic_air' },
    { key: 'allergic_inject', dictCode: 'allergic_inject' },
    { key: 'contagious_status', dictCode: 'contagious_status' },
    { key: 'pb_epidemic', dictCode: 'pb_epidemic' },
    { key: 'complications', dictCode: 'complications' },
    { key: 'complications_breath', dictCode: 'complications_breath' },
    { key: 'complications_blood', dictCode: 'complications_blood' },
    { key: 'complications_incretion', dictCode: 'complications_incretion' },
    { key: 'clinic', dictCode: 'clinic' },
    { key: 'clinic_breath', dictCode: 'clinic_breath' },
    { key: 'clinic_heart', dictCode: 'clinic_heart' },
    { key: 'clinic_blood', dictCode: 'clinic_blood' },
    { key: 'clinic_hbgr', dictCode: 'clinic_hbgr' },
    { key: 'pathological', dictCode: 'pathological' },
    { key: 'pathological_breath', dictCode: 'pathological_breath' },
    { key: 'pathological_heart', dictCode: 'pathological_heart' },
    { key: 'pathological_blood', dictCode: 'pathological_blood' },
    { key: 'pathological_hbgr', dictCode: 'pathological_hbgr' },
    { key: 'ckd', dictCode: 'ckd' },
    { key: 'ckd_breath', dictCode: 'ckd_breath' },
    { key: 'ckd_heart', dictCode: 'ckd_heart' },
    { key: 'ckd_blood', dictCode: 'ckd_blood' },
    { key: 'ckd_hbgr', dictCode: 'ckd_hbgr' },
  ]);
  onMounted(async () => {
    const res = await listDictModelBatch(bizDictData.value.map(ele => ele.dictCode));
    for (const i in res) {
      const filter = bizDictData.value.filter(ele => ele.dictCode == i)[0];
      bizDictOptions[filter.key] = res[i];
    }
    await getData();
  });
  const [registerModal, { openModal }] = useModal();
  const basicData = ref(BasicData);
  // 获取数据
  async function getData() {
    const res = await archivesPatientBasicDetail(props.info?.id);
    basicData.value[0].data = basicData.value[0].data.map(ele => {
      if (ele.dict) {
        ele.value = formatDictValue(bizDictOptions[ele.field], res[ele.field]);
      } else {
        ele.value = res[ele.field];
      }
      if (ele.dictField) {
        ele[ele.dictField] = formatDictValue(bizDictOptions[ele.dictName], res[ele.dictName]);
      }
      if (Array.isArray(ele.tags)) {
        if (res[ele.field]?.length) {
          const value = res[ele.field].map(v => {
            return {
              value: v,
            };
          });
          ele.tags = formatDictTags(bizDictOptions[ele.field], value);
          ele.value = ele.hiddenValue ? '' : res[ele.field];
        }
      }

      // if (ele.field == 'age') {
      //   ele.value = dayjs().diff(res['birthday'], 'year') || 1;
      // }
      if (ele.field == 'birthday') {
        ele.value = dayjs(res['birthday']).format('YYYY-MM-DD');
      }
      return ele;
    });
    console.log(
      '🚀 ~ file: index.vue:127 ~ getData ~ basicData.value[0].data:',
      basicData.value[0].data,
    );

    const vascularAccessRes = await archivesVascularAccessQueryCurrent(props.info?.id);
    basicData.value[1].data =
      (vascularAccessRes &&
        basicData.value[1].data.map(ele => {
          if (ele.field == 'type') {
            ele.value = formatDictValue(bizDictOptions['accessType'], vascularAccessRes[ele.field]);
          } else {
            ele.value = vascularAccessRes[ele.field];
          }
          return ele;
        })) ||
      [];
    basicData.value[2].data = [];
    // 诊断记录
    const DiagnosisHistoryMulti = await archivesDiagnosisHistoryQueryListMulti(props.info?.id);
    console.log(
      '🚀 ~ file: index.vue:158 ~ getData ~ DiagnosisHistoryMulti:',
      DiagnosisHistoryMulti,
    );
    // basicData.value[2].data =
    //   (DiagnosisHistoryMulti &&
    //     basicData.value[2].data.map(ele => {
    //       const detail = DiagnosisHistoryMulti[ele.field][0];
    //       console.log('detail', ele.field, detail);
    //       // const content = detail['multiContent'][0];
    //       detail['multiContent'].forEach(content => {
    //         if (detail.type == 'elseRemark') {
    //           ele.value = content['remark'];
    //           // ele.span = 12;
    //           ele.field = 'elseRemark';
    //           ele.title = '其他诊断';
    //           return ele;
    //         }
    //         if (!content.type) {
    //           return ele;
    //         }
    //         ele.value = formatDictValue(bizDictOptions[detail.type], content['type']);
    //         ele.tags = content.multiName.map(mEle => {
    //           return {
    //             id: nanoid(),
    //             label: formatDictValue(bizDictOptions[content.type], mEle),
    //             fontColor: formatDictFontColor(bizDictOptions[detail.type], content.type),
    //             bgColor: formatDictColor(bizDictOptions[detail.type], content.type),
    //           };
    //         });
    //         // ele.span = 12;
    //         return ele;
    //       });
    //     })) ||
    //   [];
    // const mapData = [];
    for (const i in DiagnosisHistoryMulti) {
      // console.log('🚀 ~ file: index.vue:178 ~ getData ~  i:', i);
      getDiagnosisMulti(DiagnosisHistoryMulti[i], i);
    }
    const firstDialysisRes = await archivesDiagnosisHistoryQueryListSingle(props.info?.id);
    const firstDialysisResContent = firstDialysisRes.firstDialysis?.content[0];
    basicData.value[2].data.unshift({
      field: 'first',
      label: '首次透析',
      value: firstDialysisResContent?.recordTime
        ? dayjs(firstDialysisResContent?.recordTime).format('YYYY-MM-DD')
        : '',
      tags: [
        {
          id: nanoid(5),
          label: formatDictValue(bizDictOptions['dt'], firstDialysisResContent?.contentType),
          type: 'success',
        },
      ],
    });
  }

  function getDiagnosisMulti(data, field) {
    if (data && data.length) {
      data.forEach(detail => {
        detail['multiContent'].forEach(content => {
          const obj = {} as any;
          obj.field = field + '_field';
          obj.label = DiagnosisEnum[field];

          if (field == DiagnosisEnum.elseRemark_field) {
            obj.value = content['remark'];
          } else {
            if (!content.type) return;
            obj.value = formatDictValue(bizDictOptions[detail.type], content['type']);
            obj.tags = content.multiName.map(mEle => {
              return {
                id: nanoid(),
                label: formatDictValue(bizDictOptions[content.type], mEle),
                fontColor: formatDictFontColor(bizDictOptions[detail.type], content.type),
                bgColor: formatDictColor(bizDictOptions[detail.type], content.type),
              };
            });
          }
          // obj.span = 12;
          basicData.value[2].data.push(obj);
        });
      });
    }
  }
  // 回调
  function callIcon(data) {
    console.log('🚀 ~ file: index.vue:16 ~ callIcon ~ data:', data);
    openModal(true, {
      isUpdate: true,
      record: data,
    });
  }

  async function callSuccess(data) {
    console.log('🚀 ~ file: index.vue:39 ~ handleSuccess ~ data:', data);
    await getData();
  }
</script>

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