<template>
    <app-drawer :title="t('admin.role.edit.title')" width="680" v-model:show="show" :loading="loading">
        <app-table-details :data="data" :label-width="120" :cell-props="detailProps" :column="1">
            <template #sensitivefields>
                {{ getSensitiveWords() }}
            </template>
            <template #menuids>
                <el-scrollbar max-height="300px" style="width: 100%; border: 1px solid #f2f2f2;">
                    <el-tree :data="filteredRoutes"
                        :props="{ label: (data: Model.MenusRsp) => t('routes.' + data.resourceCode) }"
                        node-key="resourceCode" />
                </el-scrollbar>
            </template>
        </app-table-details>
        <template #footer>
            <el-button @click="onCancel">{{ t('operation.cancel') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { useRequest } from '@/hooks/request'
import { queryDetail } from '@/services/api/admin'
import { getAllMenus } from '@/services/api/user'
import { i18n } from '@/stores'
import { CellProp } from '@pc/components/base/table-details/types'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTableDetails from '@pc/components/base/table-details/index.vue'
import { useEnum } from '@/hooks/enum'

const props = defineProps({
    roleid: {
        type: Number,
        required: true
    }
})

const roleTypeEnum = useEnum('roleType') // 角色名称
const { global: { t } } = i18n
const filteredRoutes = ref<Model.MenusRsp[]>([])
const show = ref(true)

const getSensitiveWords = () => {
    const options = [
        { label: t('admin.role.edit.mobilephone'), value: 1 },
        { label: t('admin.role.edit.cardtypeid'), value: 2 },
        { label: t('admin.role.edit.email'), value: 3 }
    ]
    const checkedValues = data.value?.sensitivefields.split(',') ?? []
    const selectedOptions = options.filter((e) => checkedValues.includes(e.value.toString()))
    const label = selectedOptions.map((e) => e.label).join(',')
    return handleNoneValue(label)
}

const allMenus = getAllMenus()

const { data, loading } = useRequest(queryDetail, {
    params: {
        autoId: props.roleid
    },
    onSuccess: (res) => {
        const codeSet = new Set(res.data.menuids)

        function filterMenu(data: Model.MenusRsp[]) {
            return data.reduce<Model.MenusRsp[]>((result, item) => {
                const { resourceCode, children } = item
                if (codeSet.has(resourceCode)) {
                    // 当前菜单项符合条件
                    result.push({
                        ...item,
                        children: children ? filterMenu(children) : [],
                    })
                } else if (children?.length) {
                    // 当前菜单项不符合条件，但有子菜单，递归过滤子菜单
                    const filteredChildren = filterMenu(children)
                    if (filteredChildren.length) {
                        result.push({
                            ...item,
                            children: filteredChildren,
                        })
                    }
                }
                return result
            }, [])
        }

        allMenus.then((res) => {
            // 递归过滤菜单
            filteredRoutes.value = filterMenu(res.data)
        })
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const detailProps: CellProp[] = [
    { prop: 'autoid', label: 'admin.role.edit.rolename', formatValue: (val) => roleTypeEnum.getEnumTypeName(val) },
    { prop: 'sensitivefields', label: 'admin.role.edit.sensitivefields' },
    { prop: 'menuids', label: 'admin.role.edit.menuids' },
]

const onCancel = () => {
    show.value = false
}
</script>