<template>
  <popover-filter :clearable="modelValue && modelValue.length" :label="label" :text="text" :width="width" :scroll="false" @clear="clear">
    <el-input v-model.trim="filterText" :prefix-icon="Search" placeholder="输入搜索内容"></el-input>
    <el-scrollbar class="mt-10px" wrap-style="max-height: 40vh">
      <el-tree ref="sourceTreeRef" :data="sourceTree" show-checkbox node-key="id" :props="{ class: 'customer-source-filter-tree' }" :expand-on-click-node="false" :filter-node-method="filterNode" @check-change="changeSource">
        <template #default="{ node, data }">
          <div class="w-0 flex-grow flex items-center" @click="expand(data)">
            <div class="w-0 flex-grow truncate">{{ node.label }}</div>
            <div class></div>
            <a v-if="data.children && data.children.length" class="flex-shrink-0 ml-5px">
              <el-icon v-if="treeExpandMap[data.id]">
                <CaretTop />
              </el-icon>
              <el-icon v-else>
                <CaretBottom />
              </el-icon>
            </a>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </popover-filter>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { useVModels } from "@vueuse/core";
import { storeToRefs } from "pinia";
import { memberStore } from "@/store/member";

import { CaretBottom, CaretTop, Search } from "@element-plus/icons-vue";
import PopoverFilter from "../popover-filter-item.vue";

const emits = defineEmits(["update:modelValue"]);
const props = defineProps({
  label: { type: String, default: "客户来源" },
  width: { type: Number, default: 300 },
  modelValue: { type: Array, default: () => [] },
});
const { corpInfo } = storeToRefs(memberStore());
const { modelValue } = useVModels(props, emits);
const filterText = ref("");
const sourceTree = computed(() => (Array.isArray(corpInfo.value.customerSourceList) ? convertData(corpInfo.value.customerSourceList) : []));
const sourceTreeRef = ref();
const treeExpandMap = ref({});
const text = computed(() => (modelValue.value && modelValue.value.length ? `已选${modelValue.value.length}项` : "全部"));

function clear() {
  sourceTreeRef.value.setCheckedKeys([]);
  modelValue.value = [];
}

function changeSource() {
  const nodes = sourceTreeRef.value.getCheckedNodes();
  modelValue.value = nodes.filter((i) => !i.children).map((i) => i.label);
}

function expand(data) {
  const nodesMap = sourceTreeRef.value.store.nodesMap;
  if (!nodesMap[data.id]) return;
  if (data.children && data.children.length) {
    nodesMap[data.id].expanded = !nodesMap[data.id].expanded;
    treeExpandMap.value = Object.keys(nodesMap).reduce((acc, key) => {
      const node = nodesMap[key];
      if (node.expanded) {
        acc[key] = node.expanded;
      }
      return acc;
    }, {});
  } else {
    nodesMap[data.id].checked = !nodesMap[data.id].checked;
  }
}

function filterNode(value, data) {
  return value ? data.label.includes(value) : true;
}

function convertData(data) {
  return data.reduce((acc, item) => {
    if (!item.disable) {
      const newItem = {
        id: item.sourceId,
        label: item.sourceName,
      };
      if (item.children && item.children.length > 0) {
        newItem.children = convertData(item.children);
      }
      acc.push(newItem);
    }
    return acc;
  }, []);
}

watch(filterText, (val) => sourceTreeRef.value && sourceTreeRef.value.filter(val));
</script>
<style lang="scss" scoped>
:deep(.customer-source-filter-tree > .el-tree-node__content > .el-tree-node__expand-icon) {
  display: none;
}
</style>