<template>
  <div class="h-full w-full flex">
    <LeftMenu v-model:active="menuActive" :menus="menus" @change="menuChange">
      <template #itemDesc="{ item }">
        <div
          class="rounded text-xs mt-2 border border-solid border-red-500 text-red-600 p-1 text-text w-fit"
        >
          已选{{ item.list.filter(v => v.checked).length }}个病因
        </div>
      </template>
    </LeftMenu>
    <div class="flex-1 h-full overflow-y-auto p-4 space-y-4">
      <template v-if="menus[menuActive]?.id == 'additional'">
        <div class="bg-white shadow p-4">
          <div>
            <el-input
              v-model.trim="customEtiology"
              class="w-fit"
              placeholder="请输入其他自定义病因"
            ></el-input>
            <el-button type="primary" class="ml-2" @click="addCustomEtiology"
              >添加</el-button
            >
          </div>
          <el-divider></el-divider>
          <div>
            <el-tag
              v-for="(tag, tagIdx) in menus[menuActive].list"
              size="large"
              :key="tagIdx"
              type="danger"
              closable
              class="m-1"
              @close="menus[menuActive].list.splice(tagIdx, 1)"
              >{{ tag.label }}</el-tag
            >
          </div>
        </div>
      </template>
      <template v-else>
        <div
          v-for="(item, index) in menus[menuActive]?.list"
          :key="item.id"
          class="bg-white shadow p-4 flex"
        >
          <component
            :is="item.checked ? SuccessFilled : CircleCheck"
            class="w-6 h-6 cursor-pointer"
            :class="{
              'text-blue-500': item.checked,
              'text-gray-300': !item.checked
            }"
            @click="etiologiesChange(item)"
          ></component>
          <div class="flex-1 ml-2">
            <div class="font-bold mb-3">{{ item.label }}</div>
            <div
              v-for="(text, textIdx) in item.remark"
              :key="textIdx"
              class="break-all whitespace-pre-wrap text-gray-500 py-1"
            >
              {{ text }}
            </div>
            <div v-if="item.transferRawJson && item.formFields" class="rounded mt-2 bg-gray-50">
              <div class="mb-1 px-4 pt-2 text-sm text-gray-600">相关数据</div>
              <component
                v-if="item.transferRawJson && HealthArchivesModuleView"
                :is="HealthArchivesModuleView"
                :form="item.formFields"
                :transferRawJson="item.transferRawJson"
                class="text-sm"
              ></component>
            </div>
            <div v-if="item.projectDataList.length" class="rounded mt-2 bg-gray-50">
              <div class="mb-1 px-4 pt-2 text-sm text-gray-600">相关数据</div>
              <component
                v-if="item.projectDataList.length && HealthCheckData"
                :is="HealthCheckData"
                :list="item.projectDataList"
              ></component>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  markRaw,
  ref,
  inject,
  onMounted,
  provide,
  defineAsyncComponent,
  nextTick
} from "vue";
import { useRoute, useRouter } from "vue-router";
import LeftMenu from "./LeftMenu.vue";
import { request } from "@/utils";
import { CircleCheck, SuccessFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const [route, router] = [useRoute(), useRouter()];

const HealthCheckData = defineAsyncComponent(() =>
  import("./HealthCheckData.vue")
);
const HealthArchivesModuleView = defineAsyncComponent(() =>
  import("./HealthArchivesModuleView.vue")
);

const updateStateValueForKey = inject("updateStateValueForKey");
const menus = ref([]);
const menuActive = ref(0);
const getNodeRelationship = inject("getNodeRelationship");
const diseaseMangeNode = inject("diseaseMangeNode");
const getFormFieldsSurveyIds = inject('getFormFieldsSurveyIds')
const getSurveyFormByCode = inject('getSurveyFormByCode')
const getFormAnswer = inject('getFormAnswer')

const parentState = inject("parentState");

const getMenus = async () => {
  const data = await getNodeRelationship(
    diseaseMangeNode.value,
    "功能医学病因分析分类"
  );
  menus.value = data.map(v => {
    return {
      label: v.mProperties?.name,
      id: v.mId,
      list: []
    };
  });
  if (menus.value[0]?.id) {
    menuChange(0, menus.value[0]);
  }

  const checkedEtiologies = parentState.value.etiologies.map(v => v.id);
  const customEtiologies = parentState.value.etiologies.filter(v => v.type).map(v => ({...v, checked: true}));
  
  await Promise.all(
    menus.value.map(async m => {
      const data = await getNodeRelationship(m.id, "可能导致", 1);
      m.list = data.map(v => {
        const projectSetting = v.mProperties["关联检查项目"] || []
        const projects = []
        const projectNodes = []
        projectSetting?.forEach && projectSetting.forEach(p => {
          const arr = p.split ? p.split('||') : []
          arr[0] && projects.push(arr[0])
          arr.length > 1 && projectNodes.push(...arr.slice(1))
        })
        const temp = {
          id: v.mId,
          type: 0,
          label: v.mProperties.name,
          surveyTemplateCode: v.mProperties["关联问题模板编号"] || [],
          surveyQuestionCode: v.mProperties["关联问题编号"] || [],
          checkProjectId: projects,
          checkProjectNodeId: projectNodes,
          remark: v.mProperties["备注信息"],
          checked: checkedEtiologies.includes(v.mId),
          projectDataList: [],
          transferRawJson: undefined,
          formFields: undefined
        };
        console.log('temp.name, projects', temp.label, projects)
        return temp;
      });
      m.list.forEach(async item => {
        const surveyCode = [
          ...item.surveyQuestionCode.map(v => ({ key: v, type: 2 })),
          ...item.surveyTemplateCode.map(v => ({ key: v, type: 3 }))
        ];
        item.formFields = await getSurveyFormByCode(surveyCode);
        const ids = getFormFieldsSurveyIds(item.formFields);
        if (ids.length) {
          item.transferRawJson = await getFormAnswer(ids);
        }

        if (item.checkProjectId.length) {
          item.projectDataList = await getCheckData(item.checkProjectId, item.checkProjectNodeId)
        }
      });
      console.log(m.list);
    })
  );
  menus.value = [
    ...menus.value,
    {
      label: "其他",
      id: "additional",
      list: customEtiologies || []
    }
  ];
};
getMenus();

const allList = computed(() => menus.value.map(v => v.list).flat());
const checkedList = computed(() =>
  menus.value.map(v => v.list.filter(v => v.checked).map(v => v)).flat()
);
watch(
  () => checkedList.value,
  nv => {
    updateStateValueForKey("etiologies", nv);
  }
);
const etiologiesChange = item => {
  item.checked = !item.checked;
  console.log(checkedList.value);
};

const customEtiology = ref("");
const addCustomEtiology = () => {
  if (allList.value.map(v => v.label).includes(customEtiology.value)) {
    return ElMessage.error("已存在该病因");
  }
  menus.value[menuActive.value].list.push({
    id: "",
    type: 1,
    label: customEtiology.value,
    surveyTemplateCode: [],
    checkProjectId: [],
    checkProjectNodeId: [],
    remark: [],
    checked: true
  });
  ElMessage.success("添加成功");
  customEtiology.value = "";
};
const menuChange = async (i, menu) => {
  console.log(i, menu);
};



const getCheckData = async (itemIds, nodeIds) => {
  if (!itemIds.length) return;
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/query",
    {
      archivesId: route.query.archivesId,
      itemIds,
      nodeIds,
      date: []
    }
  );
  return (data?.list || []).map(v => {
    v.expand = true;
    v.list = v.list.map(v2 => {
      const dateList = {};
      v2.list.forEach(v3 => {
        if (dateList[v3.date]) {
          dateList[v3.date].push(v3);
        } else {
          dateList[v3.date] = [v3];
        }
        v2.list = Object.values(dateList);
      });
      return v2;
    });
    return v;
  });
}
</script>

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