<template>
    <view class="top-info-wrapper">
        <view class="top-info-container">
            <view class="info-content">
                <!-- 左侧信息区域 -->
                <view class="left-info">
                    <!-- 上面：根据角色显示部门信息 -->
                    <view class="department-info">
                        <text class="department-value">{{ currentDepartmentPath }}</text>
                    </view>

                    <!-- 下面：根据是否个人显示不同信息 -->
                    <view class="user-info">
                        <text v-if="isPersonal" class="user-name">姓名：{{ currentLevelUserName }}</text>
                        <text v-else class="stat-count">统计人数：{{ currentLevelUserCount }}</text>
                    </view>
                </view>

                <!-- 右侧切换按钮 -->
                <view v-if="!userRoles.includes('SecurityCheck') && currentTab != 'team'" class="right-switch"
                    @click="openPopup">
                    <image src="/static/images/icon/switch.png" mode="aspectFit" class="switch-image" />
                </view>
            </view>

            <!-- 切换弹窗 -->
            <uni-popup ref="SelectPopup" type="center" :mask-click="false">
                <view class="popup-container">
                    <view class="popup-header">
                        <text class="popup-title">选择</text>
                        <view class="popup-close" @click="closePopup">×</view>
                    </view>

                    <!-- 搜索框 -->
                    <view class="search-section">
                        <uni-easyinput v-model="searchKeyword"
                            :placeholder="userRoles.includes('banzuzhang') ? '请输入姓名搜索' : '请输入部门名称、姓名搜索'"
                            :clearable="true" />
                    </view>

                    <!-- 部门树 -->
                    <view class="tree-section">
                        <scroll-view scroll-y="true" class="tree-scroll">
                            <mix-tree :list="filteredTreeData" :expandAll="!!searchKeyword"
                                @treeItemClick="handleNodeSelect" />
                        </scroll-view>
                    </view>

                    <!-- 按钮区域 -->
                    <view class="button-section">
                        <view class="btn-cancel" @click="closePopup">取消</view>
                        <view class="btn-confirm" @click="confirmSelection">确定</view>
                    </view>
                </view>
            </uni-popup>
        </view>
    </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import mixTree from '@/uni_modules/mix-tree/components/mix-tree/mix-tree.vue'
import { getDeptUserTree, getUserInfoById } from '@/api/system/user'
export default {
    name: 'TopInfo',
    components: {
        mixTree
    },
    props: {
        currentTab: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            searchKeyword: '',
            selectedNode: null,
            // 模拟部门树数据
            departmentTree: [],
            allLabels: [],
            // 存储通过currentLevelId获取的用户姓名
            currentLevelUserName: ''
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.userInfo,
            userRoles: state => state.user.roles,
            currentDepartmentPath: state => state.eikonLevel.currentDepartmentPath,
            currentLevelId: state => state.eikonLevel.currentLevelId,
            currentLevelUserCount: state => state.eikonLevel.currentLevelUserCount
        }),
        ...mapGetters('eikonLevel', ['isPersonal', 'isZhanZhang', 'isKeZhang', 'isBanZuZhang']),
        // 获取部门标签文本
        getDepartmentLabel() {
            if (this.isBanZuZhang) return '班组'
            if (this.isKeZhang) return '科室'
            if (this.isZhanZhang) return '站'
            return '部门'
        },

        // 过滤后的树数据
        filteredTreeData() {
            if (!this.searchKeyword) {
                // 没有搜索关键词时，设置第一层节点的showChild为true
                return this.departmentTree.map(node => ({
                    ...node,
                    showChild: true  // 设置第一层节点为展开状态
                }))
            }

            const filterTree = (nodes) => {
                if (!nodes || !Array.isArray(nodes)) {
                    return []
                }

                return nodes.filter(node => {
                    const matches = node.label && node.label.toLowerCase().includes(this.searchKeyword.toLowerCase())
                    if (node.children && node.children.length > 0) {
                        const filteredChildren = filterTree(node.children)
                        return matches || filteredChildren.length > 0
                    }
                    return matches
                }).map(node => ({
                    ...node,
                    children: node.children && node.children.length > 0 ? filterTree(node.children) : undefined
                }))
            }

            return filterTree(this.departmentTree)
        }
    },
    methods: {
        // 根据currentLevelId获取用户信息
        async getUserInfoByLevelId() {
            if (this.isPersonal && this.currentLevelId) {
                try {
                    const res = await getUserInfoById(this.currentLevelId)
                    if (res.data) {
                        this.currentLevelUserName = res.data.nickName || res.data.userName || '未知用户'
                    }
                } catch (error) {
                    console.error('获取用户信息失败:', error)
                    this.currentLevelUserName = '未知用户'
                }
            } else {
                this.currentLevelUserName = ''
            }
        },

        // 打开弹窗
        openPopup() {
            this.$refs.SelectPopup.open();

            this.searchKeyword = ''
            this.selectedNode = null
            this.getDeptTree()
        },

        // 关闭弹窗
        closePopup() {
            this.$refs.SelectPopup.close();
            this.searchKeyword = ''
            this.selectedNode = null
        },
        // 节点选择
        handleNodeSelect(item) {
            console.log('item', item)
            // mix-tree组件返回的是扁平化后的节点数据，包含id、name、parentId等信息
            this.selectedNode = item
        },
        // 确认选择
        confirmSelection() {
            if (this.selectedNode) {
                // 获取选中节点的所有父级 label（包含本级）
                const allLabels = this.getAllLabels(this.selectedNode)
                console.log('选中节点的完整路径 label:', allLabels)
                this.allLabels = allLabels;
                // 将完整路径信息传递给事件

                this.$emit('department-change', this.selectedNode)
            }
            this.closePopup()
        },
        // 获取节点在树结构中的所有 label（包含本级）
        getAllLabels(node) {
            console.log('node', node)
            if (!node || !this.departmentTree.length) {
                return []
            }

            const findNodePath = (treeNodes, targetId, path = []) => {
                for (const treeNode of treeNodes) {
                    // 如果找到目标节点，返回包含本级 label 的路径
                    if (treeNode.id === targetId) {
                        return [...path, treeNode.label]
                    }

                    // 如果有子节点，递归查找
                    if (treeNode.children && treeNode.children.length > 0) {
                        const newPath = [...path, treeNode.label]
                        const result = findNodePath(treeNode.children, targetId, newPath)
                        if (result) {
                            return result
                        }
                    }
                }
                return null
            }

            const fullPath = findNodePath(this.departmentTree, node.id)

            return fullPath || []
        },
        async getDeptTree() {
            // console.log(this.userInfo, "this.userInfo",this.userRoles)
            
            let params = {}
            if (this.userRoles.includes('test')) {
                params.deptId = this.userInfo.stationId
            }
            if (this.userRoles.includes('jingli')) {
                params.deptId = this.userInfo.brigadeId
            }
            if (this.userRoles.includes('kezhang')) {
                params.deptId = this.userInfo.departmentId
            }
            if (this.userRoles.includes('banzuzhang')) {
                params.deptId = this.userInfo.teamsId
            }
            let res = await getDeptUserTree(params)
            this.departmentTree = res.data
        }
    },



    // 监听currentLevelId和isPersonal的变化
    watch: {
        currentLevelId: {
            handler() {
                this.getUserInfoByLevelId()
            },
            immediate: true
        },

    }
}
</script>





<style lang="scss" scoped>
.top-info-wrapper {
    width: 100%;
    padding: 40rpx 40rpx 0 40rpx ;
}

.top-info-container {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.info-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.left-info {
    flex: 1;
}

.department-info {
    margin-bottom: 16rpx;

    .department-label {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
    }

    .department-value {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
    }
}

.user-info {

    .user-name,
    .stat-count {
        font-size: 26rpx;
        color: #999;
    }
}

.right-switch {


    .switch-image {
        width: 40rpx;
        height: 40rpx;
    }



}

.popup-container {
    width: 600rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .popup-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
    }

    .popup-close {
        font-size: 40rpx;
        color: #999;
        cursor: pointer;

        &:active {
            color: #666;
        }
    }
}

.search-section {
    margin-bottom: 24rpx;
}

.tree-section {

    margin-bottom: 32rpx;

    .tree-scroll {
        height: 500rpx;
    }
}

/* mix-tree组件自带样式，无需额外定义 */

.button-section {
    display: flex;
    justify-content: flex-end;
    gap: 24rpx;

    .btn-cancel,
    .btn-confirm {
        padding: 20rpx 40rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        font-weight: 500;
        border: none;
        cursor: pointer;
    }

    .btn-cancel {
        background: #f5f5f5;
        color: #666;

        &:active {
            background: #e8e8e8;
        }
    }

    .btn-confirm {
        background: #4873E3;
        color: #fff;

        &:active {
            background: #3a5bc7;
        }
    }
}
</style>