<template>
  <div>
    <div class="mx-6 mb-2">
      <TimeLine :data="timeLineData" @hover="callHover">
        <template #head>
          <transition class="animate__animated animate__slideInLeft">
            <div class="timeline-outer" v-if="timeOuter">
              <div
                class="timeline-outer_item"
                v-for="item in bizDictOptions.type"
                :key="item.id"
                @click="handleAdd(item.value)"
              >
                {{ item.label }}
              </div>
            </div>
          </transition>
        </template>
        <template #card="{ data }">
          <a-button
            v-if="data.dot == '正常'"
            type="primary"
            shape="round"
            class="mr-4"
            @click="handleAccessReturn(data.id)"
            >通路转归</a-button
          >
          <a-dropdown>
            <span class="ant-dropdown-link">
              <i :class="['iconfont', 'icon-xt-details_more_default']" />
            </span>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  v-for="menu in dropMenu"
                  :key="menu.value"
                  @click="handleMenu({ id: data.id, menu: menu.value })"
                >
                  <span>
                    {{ menu.label }}
                  </span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </TimeLine>
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
    <FormDrawer @register="registerDrawer" @success="callSuccess" />
    <FormModalReturn @register="registerModalReturn" @success="callSuccess" />
    <ViewDrawerComplication @register="registerDrawerComplication" @success="callSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onUnmounted } from 'vue';
  import TimeLine from '/@/components/XTTimeLine/src/TimeLine.vue';
  import {
    archivesVascularAccessQueryList,
    archivesVascularAccessRemove,
  } from '/@/api/biz/archives/vascularAccessApi';
  import { onMounted } from 'vue';
  import dayjs from 'dayjs';
  import { listDictModelBatch } from '/@/api/common';
  import { formatDictValue } from '/@/utils';
  // 通路回归
  import FormModalReturn from './FormModalReturn.vue';
  // 新建编辑
  import FormModal from './FormModal.vue';
  // 通路评估
  import FormDrawer from './FormDrawer.vue';
  // 通路并发症
  import ViewDrawerComplication from './ViewDrawerComplication.vue';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useDrawer } from '@/components/Drawer';
  import { DictCommon } from './data';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  const bizDictOptions = reactive<any>({});
  const timeLineData = ref([]);
  const timeOuter = ref(false);
  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];
    }
    console.log('🚀 ~ file: index.vue:47 ~ onMounted ~ bizDictOptions:', bizDictOptions);
    // console.log('🚀 ~ file: index.vue:96 ~ onMounted ~ res:', res);
    await getData();
  });
  const dropMenu = [
    { label: '通路评估', value: 'assessment' },
    { label: '评估记录', value: 'assessmentRecord' },
    { label: '通路并发症', value: 'assessComplication' },
    { label: '编辑', value: 'edit' },
    { label: '删除', value: 'del' },
  ];
  const [registerModalReturn, { openModal: openModalReturn }] = useModal();
  const [registerModal, { openModal }] = useModal();
  const [registerDrawer] = useDrawer();
  const [registerDrawerComplication, { openDrawer: openDrawerComplication }] = useDrawer();
  const { createMessage, createConfirm } = useMessage();
  const bizDictData = ref([
    // 血管材料
    { key: 'material', dictCode: 'va_material' },
    // 吻合方式
    { key: 'anastomosis', dictCode: 'va_anastomosis' },
    // 穿刺方式
    { key: 'puncture', dictCode: 'va_puncture' },
    // 通路类型
    { key: 'type', dictCode: 'va_type' },
    // 置管引导
    { key: 'catheterGuidance', dictCode: 'va_guidance' },
    // 转归原因
    { key: 'return', dictCode: 'va_return' },
    // 位置
    { key: 'avfLoc', dictCode: 'va_avf_loc' },
    // 动脉
    { key: 'avfArteries', dictCode: 'va_avf_arteries' },
    // 静脉
    { key: 'avfVein', dictCode: 'va_avf_vein' },
    { key: 'avgLoc', dictCode: 'va_avg_loc' },
    { key: 'avgArteries', dictCode: 'va_avg_arteries' },
    { key: 'avgVein', dictCode: 'va_avg_vein' },
    { key: 'nccLoc', dictCode: 'va_ncc_loc' },
    // 颈内静脉
    { key: 'nccLocJnjm', dictCode: 'ncc_loc_jnjm' },
    // 锁骨下静脉
    { key: 'nccLocSg', dictCode: 'ncc_loc_sg' },
    { key: 'tccLoc', dictCode: 'va_tcc_loc' },
    { key: 'tccLocJnjm', dictCode: 'tcc_loc_jnjm' },
    { key: 'tccLocJwjm', dictCode: 'tcc_loc_jwjm' },
    { key: 'tccLocSg', dictCode: 'tcc_loc_sg' },
  ]);

  async function getData() {
    const res = await archivesVascularAccessQueryList(props.info?.id);
    console.log('🚀 ~ file: index.vue:105 ~ getData ~ res:', res);
    timeLineData.value = res.map(ele => {
      const innerData = {
        title: '基本信息',
        // icon: 'icon-xt-details_more_default',
        icon: '',
        type: 'basic',
        data: [
          { field: 'setUpHospital', label: '建立医院', value: '' },
          { field: 'puncture', label: '穿刺体侧', value: '', dict: true },
          { field: 'location', label: '手术部位', value: '' },
          { field: 'anastomosis', label: '吻合方式', value: '', dict: true },
          { field: 'catheterGuidance', label: '置管引导', value: '', dict: true },
          { field: 'vascularMaterial', label: '血管材料', value: '', hidden: true, dict: true },
          { field: 'updatorName', label: '记录人', value: '' },
          { field: 'accessReturn', label: '转归记录', value: '', span: 12 },
        ],
      };
      innerData.title = formatDictValue(bizDictOptions.type, ele.type);
      console.log('🚀 ~ file: index.vue:114 ~ getData ~ innerData:', innerData);
      innerData.type = ele.type;
      innerData.data = innerData.data.map(eleC => {
        if (eleC.dict) {
          eleC.value = formatDictValue(bizDictOptions[eleC.field], ele[eleC.field]);
        } else {
          eleC.value = ele[eleC.field];
        }
        // 吻合方式
        if (ele.type == DictCommon.basic.va_type_ncc || ele.type == DictCommon.basic.va_type_tcc) {
          eleC.hidden = eleC.field == 'anastomosis' ? true : false;
        }
        // 置管引导
        if (ele.type == DictCommon.basic.va_type_avf || ele.type == DictCommon.basic.va_type_avg) {
          eleC.hidden = eleC.field == 'catheterGuidance' ? true : false;
        }
        // 手术位置
        if (eleC.field == 'location') {
          if (ele.type == DictCommon.basic.va_type_avf) {
            eleC.value = `
              ${formatDictValue(bizDictOptions['avfLoc'], ele['location'])}
              / ${formatDictValue(bizDictOptions['avfArteries'], ele['arteries'])}
              - ${formatDictValue(bizDictOptions['avfVein'], ele['vein'])}`;
          }
          if (ele.type == DictCommon.basic.va_type_avg) {
            eleC.value = `
              ${formatDictValue(bizDictOptions['avgLoc'], ele['location'])}
              / ${formatDictValue(bizDictOptions['avgArteries'], ele['arteries'])}
              - ${formatDictValue(bizDictOptions['avgVein'], ele['vein'])}`;
          }
          if (ele.type == DictCommon.basic.va_type_ncc) {
            let path = '';
            if (ele['location'] == 'ncc_loc_jnjm') {
              path = formatDictValue(bizDictOptions['nccLocJnjm'], ele['path']);
            } else if (ele['location'] == 'ncc_loc_sg') {
              path = formatDictValue(bizDictOptions['nccLocSg'], ele['path']);
            } else {
              path = formatDictValue(bizDictOptions['nccLoc'], ele['path']);
            }
            eleC.value = `
              ${formatDictValue(bizDictOptions['nccLoc'], ele['location'])}
              / ${path}`;
          }
          if (ele.type == DictCommon.basic.va_type_tcc) {
            let path = '';
            if (ele['location'] == 'tcc_loc_jnjm') {
              path = formatDictValue(bizDictOptions['tccLocJnjm'], ele['path']);
            } else if (ele['location'] == 'tcc_loc_jwjm') {
              path = formatDictValue(bizDictOptions['tccLocJwjm'], ele['path']);
            } else if (ele['location'] == 'tcc_loc_sg') {
              path = formatDictValue(bizDictOptions['tccLocSg'], ele['path']);
            } else {
              path = formatDictValue(bizDictOptions['tccLoc'], ele['path']);
            }
            eleC.value = `
              ${formatDictValue(bizDictOptions['tccLoc'], ele['location'])}
              / ${path}`;
          }
        }

        // 血管材料
        if (eleC.field == 'vascularMaterial') {
          eleC.hidden = ele.type == 'va_avg' ? false : true;
        }
        // 转归记录
        if (eleC.field == 'accessReturn') {
          if (ele.returnBack) {
            eleC.value = `于${dayjs(ele[eleC.field]['returnTime']).format(
              'YYYY-MM-DD',
            )}转归； 使用${dayjs(ele[eleC.field]['returnTime']).diff(
              dayjs(ele[eleC.field]['updateTime']).format('YYYY-MM-DD'),
              'day',
            )}天； ${formatDictValue(bizDictOptions.return, ele[eleC.field]['returnCause'])}； ${
              ele['updatorName']
            }`;
          } else {
            eleC.hidden = true;
          }
        }
        return eleC;
      });
      // console.log('🚀 ~ file: index.vue:168 ~ getData ~ cnt:', innerData);
      return {
        id: ele.id,
        dot: ele.returnBack ? '已转归' : '正常',
        date: dayjs(ele.setUpTime).format('YYYY-MM-DD'),
        cnt: innerData,
      };
    });
    console.log('🚀 ~ file: index.vue:168 ~ getData ~ timeLineData.value :', timeLineData.value);
  }
  function handleAdd(data) {
    console.log('🚀 ~ file: index.vue:205 ~ handleAdd ~ data:', data);
    // timeOuter.value = false;
    openModal(true, {
      record: { ...props.info, accessType: data },
    });
  }
  function callHover() {
    timeOuter.value = true;
  }
  function handleAccessReturn(id) {
    console.log('通路转归', id);
    openModalReturn(true, {
      record: props.info,
      accessId: id,
      isUpdate: true,
    });
  }
  onUnmounted(() => {
    timeOuter.value = false;
  });
  function handleMenu(data) {
    if (data.menu == 'edit') {
      console.log('data', data);
      openModal(true, {
        isUpdate: true,
        record: { ...props.info, ...data },
      });
    }
    if (data.menu == 'del') {
      console.log('data', data);
      createConfirm({
        content: '确定要删除选中数据?',
        iconType: 'warning',
        onOk: async () => {
          // 删除
          await archivesVascularAccessRemove([data.id]);
          createMessage.success('删除成功！');
          await getData();
        },
      });
    }
    if (data.menu == 'assessment') {
      console.log('data', data);
    }
    if (data.menu == 'assessmentRecord') {
      console.log('data', data);
    }
    if (data.menu == 'assessComplication') {
      console.log('data', data);
      openDrawerComplication(true, {
        record: props.info,
        accessId: data.id,
      });
    }
  }
  // 回调
  async function callSuccess(data) {
    console.log('🚀 ~ file: index.vue:212 ~ callSuccess ~ data:', data);
    await getData();
  }
</script>

<style lang="less" scoped>
  .timeline-outer {
    display: flex;
    margin-left: 20px;
    transition: all 0.3s ease-in-out;

    &_item {
      padding: 0 30px;
      height: 40px;
      line-height: 40px;
      border-radius: 30px;
      color: #fff;
      background: #0075ff;
      margin-right: 20px;
      cursor: pointer;
      letter-spacing: 2px;
    }
  }

  ::v-deep(.ant-picker) {
    width: 100%;
  }

  .ant-dropdown-link {
    display: block;
    margin-right: 16px;
    background: #fff;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    cursor: pointer;

    &:last-child {
      margin-right: 0;
    }

    &:hover {
      color: #0075ff;
    }
  }
</style>
