<template>
    <view class="nav choose">
        <view class="nav-menu nav-menu1" @click="selectEngineering" v-if="showQianTree">
            <view class="nav-text">
                {{ lineDisplayText }}
            </view>

            <uni-icons type="bottom" size="14"></uni-icons>
        </view>
        <view class="nav-menu nav-menu1" @click="selectEngineering" v-if="showQianTree">
            <view class="nav-text">
                {{
                    '指标配置'
                }}
            </view>

            <uni-icons type="bottom" size="14"></uni-icons>
        </view>
        <!-- 弹框组件 -->
        <Cn-MultipleTree ref="qiantree" :selectParent="true" :multiple="true" :range="list" :foldAll="true"
            @confirm="treeConfirm" @cancel="treeCancel"></Cn-MultipleTree>



        <slot />
    </view>
</template>
<script>
import { lineTree } from '@/common/api/device'
export default {
    components: {},
    props: {
        level: { type: Number, default: 3 },

        singleChoice: { type: Boolean, default: false },
        showQianTree: { type: Boolean, default: true },
    },
    data() {

        return {
            select: {
                lineList: []//监测点id
            },
            list: [],
        }
    },
    created() { },
    onShow() { },

    mounted() { },

    methods: {
        getTree() {
            this.clear()
            lineTree().then((res) => {
                let list = {}
                // if (this.singleChoice) {
                //     let result = this.findFirstLevel(res.data)

                // } else {
                //     list = {
                //         id: '',
                //         pid: '0',
                //         pids: '0',
                //         name: '全部工程',
                //         path: null,
                //         provinceId: null,
                //         cityId: null,
                //         area: null,
                //         remark: null,
                //         sort: 0,
                //         level: 0,
                //         comFlag: null,
                //         type: null,
                //         lineType: null,
                //         conType: null,
                //         process: null,
                //         isTop: 0,
                //         children: [],
                //         ndid: null,
                //     }
                // }

                this.list = this.filterTreeByLevel(this.singleChoice ? res.data : [...res.data])
                // this.findFirstLevel( this.list)
            })
        },
        // 递归过滤函数：去除level > 2的节点
        filterTreeByLevel(tree) {
            // 遍历每一个节点
            return tree.map((node) => {
                // 复制当前节点（避免修改原数据）
                const newNode = { ...node }

                // 如果当前节点有子节点，并且当前节点的level <= 2（因为level=2的节点的子节点是level=3，需要过滤）
                if (newNode.children && newNode.children.length > 0) {
                    // 递归过滤子节点：只保留子节点中level <= 2的
                    newNode.children = this.filterTreeByLevel(
                        newNode.children.filter((child) => child.level <= this.level),
                    )
                }

                return newNode
            })
        },



        selectEngineering() {
            this.$refs.qiantree._show()
        },

        // 确定回调事件
        treeConfirm(e) {
            this.select.lineList = e.filter(item => item.rank == 3)
        },
        // 清空
        clear() {
            this.select.lineList = []//监测点id
        },


        // 取消回调事件
        treeCancel(e) {
            console.log(e)
        },
        findFirstLevel(list, parents = []) {
            for (const item of list) {
                // 当前就是 level=3
                if (item.level === 3) {
                    return {
                        node: item, // 第一个 level=3
                        parents: parents, // 它的所有上级
                    }
                }

                // 递归子节点
                if (item.children && item.children.length) {
                    const res = this.findFirstLevel(item.children, [...parents, item])
                    if (res) return res // 找到直接返回，不再循环
                }
            }
            return null
        },
    },

    computed: {
        lineDisplayText() {
            const list = this.select.lineList || []
            if (!list.length) {
                return '筛选监测点'
            }
            const text = list
                .map((item) => item.name)
                .filter(Boolean)
                .join('、')
            if (text.length > 8) {
                return text.slice(0, 8) + '...'
            }
            return text
        },
    },

    watch: {
        select: {
            handler(val, oldVal) {
                console.log("🚀 ~ val:", val)
                if (this.loading) return
                this.$emit('select', val)
            },
            deep: true,
            immediate: true,
        },
        level: {
            handler(val, oldVal) {
                this.getTree()
            },
            deep: true,
            immediate: true,
        },
        // showDatetime: {
        //     handler(val, oldVal) {
        //         if (val == false) {

        //             console.log("🚀 ~  this.select.range:",  this.select.range)
        //         }
        //     },
        //     deep: true,
        // },
    },
}
</script>
<style lang="scss" scoped>
/deep/ .uni-date-editor {
    width: 360rpx;
}

.nav-menu {
    display: flex;
    align-items: center;
}

// .nav-menu1 {
//     max-width: calc(100vw - 150px);
//     overflow: hidden !important;
//     -webkit-line-clamp: 1;
//     display: -webkit-box;
//     -webkit-box-orient: vertical;
//     text-overflow: ellipsis;
//     word-break: break-all;
//     white-space: nowrap;
// }
.nav-menu1 {
    display: flex;
    align-items: center;
    max-width: calc(100vw - 150px);
}

/* 文字容器：单行溢出省略 */
.nav-text {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    /* 强制不换行 */
    text-overflow: ellipsis;
    // -webkit-line-clamp: 1;
    // display: -webkit-box;
    // -webkit-box-orient: vertical;
    // text-overflow: ellipsis;
    // word-break: break-all;
    // white-space: nowrap;
    line-height: 1;
}
</style>
