<script setup>
import { ref, onMounted, reactive, computed, nextTick, watchEffect } from "vue";
import { Search } from "@element-plus/icons-vue";
import FilterGroup from "@/components/FilterGroup";
import {
  getSubjectChapterList,
  getSubjectKnowledgeList,
  getPaperTypeList,
} from "@/api";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";

const { search, searchFun, paperConfig, userConfig } = storeToRefs(
  usePaperStore()
);
const { saveStaffChapter } = usePaperStore();

const treeData = ref([]);
const filterText = ref("");
const treeRef = ref();
const treeLoading = ref(false);
watch(filterText, (val) => {
  treeRef.value?.filter(val);
});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};

const options = reactive([
  {
    id: "1",
    label: "教材",
    children: [],
  },
  {
    id: "2",
    label: "年级",
    children: [],
  },
]);

const active = reactive(Array.from({ length: options.length }, () => []));

const activeNodeKey = ref("");
const handleNodeClick = (data) => {
  if (
    paperConfig.value.showLabelType !== 1 &&
    data.id === activeNodeKey.value
  ) {
    treeRef.value?.setCurrentKey(null);
    activeNodeKey.value = "";
    setSearch();
    return;
  }
  activeNodeKey.value = data.id;
  setSearch(data.baseId || data.id);
};

function setSearch(val = undefined) {
  if (paperConfig.value.showLabelType === 1) {
    search.value.knowledgeId = val;
    return;
  }
  if ([0, 2].includes(paperConfig.value.showLabelType)) {
    search.value.chapterId = val;
    search.value.bookId = active[1][0];
  } else if ([3, 4].includes(paperConfig.value.showLabelType)) {
    search.value.type = val;
  }
  searchFun.value();
}

async function init() {
  if (!search.value.stagePid || !search.value.subjectId) return;
  treeLoading.value = true;
  try {
    const { data: res } = await getSubjectChapterList({
      pid: 0,
      stagePid: search.value.stagePid,
      subjectId: search.value.subjectId,
    });

    options[0].children = res.map((i) => ({
      id: i.baseId,
      label: i.name,
      value: i.baseId,
      child: i.children.map((j) => ({
        id: j.baseId,
        label: j.name,
        value: j.baseId,
        child: j.children,
      })),
    }));
    const textbookId = userConfig.value.textbookId;
    // 优先使用缓存值
    active[0] = options[0].children.find((i) => i.id === textbookId)
      ? [textbookId]
      : [options[0].children[0].id];
  } catch (err) {
    console.log(err);
  } finally {
    treeLoading.value = false;
  }
}

function transformTreeData(data) {
  return data.map((item) => {
    const transformedItem = {
      ...item,
      id: item.baseId,
    };

    // 如果有 children，递归处理
    if (item.children && item.children.length > 0) {
      transformedItem.children = transformTreeData(item.children);
    }

    return transformedItem;
  });
}

async function onePieceInit() {
  if (!search.value.stagePid || !search.value.subjectId) return;
  treeLoading.value = true;
  try {
    let fn = getSubjectKnowledgeList;
    let category;
    if (paperConfig.value.showLabelType === 3) {
      fn = getPaperTypeList;
      category = 2;
    }
    if (paperConfig.value.showLabelType === 4) {
      fn = getPaperTypeList;
      category = 3;
    }
    treeData.value = [];
    const { data: res } = await fn({
      pid: 0,
      stagePid: search.value.stagePid,
      subjectId: search.value.subjectId,
      category,
    });
    if ([3, 4].includes(paperConfig.value.showLabelType)) {
      treeData.value = res.map((i) => ({
        id: i.type,
        name: i.typeName,
        value: i.type,
      }));
      return;
    }

    treeData.value = transformTreeData(res);

    if (!search.value.knowledgeId) {
      search.value.knowledgeId = treeData.value[0].id;
    }
    searchFun.value();
  } catch (err) {
    console.log(err);
  } finally {
    treeLoading.value = false;
  }
}

const name = computed(
  () =>
    `${options[0].children.find((i) => i.id === active[0][0])?.label || ""} · ${
      options[1].children.find((i) => i.id === active[1][0])?.label || ""
    }` || "教材"
);
const title = computed(() => {
  switch (paperConfig.value.showLabelType) {
    case 1:
      return "知识点";
    case 3:
      return "备考专区";
    case 4:
      return "升学专区";
    default:
      return "";
  }
});
const onePiece = computed(() =>
  [1, 3, 4].includes(paperConfig.value.showLabelType)
);

watch(
  () => active[0],
  (newVal) => {
    if (onePiece.value) return;
    userConfig.value.textbookId = newVal[0];
    saveStaffChapter(); // 更新个性化记录
    // 设置年级选项
    options[1].children = options[0].children.filter(
      (i) => i.id === newVal[0]
    )[0].child;
    // 优先使用缓存，默认第一个
    const gradeId = userConfig.value.gradeId;
    active[1] = options[1].children.find((i) => i.id === gradeId)
      ? [gradeId]
      : [options[1].children[0].id];
  },
  { deep: true }
);

watch(
  () => active[1],
  (newVal) => {
    if (onePiece.value) return;
    treeData.value = options[1].children.find((i) => i.id === newVal[0])?.child;
    search.value.chapterId = active[0][0];
    search.value.bookId = active[1][0];
    userConfig.value.gradeId = newVal[0];
    saveStaffChapter(); // 更新个性化记录
    searchFun.value();
  },
  {
    deep: true,
  }
);

watchEffect(() => {
  if (onePiece.value) {
    onePieceInit();
  } else {
    search.value.chapterId = "";
    search.value.bookId = "";
    init();
  }
});

watch(
  () => paperConfig.value.showLabelType,
  (newVal) => {
    if (newVal === 1 && search.value.knowledgeId) {
      activeNodeKey.value = search.value.knowledgeId;
      treeRef.value?.setCurrentKey(search.value.knowledgeId, true);
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => search.value.knowledgeId,
  (newVal) => {
    if (paperConfig.value.showLabelType === 1) {
      activeNodeKey.value = newVal;
      treeRef.value?.setCurrentKey(newVal);
    }
    searchFun.value();
  },
  {
    immediate: true,
  }
);
// watchEffect(() => {
//   // 知识点跳转
//   if (paperConfig.value.showLabelType === 1 && search.value.knowledgeId) {
//     // const node = treeRef.value?.store.nodesMap;
//     // if (node) {
//     //   for (let i in node) {
//     //     node[i]?.collapse();
//     //   }
//     // }
//     console.log("知识点跳转", search.value.knowledgeId);
//     activeNodeKey.value = search.value.knowledgeId;
//     treeRef.value?.setCurrentKey(search.value.knowledgeId);
//   }
// });
</script>

<template>
  <div class="filter-tree">
    <el-popover
      placement="bottom-start"
      trigger="hover"
      popper-class="filter-tree-popover"
      :disabled="onePiece"
    >
      <template #reference>
        <div class="box title">
          <template v-if="onePiece">
            {{ title }}
          </template>
          <template v-else>
            {{ name }}
          </template>
        </div>
      </template>
      <FilterGroup v-model="active" :options="options" />
    </el-popover>
    <div class="box">
      <el-input
        v-model="filterText"
        placeholder="请输入"
        :suffix-icon="Search"
        clearable
      ></el-input>
    </div>
    <el-scrollbar max-height="calc(100vh - 350px)">
      <el-tree
        class="box"
        ref="treeRef"
        style="width: 100%"
        node-key="id"
        v-loading="treeLoading"
        :data="treeData"
        :props="{
          children: 'children',
          label: 'name',
        }"
        highlight-current
        accordion
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        :current-node-key="activeNodeKey"
        @node-click="handleNodeClick"
      />
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
.filter-tree {
  background: #fff;
  border-radius: 4px;
  .box {
    padding: 16px;
  }
  .title {
    min-height: 50px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.filter-tree-popover {
  width: auto !important;
  max-width: 70% !important;
}
</style>
