<template>
    <div class="default-main" style="display: flex" :style="{ height: height }">
        <div style="flex: 1; overflow: hidden">
            <div class="custom-table-header">
                <div class="title">角色列表</div>
                <el-button :icon="Plus" type="primary" @click="addRole" class="ml10">新增</el-button>
            </div>
            <Table ref="tableRef" :row-config="{ isCurrent: true, isHover: true }" @currentChange="currentChange" />
        </div>
        <div>
            <el-tabs type="border-card">
                <el-tab-pane label="菜单">
                    <Tree
                        v-if="menuListId"
                        ref="treeRef"
                        show-checkbox
                        width="350px"
                        :data="menuTree"
                        :checkStrictly="false"
                        @checkChange="checkChange"
                    ></Tree>
                    <el-empty
                        style="width: 350px; padding-top: 300px; box-sizing: border-box"
                        description="请选择角色"
                        v-else
                    />
                </el-tab-pane>
                <el-tab-pane label="系统">
                    <div class="mt10 mr10" style="display: flex; justify-content: end">
                        <el-button type="primary" icon="el-icon-Select" @click="saveSystem">保存</el-button>
                    </div>
                    <el-checkbox-group v-model="systemIds" class="md10 system">
                        <el-checkbox v-for="item in systemList" :label="item.name" :value="item.id" :key="item.id" />
                    </el-checkbox-group>
                </el-tab-pane>
            </el-tabs>
        </div>
        <PopupForm ref="popupRef"></PopupForm>
    </div>
</template>
<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted, provide } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import Tree from '@/components/tree/allocation.vue'
import { functionTree } from '@/api/user-boot/function'
import { getFunctionsByRoleIndex, updateRoleMenu, getSystemByRoleId, systemAdd } from '@/api/user-boot/roleFuction'
import { mainHeight } from '@/utils/layout'
import { del } from '@/api/user-boot/role'
import { ElMessage } from 'element-plus'
import PopupForm from './popupForm.vue'
import { useAdminInfo } from '@/stores/adminInfo'
import { useDictData } from '@/stores/dictData'
const dictData = useDictData()
const systemList = dictData.getBasicData('System_Type')
const adminInfo = useAdminInfo()
defineOptions({
    name: 'auth/role'
})
const systemIds = ref([])
const height = mainHeight(20).height
const treeRef = ref()
const menuTree = ref<treeData[]>([])
const popupRef = ref()
const tableRef = ref()
const checkStrictly = ref(true)
const menuListId = ref('')
const tableStore = new TableStore({
    showPage: false,
    url: '/user-boot/role/selectRoleDetail?id=' + adminInfo.$state.userType,
    method: 'POST',
    column: [
        { title: '角色名称', field: 'name', align: 'center' },
        { title: '角色编码', field: 'code', align: 'center' },
        { title: '备注', field: 'remark', align: 'center' },
        {
            title: '状态',
            field: 'state',
            width: '80',
            render: 'tag',
            custom: {
                0: 'danger',
                1: 'success'
            },
            replaceValue: {
                0: '注销',
                1: '正常'
            }
        },
        {
            title: '操作',
            align: 'center',
            width: '180',
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        popupRef.value.open('编辑角色', row)
                    }
                },
                {
                    name: 'del',
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除该角色吗？'
                    },
                    click: row => {
                        del([row.id]).then(() => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                }
            ]
        }
    ],
    loadCallback: () => {
        tableRef.value.getRef().setCurrentRow(tableStore.table.data[0])
        currentChange({
            row: tableStore.table.data[0]
        })
    }
})
tableStore.table.params.searchValue = ''

provide('tableStore', tableStore)
const filterData = (arr: any[]) => {
    // return arr.filter((item: any) => {
    //     item.name = item.title
    //     if (item.children.length) {
    //         item.children = filterData(item.children)
    //     }
    //     return item.type === 0
    // })
    arr.forEach((item: any) => {
        item.name = item.title
        if (item.children.length) {
            filterData(item.children)
        }
    })
}
functionTree().then((res: any) => {
    filterData(res.data)
    menuTree.value = res.data
})

const currentChange = (data: any) => {
    checkStrictly.value = true
    menuListId.value = data.row.id
    getFunctionsByRoleIndex({ id: data.row.id }).then((res: any) => {
        treeRef.value.treeRef.setCheckedKeys(res.data.map((item: any) => item.id))
    })
    getSystemByRoleId({ id: data.row.id }).then((res: any) => {
        systemIds.value = res.data.systemIds || []
    })
}

const timeout = ref<NodeJS.Timeout>()
const checkChange = (data: any) => {
    // if (checkStrictly.value) {
    //     checkStrictly.value = false
    //     return
    // }

    updateRoleMenu({
        id: menuListId.value,
        idList: treeRef.value.treeRef.getCheckedNodes(false, true).map((node: any) => node.id)
    })
        .then(() => {
            ElMessage.success('操作成功!')
            treeRef.value.loading = false
        })
        .catch(() => {
            treeRef.value.loading = false
        })
}
const saveSystem = () => {
    systemAdd({
        roleId: menuListId.value,
        systemIds: systemIds.value
    })
        .then(() => {
            ElMessage.success('操作成功!')
            treeRef.value.loading = false
        })
        .catch(() => {
            treeRef.value.loading = false
        })
}
onMounted(() => {
    tableStore.index()
})
const addRole = () => {
    popupRef.value.open('新增角色')
}
</script>

<style lang="scss" scoped>
:deep(.el-tabs--border-card > .el-tabs__content) {
    padding: 0px !important;
}
.system {
    width: 330px;
    height: calc(100vh - 225px);
    border: 1px solid var(--el-border-color);
    padding: 5px 10px;
    display: flex;
    flex-direction: column;
}
</style>
