<template>
    <hc-dialog v-model="isShow" widths="800px" :padding="false" title="角色权限配置" is-table is-footer-center @close="dialogClose">
        <el-tabs tab-position="left" class="hc-role-auth-dialog h-full w-full">
            <template v-for="(item, index) in tabPaneData" :key="index">
                <el-tab-pane :label="item.name">
                    <hc-data-tree
                        :ref="(el) => setTreeRefs(el, item)" tree-key="id" :h-props="treeProps"
                        show-checkbox :datas="authTree[item.key]" :default-checked-keys="roleData[item.key]"
                    />
                </el-tab-pane>
            </template>
        </el-tabs>
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { arrIndex, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/authority/role'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['close'])

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听内容
const rowInfo = ref(props.info)
watch(() => props.info, (data) => {
    rowInfo.value = data
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) {
        getDataApi()
    }
})

//权限列表
const tabPaneData = ref([
    { key: 'menu', name: '后台管理', form: 'menuIds' },
    { key: 'usermenu', name: '质检试验', form: 'menuClientIds' },
    { key: 'archivesMenu', name: '档案管理', form: 'menuArchivesIds' },
    { key: 'larMenu', name: '征拆管理', form: 'menularIds' },
    { key: 'measureMenu', name: '计量支付', form: 'menuMeasureIds' },
    { key: 'hacMenu', name: '内控系统', form: 'menuHacIds' },
    { key: 'tableOwners', name: '表单权限', form: 'tableOwners' },
    { key: 'dataScope', name: '数据权限', form: 'dataScopeIds' },
    { key: 'apiScope', name: '接口权限', form: 'apiScopeIds' },
])

//获取数据
const getDataApi = () => {
    const { id } = rowInfo.value
    if (isNullES(id)) return
    getGrantTree()
    getRoleData(id)
}

//设置权限树的属性
const treeProps = {
    label: 'title',
    children: 'children',
}
const treeRefs = ref([])
const setTreeRefs = (el, { key }) => {
    if (!el) return
    let index = arrIndex(treeRefs.value, 'id', key)
    if (index !== -1) {
        treeRefs.value[index].ref = el
    } else {
        treeRefs.value.push({ id: key, ref: el })
    }
}
const getTreeRef = async (key) => {
    const itemRef = getArrValue(treeRefs.value)
    if (itemRef.length <= 0) return ''
    const index = arrIndex(itemRef, 'id', key)
    if (index === -1) return ''
    const obj = getObjValue(itemRef[index])
    return obj?.ref
}


//获取权限树的数据
const authTree = ref({})
const getGrantTree = async () => {
    const { data } = await mainApi.grantTree()
    authTree.value = getObjValue(data)
}

//获取选中的数据
const roleData = ref({})
const getRoleData = async (id) => {
    const { data } = await mainApi.getRole(id)
    const res = getObjValue(data)
    let newObjData = {}
    Object.keys(res).forEach((key) => {
        newObjData[key] = []
        const arr = getArrValue(res[key])
        for (let i = 0; i < arr.length; i++) {
            let strs = arr[i].split('---')
            if (strs[1] === 'all') {
                newObjData[key].push(strs[0])
            }
        }
    })
    roleData.value = newObjData
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    submitLoading.value = true
    const paneData = tabPaneData.value
    let newObjData = { roleIds: [rowInfo.value.id] }
    for (let i = 0; i < paneData.length; i++) {
        const item = paneData[i]
        newObjData[item.form] = []
        const refs = await getTreeRef(item.key)
        const all = refs?.getRef()?.getCheckedKeys()
        const half = refs?.getRef()?.getHalfCheckedKeys()
        for (let j = 0; j < all.length; j++) {
            newObjData[item.form].push(all[j] + '---all')
        }
        for (let j = 0; j < half.length; j++) {
            newObjData[item.form].push(half[j] + '---all')
        }
    }
    //发起请求
    const { isRes } = await mainApi.grant(newObjData)
    submitLoading.value = false
    if (!isRes) return
    dialogClose()
    window?.$message?.success('操作成功')
    getDataApi()
}

//关闭弹窗
const dialogClose = () => {
    isShow.value = false
    submitLoading.value = false
    emit('close')
}
</script>

<style lang="scss">
.el-tabs.el-tabs--left.hc-role-auth-dialog {
    position: relative;
    .el-tabs__header.is-left {
        margin-right: 0;
    }
    .el-tabs__content {
        position: relative;
        height: 100%;
        .el-tab-pane {
            position: relative;
            height: 100%;
            width: 100%;
            overflow: auto;
            .el-tree.hc-tree-node-v2 .data-custom-tree-node .label.level-name,
            .hc-tree-node .data-custom-tree-node .label.level-name {
                font-size: 16px;
                font-weight: initial;
            }
        }
    }
}
</style>
