<!-- 管理员管理-管理员角色管理-编辑 -->
<template>
    <app-drawer :title="t('admin.role.edit.title')" width="680" v-model:show="show" :refresh="refresh"
        :loading="loading">
        <el-form ref="formRef" class="el-form--vertical" label-width="90px" :model="formData" :rules="formRules">
            <el-form-item :label="t('admin.role.edit.rolename')" prop="rolename">
                <el-input v-model="formData.rolename" :placeholder="t('common.pleaseenter')"
                    :disabled="!!record?.autoid" />
            </el-form-item>
            <el-form-item :label="t('admin.role.edit.sensitivefields')" prop="sensitivefields">
                <el-checkbox-group v-model="checkedValue">
                    <el-checkbox :label="t('admin.role.edit.mobilephone')" value="1" />
                    <el-checkbox :label="t('admin.role.edit.cardtypeid')" value="2" />
                    <el-checkbox :label="t('admin.role.edit.email')" value="3" />
                </el-checkbox-group>
            </el-form-item>
            <el-form-item :label="t('admin.role.edit.menuids')" prop="menuids">
                <el-scrollbar max-height="300px" style="width: 100%;">
                    <el-tree ref="treeRef" :data="routerStore.userRoutes" :props="{ label: (data: Model.MenusRsp)=> t('routes.'+data.resourceCode) }"
                        node-key="resourceCode" show-checkbox check-strictly @check="handleCheck" />
                </el-scrollbar>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.submit') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, PropType, toRaw, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useRequest } from '@/hooks/request'
import { dealRoleMenus, queryDetail } from '@/services/api/admin'
import { useRouterStore, i18n } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'

const props = defineProps({
    record: {
        type: Object as PropType<Model.RoleRsp>
    }
})

const routerStore = useRouterStore()
const treeRef = ref()
const { global: { t } } = i18n
const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const checkedValue = ref<string[]>([])

const formData = ref<Partial<Model.RoleRsp>>({})

const { loading, run } = useRequest(queryDetail, {
    manual: true,
    onSuccess: ((res) => {
        // const isPrefixOfAny = (str: string, arr: string[]) => {
        //     // 检查str是否是arr中其他元素（以下划线分隔的部分）的前缀
        //     return arr.some((item) => {
        //         // 排除str本身，并将两个字符串分割成数组进行比较
        //         if (item === str) return false
        //         const strParts = str.split('_')
        //         const itemParts = item.split('_')
        //         return itemParts.length >= strParts.length && strParts.every((part, index) => part === itemParts[index])
        //     })
        // }

        // // 过滤出不是其他元素前缀的元素
        // const checkedKeys = res.data.menuids.filter((item) => !isPrefixOfAny(item, res.data.menuids))
        res.data.menuids.forEach((val) => {
            treeRef.value.setChecked(val, true, false)
        })
        formData.value = res.data
        checkedValue.value = res.data.sensitivefields.split(',')
    }),
    onError: (err) => {
        ElMessage.error(err)
    }
})

// 表单验证规则
const formRules: FormRules = {
    rolename: [{ required: true }],
}

const handleCheck = (data: Model.MenusRsp, state: { checkedKeys: string[] }) => {
    if (state.checkedKeys.includes(data.resourceCode)) {
        const node = treeRef.value.getNode(data.resourceCode)
        selectChildren(data, true)
        parentNodesChange(node)
    } else {
        selectChildren(data, false)
    }
}

// 选择子节点
const selectChildren = (data: Model.MenusRsp, checked: boolean) => {
    data && data.children && data.children.map((item) => {
        treeRef.value.setChecked(item.resourceCode, checked)
        if (data.children) {
            selectChildren(item, checked)
        }
    })
}

// 选中父节点
const parentNodesChange = (node: Node) => {
    if (node.parent) {
        treeRef.value.setChecked(node, true)
        if (node.id > 0) {
            parentNodesChange(node.parent)
        }
    }
}

const onCancel = (isRefresh = false) => {
    show.value = false
    refresh.value = isRefresh
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            const rawData = toRaw(formData.value)
            rawData.sensitivefields = checkedValue.value.join(',')
            rawData.menuids = treeRef.value.getCheckedKeys()
            loading.value = true
            dealRoleMenus({
                data: rawData
            }).then(() => {
                ElMessage.success(t('common.tips3'))
                onCancel(true)
            }).catch((err) => {
                ElMessage.error(t('common.tips4') + err)
            }).finally(() => {
                loading.value = false
            })
        }
    })
}

onMounted(() => {
    const autoId = props.record?.autoid
    if (autoId) {
        run({ autoId })
    }
})
</script>