<template>
    <div>
        <el-card class="tjm_card_style_custom">
            <div class="tjm_cart_table">
                <el-table
                    header-cell-class-name="tjm_cart_table_header"
                    :data="tableData"
                    v-loading="tableLoading"
                    border
                    lazy
                    :load="loadTalbeTree"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                    row-key="id"
                >
                    <!-- <el-table-column type="selection" width="55" /> -->
                    <el-table-column prop="name" width="300" label="菜单名称" />
                    <el-table-column prop="path" width="350" label="菜单路由" />
                    <el-table-column prop="code" label="菜单代码" />
                    <el-table-column prop="type" label="类型">
                        <template #default="scope">
                            <el-tag :type="scope.row.type === 1 ? 'info' : 'success'">{{ scope.row.type === 1 ? '菜单' : '按钮' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="menuType" label="设备">
                        <template #default="scope">
                            <el-tag :type="scope.row.menuType === 1 ? 'info' : 'success'">
                                {{ scope.row.menuType === 1 ? 'Cloud端' : scope.row.menuType === 2 ? 'APP端' : 'Boot端' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="icon" label="图标">
                        <template #default="scope">
                            <!-- <el-icon size="18">
                                <component :is="scope.row.icon" />
                            </el-icon> -->
                        </template>
                    </el-table-column>
                    <el-table-column prop="sort" label="排序" />
                    <el-table-column prop="ope" width="120" label="操作">
                        <template #default="scope">
                            <el-button link type="primary" icon="Edit" @click="editItem(scope.row)">权限配置</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        <el-drawer
            v-model="drawerShow"
            title="权限配置"
            direction="rtl"
            size="50%"
        >
            <el-button style="margin-bottom: 20px" type="primary" @click="addPower">
                <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-Plus /></el-icon>
                新增
            </el-button>
            <el-table
                header-cell-class-name="tjm_cart_table_header"
                :data="powerData"
                border
                width="100%"
            >
                <el-table-column type="index" label="序号" width="55" />
                <el-table-column prop="scopeName" label="权限名称" />
                <el-table-column prop="resourceCode" label="权限编号" />
                <el-table-column prop="scopeColumn" label="权限字段" />
                <el-table-column prop="scopeType" label="规则类型" />
                <el-table-column prop="ope" label="操作">
                    <template #default="scope">
                        <el-tooltip content="查看" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="View"
                                @click="checkPower(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="编辑" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="Edit"
                                @click="editPower(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="Delete"
                                @click="deletePower(scope.row)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px; display: flex; justify-content: right">
                <el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange" />
            </div>
        </el-drawer>

        <el-dialog :title="dialogTitle" v-model="dialogShow" width="680px" append-to-body>
            <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px" :disabled="formLock">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="权限名称" prop="scopeName">
                            <el-input v-model="form.scopeName" placeholder="请输入权限名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="权限编号" prop="resourceCode">
                            <el-input
                                v-model="form.resourceCode"
                                placeholder="请输入权限编号"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="权限字段" prop="scopeColumn">
                            <el-input
                                v-model="form.scopeColumn"
                                placeholder="请输入权限字段"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规则类型" prop="scopeType">
                            <el-select v-model="form.scopeType" clearable @change="scopeTypeSelect">
                                <el-option v-for="(item, index) in ruleList" :key="index" :value="item.value" :label="item.label">{{ item.label }}</el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="可见字段" prop="scopeField">
                            <el-input
                                v-model="form.scopeField"
                                placeholder="请输入菜单描述"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="权限类名" prop="scopeClass">
                            <el-input
                                v-model="form.scopeClass"
                                placeholder="请输入权限类名"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                type="textarea"
                                v-model="form.remark"
                                placeholder="请输入备注"
                                clearable
                                autosize
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-if="!formLock" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getMainList, getPowerList, scopeSave, scopeUpdate, scopeRemove } from '@/api/system/dataList'
import { getMenuTree } from '@/api/system/menu'

const tableLoading = ref(false) //加载
const drawerShow = ref(false)
const total = ref(0)
//查询
const params = ref({
    page: 1,
    size: 10
})
const tableData = ref([])
const allTableData = ref([])
const powerData = ref([])
const dialogTitle = ref('新增')
const currentRow = ref({})
const dialogShow = ref(false)
const formLock = ref(false)
const { proxy } = getCurrentInstance()
const ruleList = ref([
    { label: '全部可见', value: 1 },
    { label: '本人可见', value: 2 },
    { label: '所在机构可见', value: 3 },
    { label: '所在机构及子级可见', value: 4 },
    { label: '自定义', value: 5 }
])
const form = ref({
    scopeName: '',
    resourceCode: '',
    scopeColumn: '-',
    scopeType: '',
    scopeField: "*",
    scopeClass: '',
    remark: 0
})
const rules = ref({
    scopeName: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
    resourceCode: [{ required: true, message: '权限编号不能为空', trigger: 'blur' }],
    scopeColumn: [{ required: true, message: '权限字段不能为空', trigger: 'blur' }],
    scopeType: [{ required: true, message: '规则类型不能为空', trigger: 'blur' }],
    scopeField: [{ required: true, message: '可见字段不能为空', trigger: 'blur' }],
    scopeClass: [{ required: true, message: '权限类名不能为空', trigger: 'blur' }],
})

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

function loadTalbeTree(tree, treeNode, resolve) {
    const idCopy = JSON.parse(JSON.stringify(tree.idList))
    let resolveArr = allTableData.value
    let id = tree.idList.shift()
    while (id) {
        const tarItem = resolveArr.find(item => item.id === id)
        if (tarItem) {
            tarItem.loadedChildren = true
            resolveArr = tarItem.children
        }
        id = tree.idList.shift()
    }
    resolveArr = JSON.parse(JSON.stringify(resolveArr))
    resolveArr.forEach(item => {
        item.hasChildren = item.children && item.children.length > 0
        item.children = null
        item.idList = JSON.parse(JSON.stringify(idCopy))
        item.idList.push(item.id)
    })
    tree.loadedChildren = true
    resolve(resolveArr)
}


function getList() {
    tableLoading.value = true
    getMainList({ systemCode: 10001 }).then(res => {
        tableLoading.value = false
        if (res.code === 200) {
            if (res.data.length && res.data[0].children) {
                const array = []
                res.data[0].children.forEach((item) => {
                    if (item.menuType === 3) {
                        array.push(item)
                    }
                })
                res.data = array
            }
            allTableData.value = res.data || []
            tableData.value = JSON.parse(JSON.stringify(res.data)).map(item => {
                item.hasChildren = item.children && item.children.length > 0
                item.children = null
                item.idList = [item.id]
                return item
            })
        }
    }).catch(() => {
        tableLoading.value = false
    })
}

function getSubList() {
    getPowerList({ menuId: currentRow.value.id, ...params.value }).then(res => {
        if (res.code === 200) {
            powerData.value = res.data.records
            total.value = res.data.total
            drawerShow.value = true
        }
    })
}

function currentChange(e) {
    params.value.page = e
    getPowerList({ menuId: currentRow.value.id, ...params.value }).then(res => {
        if (res.code === 200) {
            powerData.value = res.data.records
            total.value = res.data.total
            drawerShow.value = true
        }
    })
}

function editItem(row) {
    console.log(row)
    currentRow.value = row
    getPowerList({ menuId: row.id, current: params.value.page, size: params.value.size }).then(res => {
        if (res.code === 200) {
            powerData.value = res.data.records
            total.value = res.data.total
            drawerShow.value = true
        }
    })
}

function checkPower(row) {
    formLock.value = true
    dialogTitle.value = '查看权限'
    form.value = { ...row }
    dialogShow.value = true
}

function editPower(row) {
    formLock.value = false
    form.value = { ...row }
    dialogTitle.value = '修改权限'
    dialogShow.value = true
}

function addPower() {
    form.value = {
        scopeName: null,
        resourceCode: '',
        scopeColumn: '-',
        scopeType: null,
        scopeField: "*",
        scopeClass: null,
        remark: 0
    }
    formLock.value = false
    dialogTitle.value = '新增权限'
    form.value.scopeName = currentRow.value.name + "[暂无]"
    form.value.resourceCode = currentRow.value.code
    dialogShow.value = true
}
function scopeTypeSelect(value) {
    form.value.scopeName = currentRow.value.name + "[" + ruleList.value[value - 1].label + "]"
}
function resetForm() {
    form.value = {
        scopeName: null,
        resourceCode: '',
        scopeColumn: '-',
        scopeType: null,
        scopeField: "*",
        scopeClass: null,
        remark: 0
    }
    if (proxy.$refs['menuRef']) {
        proxy.$refs['menuRef'].resetFields()
    }
    console.log('重置表单')
}

function submitForm() {
    proxy.$refs['menuRef'].validate(valid => {
        if (valid) {
            if (form.value.id) {
                console.log('修改表单')
                const params = {
                    ...form.value
                }
                scopeUpdate(params).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success'
                        })
                        dialogShow.value = false
                        resetForm()
                        getSubList()
                    }
                })
            } else {
                console.log('新增表单')
                const params = {
                    menuId: currentRow.value.id,
                    ...form.value
                }
                scopeSave(params).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: '新增成功',
                            type: 'success'
                        })
                        dialogShow.value = false
                        resetForm()
                        getSubList()
                    }
                })
            }
        }
    })
}

function cancel() {
    dialogShow.value = false
    resetForm()
}

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

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