<!--
 * @Author: micky
 * @Date: 2024-08-16 16:07:29
 * @LastEditors: micky
 * @LastEditTime: 2024-10-19 15:20:34
 * @FilePath: \chargingpile-uniapp\src\components\roles-popup.vue
-->
<template>
    <u-popup :show="visible" :closeOnClickOverlay="true" @close="emit('close')">
        <view class="wrapper">
            <view class="list">
                <view
                    v-for="item in userInfo.roles"
                    :key="item.id"
                    @click="handleActiveRole(item.id)"
                >
                    <text :class="{ active: item.id === activeRole }">{{ item.name }}</text>
                </view>
            </view>
            <TFooterBtn text="确定" @handle-btn-click="handleConfirm" />
        </view>
    </u-popup>
</template>

<script setup lang="ts">
import { ref, watch, unref } from 'vue'
import { useUserStore } from '@/stores/user'
import cache from '@/utils/cache'
import { ROLEINDEX } from '@/enums/cacheEnums'
import { useTabBarStore } from '@/stores/tabbar'
import { useRoleData } from '@/hooks/useRoleData'

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    modelValue: {
        type: Number,
        default: 1
    }
})
const tabBarStore = useTabBarStore()
const userStore = useUserStore()
const { userInfo } = userStore
const { roles } = useRoleData()
const emit = defineEmits(['update:modelValue', 'close'])
const activeRole = ref(props.modelValue)
const visible = ref(false)
const currentRoutes = getCurrentPages() // 获取当前打开过的页面路由数组
const currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
const handleActiveRole = (val: number) => {
    activeRole.value = val
}
const handleConfirm = async () => {
    const ind = userInfo.roles.findIndex(item => item.id == unref(activeRole))
    cache.set(ROLEINDEX, ind)
    const obj: any = roles.find(role => {
        return role.ids.includes(activeRole.value)
    })

    tabBarStore.setTabBarList(obj?.tabBarList!)
    const sampleRoute = obj?.tabBarList.find(item => item.path == `/${currentRoute}`)
    // 没有找到相同的路由
    if (!sampleRoute) {
        const ind = (obj?.tabBarList?.length - 1) as number
        uni.redirectTo({
            url: obj?.tabBarList[ind]?.path as string
        })
        tabBarStore.setActiveTabBar(ind)
    }

    visible.value = false
    emit('close', ind)
    emit('update:modelValue', unref(activeRole))
}

watch(
    () => props.show,
    (newVal: boolean) => {
        visible.value = newVal
    }
)
</script>
<style lang="scss" scoped>
.wrapper {
    @include flex-direction;
    .list {
        flex: 1;
        overflow: auto;
        > view {
            @include flex-center;
            height: 100rpx;
            line-height: 100rpx;
            border-bottom: 1px solid $gray-3;
            &:last-child {
                border-bottom: none;
            }
            .active {
                color: $blue-1;
            }
        }
    }
}
</style>
