<template>
    <el-input v-model="filterText" placeholder="搜索" class="mb-10">
        <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon>
        </template>
    </el-input>
    <div class="tree-container">
        <el-scrollbar>
            <el-tree
                :data="treeData"
                node-key="value"
                :render-content="renderContent"
                :default-expanded-keys="[ROOT_ID]"
                :props="{
                    label: 'riskName',
                    value: 'id',
                }"
                :filter-node-method="filterNode"
                @node-click="handleClick"
                ref="treeRef"
            />
        </el-scrollbar>
    </div>
</template>
<script lang="ts" setup>
import Icon from "@/components/icon/index.vue";
import { listRiskScoreRuleTree } from "@/api/sensitivePerception/riskScoreRule";

const ROOT_ID = 0;
const treeData = ref([
    {
        riskName: "全部",
        value: ROOT_ID,
        children: [],
    },
]);

const list = ref([]);
const total = ref(0);

onMounted(() => {
    listRiskScoreRuleTree().then((data) => {
        treeData.value[0].children = data;
    });
});

function renderContent(
    h,
    {
        node,
        data,
        store,
    }: {
        node: Node;
        data: Tree;
        store: Node["store"];
    }
) {
    console.log(node);
    return h(
        "div",
        {
            class: "flex v-center",
        },
        h(
            Icon,
            {
                name: "el-icon-Folder",
                class: "mr-8",
            },
            node.label
        ),
        h(
            "span",
            {
                title: node.label + "(" + node.ruleDesc + ")",
            },
            node.label
        ),
        h(
            "span",
            {
                class: "ml-8 text-primary",
            },
            node.data.size ? `(${node.data.size})` : ""
        )
    );
}

const filterText = ref("");
const treeRef = ref(null);

const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.label.includes(value);
};

watch(filterText, (val) => {
    treeRef.value!.filter(val);
});

const props = defineProps({
    modelValue: {
        type: Array,
        defalut: [],
    },
});

const emit = defineEmits(["update:modelValue"]);

function handleClick(node) {
    if (node.value === ROOT_ID) {
        emit("update:modelValue", null);
        return;
    }
    const arr = [];
    getModelId(arr, node);
    emit("update:modelValue", arr);
}

function getModelId(arr, node) {
    arr.push(node.id);
    node.children.forEach((item) => {
        getModelId(arr, item);
    });
}

</script>
<style lang="scss" scoped>
:deep() {
    .el-tree-node.is-current {
        & > .el-tree-node__content {
            background: #e1e5ff;
        }
    }
}
.tree-container {
    height: calc(100% - 42px);
}
</style>
