<template>
  <div class="mb-4">
    <!-- <DescCard
      id="1"
      icon="icon-xt-add_default"
      title="首次透析"
      type="touxi"
      :data="descData"
      :right="descRight"
      class="mb-4"
    /> -->
    <div v-for="(item, index) in singleData" :key="item.type" class="mb-4">
      <DescCard
        :id="index"
        :icon="item['data'].length ? '' : 'icon-xt-add_default'"
        :title="item['title']"
        :type="item['type']"
        :data="item['data']"
        :right="item['right']"
        @edit="callEdit"
        @delete="callDel"
        @icon="callEdit"
      />
    </div>
    <div v-for="(item, index) in multiData" :key="item.type" class="mb-4">
      <DescMultiCard
        :id="index"
        icon="icon-xt-add_default"
        :title="item['title']"
        :type="item['type']"
        :data="item['data']"
        @edit="callEditMulti"
        @delete="callDel"
        @icon="callIcon"
      />
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { DescCard, DescMultiCard } from '/@/components/XTCard/index';
  import { useModal } from '/@/components/Modal';
  import FormModal from './FormModal.vue';
  import { onMounted, reactive, ref } from 'vue';
  import { formatDictColor, formatDictFontColor, formatDictValue } from '/@/utils';
  import dayjs from 'dayjs';
  import {
    archivesDiagnosisHistoryQueryListSingle,
    archivesDiagnosisHistoryQueryListMulti,
    archivesDiagnosisHistoryMultiRemoveByIds,
  } from '@/api/biz/archives/diagnosisHistoryApi';
  import { listDictModelBatch } from '@/api/common';
  import { DiagnosisEnum } from './data';
  import { nanoid } from 'nanoid';
  import { useUserStore } from '@/store/modules/user';
  import { useMessage } from '@/hooks/web/useMessage';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    } as any,
  });
  const bizDictOptions = reactive<any>({});
  const bizDictData = ref([
    { key: 'gender', dictCode: 'pb_sex' },
    { 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' },
  ]);
  const [registerModal, { openModal }] = useModal();
  const useUser = useUserStore();
  const { createConfirm, createMessage } = useMessage();
  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 singleData = ref({});
  const multiData = ref({});
  const originSingleData = ref({});
  const originMultiData = ref({});

  // const descData = [
  //   {
  //     label: '诊断名称/病史/状态',
  //     value: '乙肝 / 2022-01-19 ～',
  //     tags: [{ id: '12', label: '活动中', type: 'error' }],
  //   },
  //   {
  //     label: '备注',
  //     value: '药物治疗或其他治疗',
  //   },
  //   {
  //     label: '测试',
  //     value: '药物治疗或其他治疗',
  //   },
  //   {
  //     label: '诊断名称/病史/状态备份',
  //     value: '结核 / 2022-02-10 ～ 20',
  //     tags: [
  //       { id: '1', label: '未活动', type: 'muted' },
  //       { id: '2', label: '未活动1', type: 'primary' },
  //     ],
  //   },
  // ];
  // const descRight = {
  //   show: true,
  //   date: '2023-04-23',
  //   doctor: '张医生',
  //   edit: true,
  //   delete: true,
  // };
  // 获取数据
  async function getData() {
    const res = await archivesDiagnosisHistoryQueryListSingle(props.info?.id);
    originSingleData.value = res;
    for (const i in res) {
      // console.log('res ', i, res[i]);
      const detail = [];
      // if (res[i] == null) {
      //   singleData.value[i] = {
      //     title: DiagnosisEnum[i],
      //     data: [],
      //     right: {
      //       show: false,
      //       date: '',
      //       doctor: '',
      //     },
      //     type: i,
      //   };
      //   continue;
      // }
      res[i] &&
        res[i].content.forEach(ele => {
          if (i == DiagnosisEnum.firstDialysis_field) {
            detail.push({
              label: DiagnosisEnum.firstDialysis + '日期/方式',
              value: dayjs(ele.recordTime).format('YYYY-MM-DD'),
              tags: [
                {
                  id: nanoid(),
                  label: formatDictValue(bizDictOptions.dt, ele.contentType),
                  type: 'success',
                  // fontColor: formatDictFontColor(bizDictOptions.dt, ele.contentType),
                  // bgColor: formatDictColor(bizDictOptions.dt, ele.contentType),
                },
              ],
            });
          }
          if (i == DiagnosisEnum.operation_field) {
            detail.push({
              label: DiagnosisEnum.operation + '日期/名称',
              value: dayjs(ele.recordTime).format('YYYY-MM-DD'),
              tags: [
                {
                  id: nanoid(),
                  label: ele.singleName,
                  type: 'muted',
                  // fontColor: formatDictFontColor(bizDictOptions.dt, ele.contentType),
                  // bgColor: formatDictColor(bizDictOptions.dt, ele.contentType),
                },
              ],
            });
            detail.push({
              label: '备注',
              value: ele.remark || '——',
            });
          }
          if (i == DiagnosisEnum.allergic_field) {
            detail.push({
              label: '过敏原/名称',
              value: formatDictValue(bizDictOptions.allergic, ele.contentType),
              tags: ele.multiName.map(mEle => {
                return {
                  id: nanoid(),
                  label: formatDictValue(bizDictOptions[ele.contentType], mEle),
                  // type: 'warning',
                  fontColor: formatDictFontColor(bizDictOptions.allergic, ele.contentType),
                  bgColor: formatDictColor(bizDictOptions.allergic, ele.contentType),
                };
              }),
            });
          }
          if (i == DiagnosisEnum.contagious_field) {
            detail.push({
              label: '诊断名称/病史/状态',
              value: `${formatDictValue(bizDictOptions.pb_epidemic, ele.contentType)}/${dayjs(
                ele.startTime,
              ).format('YYYY-MM-DD')} ~ ${
                ele.endTime ? dayjs(ele.endTime).format('YYYY-MM-DD') : ''
              }`,
              tags: [
                {
                  id: nanoid(),
                  label: formatDictValue(bizDictOptions.contagious, ele.status),
                  // type: ele.status == 'contagious_status_stop' ? 'muted' : 'error',
                  fontColor: formatDictFontColor(bizDictOptions.contagious, ele.status),
                  bgColor: formatDictColor(bizDictOptions.contagious, ele.status),
                },
              ],
            });
            detail.push({
              label: '备注',
              value: ele.remark || '——',
            });
          }
        });
      singleData.value[i] = {
        title: DiagnosisEnum[i],
        data: res[i] ? detail : [],
        right: {
          show: res[i] ? true : false,
          date: res[i] ? dayjs(res[i].updateTime).format('YYYY-MM-DD') : '',
          doctor: res[i] ? res[i]?.updatorName : '',
          edit: true,
        },
        type: i,
      };
    }
    console.log('🚀 ~ file: index.vue:63 ~ getData ~ singleData.value:', singleData.value);
    // 下面五个
    const resMulti = await archivesDiagnosisHistoryQueryListMulti(props.info?.id);
    originMultiData.value = resMulti;
    for (const i in resMulti) {
      // console.log('resMulti ', i, resMulti[i]);
      if (i == DiagnosisEnum.complications_field) {
        setMultiData(i, resMulti[i], 'complications');
      } else if (i == DiagnosisEnum.clinic_field) {
        setMultiData(i, resMulti[i], 'clinic');
      } else if (i == DiagnosisEnum.pathological_field) {
        setMultiData(i, resMulti[i], 'pathological');
      } else if (i == DiagnosisEnum.ckd_field) {
        setMultiData(i, resMulti[i], 'ckd');
      } else {
        setMultiData(i, resMulti[i], '', '诊断结果');
      }
    }
    // console.log('🚀 ~ file: index.vue:243 ~ getData ~ multiData.value:', multiData.value);
  }
  // 设置 过敏原,合并症类型、临床诊断类型、病理类型、CKD类型、其他编辑 数据
  function setMultiData(i, record, dict?: string, str?: string) {
    const detailMulti = [];
    record &&
      record.forEach(ele => {
        detailMulti.push({
          data: ele.multiContent.map(mEle => {
            return {
              label: str || '诊断类型/名称',
              value: mEle.type ? formatDictValue(bizDictOptions[dict], mEle.type) : mEle.remark,
              span: mEle.type ? 8 : 8,
              tags:
                mEle.type &&
                mEle.multiName.map(mmEle => {
                  return {
                    id: nanoid(),
                    label: formatDictValue(bizDictOptions[mEle.type], mmEle),
                    // type: 'warning',
                    fontColor: formatDictFontColor(bizDictOptions[dict], mEle.type),
                    bgColor: formatDictColor(bizDictOptions[dict], mEle.type),
                  };
                }),
            };
          }),
          right: {
            show: true,
            date: dayjs(ele.updateTime).format('YYYY-MM-DD'),
            doctor: ele.updatorName,
            edit: useUser.getUserInfo.nickname == ele.updatorName ? true : false,
            delete: useUser.getUserInfo.nickname == ele.updatorName ? true : false,
          },
          id: ele.id,
        });
      });
    multiData.value[i] = {
      title: DiagnosisEnum[i],
      data: record == null ? [] : detailMulti,
      type: DiagnosisEnum[i + '_field'],
    };
  }

  // 回调
  // single
  function callEdit(data) {
    console.log('🚀 ~ file: index.vue:181 ~ callEdit ~ data:', data);
    // openModal(true, singleData.value[data.type]);
    console.log('...originSingleData.value[data.type]', originSingleData.value[data.type]);
    let modelData = {} as any;
    if (originSingleData.value[data.type] == null) {
      modelData = {
        updatorName: useUser.getUserInfo.nickname,
        content: [],
      };
    } else {
      modelData = originSingleData.value[data.type];
    }
    openModal(true, {
      ...modelData,
      title: singleData.value[data.type]?.title,
      dictOptions: bizDictOptions[data.type],
      type: data.type,
      patientBasicId: props.info?.id,
      id: modelData.content.length ? nanoid(5) : '',
      isSingle: true,
    });
  }
  function callEditMulti(data) {
    console.log('🚀 ~ file: index.vue:181 ~ callEdit ~ data:', data);
    const filterData =
      originMultiData.value[data.type].filter(ele => {
        return ele.id == data.data.id;
      })[0] || [];
    openModal(true, {
      ...filterData,
      title: multiData.value[data.type]?.title,
      id: data.data.id,
      dictOptions: bizDictOptions[data.type],
      patientBasicId: props.info?.id,
      isSingle: false,
    });
  }
  // multi
  async function callDel(data) {
    console.log('🚀 ~ file: index.vue:181 ~ callDel ~ data:', data);
    const id = data.data.id || '';
    createConfirm({
      content: '你确定要删除?',
      iconType: 'warning',
      onOk: async () => {
        await archivesDiagnosisHistoryMultiRemoveByIds([id]);
        createMessage.success('删除成功！');
        await getData();
      },
    });
  }
  // multi add
  function callIcon(data) {
    console.log('🚀 ~ file: index.vue:295 ~ callIcon ~ data:', data);
    openModal(true, {
      type: data.type,
      updateTime: dayjs().format('YYYY-MM-DD'),
      updatorName: useUser.getUserInfo.nickname,
      multiContent: [],
      title: multiData.value[data.type]?.title,
      id: '',
      dictOptions: bizDictOptions[data.type],
      patientBasicId: props.info?.id,
      isSingle: false,
    });
  }
  async function callSuccess() {
    await getData();
  }
</script>

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