<template>
    <div>
        <el-card class="tjm_card_style_custom">
        <!--      <div class="tjm_card_title">查询表格</div>-->
        <!--      <div class="tjm_card_select">-->
        <!--        <div class="tjm_card_select_left">-->
        <!--          <el-form-->
        <!--            :inline="true"-->
        <!--            :model="formInline"-->
        <!--            label-width="80px"-->
        <!--            :label-position="'left'"-->
        <!--          >-->
        <!--            <el-form-item label="角色名称">-->
        <!--              <el-input-->
        <!--                v-model="formInline.name"-->
        <!--                placeholder="请输入"-->
        <!--                clearable-->
        <!--              />-->
        <!--            </el-form-item>-->
        <!--            <el-form-item label="角色编码">-->
        <!--              <el-input-->
        <!--                v-model="formInline.code"-->
        <!--                placeholder="请输入"-->
        <!--                clearable-->
        <!--              />-->
        <!--            </el-form-item>-->
        <!--            <el-form-item label="创建时间">-->
        <!--              <el-date-picker-->
        <!--                v-model="formInline.date"-->
        <!--                type="daterange"-->
        <!--                placeholder="Pick a date"-->
        <!--                clearable-->
        <!--              />-->
        <!--            </el-form-item>-->
        <!--            <el-form-item label="角色状态">-->
        <!--              <el-select-->
        <!--                v-model="formInline.status"-->
        <!--                clearable-->
        <!--                placeholder="请选择"-->
        <!--              >-->
        <!--                <el-option label="启用" value="1" />-->
        <!--                <el-option label="禁用" value="2" />-->
        <!--              </el-select>-->
        <!--            </el-form-item>-->
        <!--          </el-form>-->
        <!--        </div>-->
        <!--        <div class="tjm_card_select_right">-->
        <!--          <div>-->
        <!--            <el-button type="primary">-->
        <!--              <el-icon class="tjm_btn_icon_right">-->
        <!--                <tjm-icon-ep-Plus />-->
        <!--              </el-icon>-->
        <!--              搜索-->
        <!--            </el-button>-->
        <!--          </div>-->

        <!--          <div>-->
        <!--            <el-button>-->
        <!--              <el-icon class="tjm_btn_icon_right">-->
        <!--                <tjm-icon-ep-RefreshRight />-->
        <!--              </el-icon>-->
        <!--              重置-->
        <!--            </el-button>-->
        <!--          </div>-->
        <!--        </div>-->
        <!--      </div>-->
        <!--      <el-divider />-->
            <div class="tjm_card_tools">
                <div class="tjm_card_tools_left">
                    <el-button type="primary" @click="addClick">
                        <el-icon class="tjm_btn_icon_right">
                            <tjm-icon-ep-Plus />
                        </el-icon>
                        新增
                    </el-button>
                    <!-- <el-button type="danger">
                        <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-delete /></el-icon>
                        批量删除
                    </el-button> -->
                </div>
                <!-- <div class="tjm_card_tools_right">
                    <el-button>
                        <el-icon class="tjm_btn_icon_right">
                            <tjm-icon-ep-Download />
                        </el-icon>
                        导出
                    </el-button>
                </div> -->
            </div>
            <div class="tjm_cart_table">
                <el-table
                    header-cell-class-name="tjm_cart_table_header"
                    height="400"
                    :data="tableData"
                    v-loading="loading"
                    border
                    style="width: 100%"
                    row-key="id"
                >
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="name" label="角色名称" width="180" />
                    <el-table-column prop="code" label="角色代码" width="180" />
                    <el-table-column prop="description" label="角色描述" />
                    <el-table-column prop="state" label="角色状态">
                        <template #default="scope">
                            <el-tag
                                :type="scope.row.state === 1 ? 'danger' : 'success'"
                                disable-transitions>
                                {{ scope.row.state === 1 ? '禁用' : '启用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ope" width="240" label="操作">
                        <template #default="scope">
                            <el-button link type="primary" icon="Edit" @click="showChange(scope.row)">修改</el-button>
                            <el-button link type="primary" icon="Plus" @click="sendPermissions(scope.row)">分配权限</el-button>
                            <el-button link type="primary" icon="Delete" @click="deleteRoleClick(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="tjm_cart_pagination">
                <el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑 -->
        <el-dialog :title="dialogTitle" v-model="addShow" append-to-body @close="resetForm">
            <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="角色名称" prop="name">
                            <el-input
                                v-model="form.name"
                                placeholder="请输入角色名称"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色代码" prop="code">
                            <el-input
                                v-model="form.code"
                                placeholder="请输入角色代码"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色描述" prop="description">
                            <el-input
                                v-model="form.description"
                                placeholder="请输入角色描述"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="是否启用" prop="state">
                            <el-switch v-model="form.state" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="addCancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 分配权限 -->
        <el-dialog title="分配权限" v-model="sendShow" append-to-body>
            <el-tabs type="border-card" v-model="activeName" class="demo-tabs">
                <el-tab-pane label="菜单权限" name="first">
                    <el-tree
                        :key="checkedMenuKeys"
                        ref="treeRef"
                        :data="treeData"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :default-checked-keys="checkedMenuKeys"
                        :props="defaultProps"
                    />
                </el-tab-pane>
                <!-- <el-tab-pane label="数据权限" name="second">
                    <el-tree
                        :key="checkedMenuKeys2"
                        ref="treeRef2"
                        :data="treeData2"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :default-checked-keys="checkedMenuKeys2"
                        :props="defaultProps"
                    />
                </el-tab-pane> -->
            </el-tabs>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="saveAllTree">确 定</el-button>
                    <el-button @click="sendShow = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    addRole,
    deleteRole,
    getMenuTree, getPortTree,
    getRoleList,
    getRoleMenuTree,
    getRolePortTree,
    setRole,
    setRoleMenuTree,
    setRolePortTree
} from '@/api/system/role'

const activeName = ref('first')
const defaultProps = ref({
    children: 'children',
    label: 'name'
})
const treeData = ref([])
const treeData2 = ref([])
const loading = ref(false) //加载
// const isExpandAll = ref(false) //展开
const dialogTitle = ref('新增')
const addShow = ref(false)
const sendShow = ref(false)
const selectedRow = ref('')
const tableData = ref([])

const form = ref({
    name: null,
    code: null,
    state: true,
    description: null
})
const rules = ref({
    name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '角色代码不能为空', trigger: 'blur' }]
})

const checkedMenuKeys = ref([])
const checkedMenuKeys2 = ref([])

const { proxy } = getCurrentInstance()

//查询
const params = ref({
    page: 1,
    size: 10
})
const total = ref(0)

onMounted(() => {
    getList()
})

function getList() {
    loading.value = true
    getRoleList(params.value).then(res => {
        loading.value = false
        if (res.code === 200) {
            total.value = res.data.total
            tableData.value = res.data.records
        }
    }).catch(() => {
        loading.value = false
    })
}

function currentChange(e) {
    params.value.page = e
    getList()
}

function addClick() {
    dialogTitle.value = '新增'
    addShow.value = true
}

function showChange(row) {
    console.log(row)
    dialogTitle.value = '修改'
    form.value.state = row.state === 0
    form.value.description = row.description
    form.value.code = row.code
    form.value.name = row.name
    form.value.id = row.id
    addShow.value = true
}

function addCancel() {
    addShow.value = false
    resetForm()
}

function resetForm() {
    form.value = {
        name: null,
        code: null,
        state: true,
        description: null
    }
    if (proxy.$refs['userRef']) {
        proxy.$refs['userRef'].resetFields()
    }
    console.log('重置表单')
}

function submitForm() {
    proxy.$refs['userRef'].validate(valid => {
        if (valid) {
            if (form.value.id) {
                console.log('修改表单')
                const params = {
                    ...form.value
                }
                params.state = params.state ? 0 : 1
                setRole(params).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success'
                        })
                        addShow.value = false
                        resetForm()
                        getList()
                    }
                })
            } else {
                console.log('新增表单')
                const params = {
                    ...form.value
                }
                params.state = params.state ? 0 : 1
                addRole(params).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: '新增成功',
                            type: 'success'
                        })
                        addShow.value = false
                        resetForm()
                        getList()
                    }
                })
            }
        }
    })
}

function sendPermissions(row) {
    console.log(row)
    selectedRow.value = row

    //获取菜单树
    getMenuTree().then(res => {
        if (res.code === 200) {
            treeData.value = res.data
            //获取角色菜单树
            getRoleMenuTree(row.id).then(resp => {
                checkedMenuKeys.value = []
                if (!resp.data.length) {
                    proxy.$refs['treeRef'] && proxy.$refs['treeRef'].setCheckedNodes(checkedMenuKeys.value, false)
                    sendShow.value = true
                } else {
                    //
                    let keys = []
                    for (let li of resp.data) {
                        keys.push(li.id)
                    }
                    // //解决
                    // //首先拿到 树形数据 所有的最深层的节点
                    let lastKeys = deepList([], treeData.value[0].children)
                    // //拿着接口返回的选中的 去所有深层节点查找  取交集  就是 最终选中的
                    checkedMenuKeys.value = [...new Set(lastKeys)].filter(item => {
                        return keys.includes(item)
                    })
                    sendShow.value = true
                }
            })
        }
    })

    getPortTree().then(res => {
        if (res.code === 200) {
            treeData2.value = res.data
            //获取角色接口菜单树
            getRolePortTree(row.id).then(resp => {
                checkedMenuKeys2.value = []
                if (!resp.data.length) {
                    proxy.$refs['treeRef2'].setCheckedNodes(checkedMenuKeys2.value, false)
                    sendShow.value = true
                    console.log('都没选中接口')
                } else {
                    //
                    let keys = []
                    for (let li of resp.data) {
                        keys.push(li.id)
                    }
                    // //解决
                    // //首先拿到 树形数据 所有的最深层的节点
                    let lastKeys = deepList([], treeData2.value[0].children)
                    // //拿着接口返回的选中的 去所有深层节点查找  取交集  就是 最终选中的
                    checkedMenuKeys2.value = [...new Set(lastKeys)].filter(item => {
                        return keys.includes(item)
                    })
                    console.log(checkedMenuKeys2.value, '123')
                    sendShow.value = true
                }
            })
        }
    })
}

function deepList(lastKeys, data) {
    data.map(item => {
        if (item.children && item.children.length > 0) {
            deepList(lastKeys, item.children)
        } else {
            lastKeys.push(item.id)
        }
    })
    return lastKeys
}

function saveAllTree() {
    saveTree()
    savePortTree()
}

function saveTree() {
    // 获取所有选中的节点信息（包括未完全选中的父节点）
    const halfCheckedKeys = proxy.$refs['treeRef'].getHalfCheckedKeys() // 获取半选中（即父节点未完全选中）节点的 keys
    const checkedKeys = proxy.$refs['treeRef'].getCheckedKeys()
    console.log(halfCheckedKeys, '半选菜单', checkedKeys, '选中的菜单')
    // 合并已选中的节点和半选中的节点 keys，因为半选中的节点代表有子节点被选中，需要被包括在内
    const allKeys = [...new Set([...halfCheckedKeys, ...checkedKeys])]

    // 调用 API，传递所有必要的节点
    setRoleMenuTree(selectedRow.value.id, { menuIds: allKeys.join(','), roleId: selectedRow.value.id }).then(res => {
        if (res.code === 200) {
            // ElMessage({
            //   message: '分配成功',
            //   type: 'success'
            // })
            sendShow.value = false
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            })
        }
    })
}

function savePortTree() {
    // 获取所有选中的节点信息（包括未完全选中的父节点）
    const halfCheckedKeys = proxy.$refs['treeRef2'].getHalfCheckedKeys() // 获取半选中（即父节点未完全选中）节点的 keys
    const checkedKeys = proxy.$refs['treeRef2'].getCheckedKeys()
    console.log(halfCheckedKeys, '半选菜单', checkedKeys, '选中的菜单')
    // 合并已选中的节点和半选中的节点 keys，因为半选中的节点代表有子节点被选中，需要被包括在内
    const allKeys = [...new Set([...halfCheckedKeys, ...checkedKeys])]

    // 调用 API，传递所有必要的节点
    setRolePortTree({ permissionType: 1, scopeIds: allKeys.join(','), roleId: selectedRow.value.id }).then(res => {
        if (res.code === 200) {
            ElMessage({
                message: '分配成功',
                type: 'success'
            })
            sendShow.value = false
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            })
        }
    })
}

function deleteRoleClick(row) {
    ElMessageBox.confirm('是否确认删除"' + row.name + '"?', '删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteRole(row.id).then(res => {
            if (res.code === 200) {
                ElMessage({
                    message: '删除成功',
                    type: 'success'
                })
                getList()
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error'
                })
            }
        })
    })
}
</script>

<style lang="scss" scoped></style>