<template>
    <basic-container>
        <avue-crud :option="option" :table-loading="loading" :data="data" v-model="form" v-model:page="page" ref="crud"
            @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad">
            <template #menu-left>
                <el-button type="danger" icon="el-icon-delete" v-if="permission.role_delete" plain
                    @click="handleDelete">删 除
                </el-button>
                <!-- <el-button type="primary" @click="handleGet">下载模版</el-button> -->
                <el-upload :auto-upload="false" :show-file-list="false" action="action" :on-change="handleChange"
                    style="float: right;margin-left: 12px;">
                    <el-button type="primary">导入</el-button>
                </el-upload>
            </template>
            <template #menu-right>

            </template>
            <template #rlueStatus="{ row }">
                <el-switch v-model="row.rlueStatus" />
            </template>
            <template #menu="{ row }">
                <el-button type="primary" text icon="el-icon-setting" plain
                    style="border: 0; background-color: transparent !important" @click.stop="handleRowRole(row)">修改记录
                </el-button>
            </template>
        </avue-crud>
        <el-dialog title="角色权限配置" append-to-body v-model="box" width="345px">
            <el-tabs type="border-card">
                <el-tab-pane label="菜单权限">
                    <el-tree :data="menuGrantList" show-checkbox node-key="id" ref="treeMenu"
                        :default-checked-keys="menuTreeObj" :props="props">
                    </el-tree>
                </el-tab-pane>
                <el-tab-pane label="数据权限">
                    <el-tree :data="dataScopeGrantList" show-checkbox node-key="id" ref="treeDataScope"
                        :default-checked-keys="dataScopeTreeObj" :props="props">
                    </el-tree>
                </el-tab-pane>
                <el-tab-pane label="接口权限">
                    <el-tree :data="apiScopeGrantList" show-checkbox node-key="id" ref="treeApiScope"
                        :default-checked-keys="apiScopeTreeObj" :props="props">
                    </el-tree>
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="box = false">取 消</el-button>
                    <el-button type="primary" @click="submit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </basic-container>
</template>

<script>
import {
    add,
    getRole,
    getRoleAlias,
    getRoleTreeById,
    grant,
    grantTree,
    remove,
    update,
} from '@/api/system/role';
import { mapGetters } from 'vuex';
import website from '@/config/website';
import { validatenull } from '@/utils/validate';
import { getList } from '@/api/base/region';
export default {
    data() {
        return {
            form: {},
            box: false,
            props: {
                label: 'title',
                value: 'key',
            },
            menuGrantList: [],
            dataScopeGrantList: [],
            apiScopeGrantList: [],
            apiGrantList: [],
            menuTreeObj: [],
            dataScopeTreeObj: [],
            apiScopeTreeObj: [],
            selectionList: [],
            query: {},
            loading: true,
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0,
            },
            option: {
                tip: false,
                simplePage: true,
                searchShow: true,
                searchMenuSpan: 6,
                searchIcon: true,
                searchIndex: 3,
                tree: false,
                border: true,
                index: true,
                selection: true,
                viewBtn: true,
                labelWidth: 120,
                searchLabelWidth: 60,
                menuWidth: 350,
                dialogWidth: 600,
                dialogClickModal: false,
                searchEnter: true,
                excelBtn: true,

                column: [
                    {
                        label: '规则ID',
                        prop: 'rlueId',
                        search: true,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '名称',
                        prop: 'rlueName',
                        search: true,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '类型',
                        prop: 'rlueType',
                        search: true,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '优先级',
                        prop: 'rluePriority',
                        search: false,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '状态',
                        prop: 'rlueStatus',
                        search: true,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '创建人',
                        prop: 'createName',
                        search: true,
                        span: 24,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },

                ],
            },
            data: [],
        };
    },
    computed: {
        ...mapGetters(['userInfo', 'permission']),
        permissionList() {
            return {
                addBtn: this.validData(this.permission.role_add, false),
                viewBtn: this.validData(this.permission.role_view, false),
                delBtn: this.validData(this.permission.role_delete, false),
                editBtn: this.validData(this.permission.role_edit, false),
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(',');
        },
        idsArray() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids;
        },
    },
    watch: {
        'form.currentAlias'() {
            const alias = this.form.currentAlias;
            if (!validatenull(alias)) {
                this.form.roleAlias = alias;
            }
        },
    },
    methods: {
        initData(roleId) {
            getRoleTreeById(roleId).then(res => {
                const column = this.findObject(this.option.column, 'parentId');
                column.dicData = res.data.data;
            });
        },
        submit() {
            const menuList = this.$refs.treeMenu.getCheckedKeys();
            const dataScopeList = this.$refs.treeDataScope.getCheckedKeys();
            const apiScopeList = this.$refs.treeApiScope.getCheckedKeys();
            grant(this.idsArray, menuList, dataScopeList, apiScopeList).then(() => {
                this.box = false;
                this.$message({
                    type: 'success',
                    message: '操作成功!',
                });
                this.selectionList = [];
                this.onLoad(this.page);
            });
        },
        rowSave(row, done, loading) {
            add(row).then(
                () => {
                    this.onLoad(this.page);
                    this.$message({
                        type: 'success',
                        message: '操作成功!',
                    });
                    done();
                },
                error => {
                    window.console.log(error);
                    loading();
                }
            );
        },
        rowUpdate(row, index, done, loading) {
            update(row).then(
                () => {
                    this.onLoad(this.page);
                    this.$message({
                        type: 'success',
                        message: '操作成功!',
                    });
                    done();
                },
                error => {
                    window.console.log(error);
                    loading();
                }
            );
        },
        rowDel(row) {
            this.$confirm('确定将选择数据删除?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    return remove(row.id);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: 'success',
                        message: '操作成功!',
                    });
                });
        },

        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        beforeOpen(done, type) {
            if (['add', 'edit'].includes(type)) {
                this.initData(this.form.id);
            }
            if (['edit', 'view'].includes(type)) {
                if (this.form.parentId === '0') {
                    this.form.parentId = '';
                }
            }
            getRoleAlias().then(res => {
                const column = this.findObject(this.option.column, 'currentAlias');
                column.dicData = res.data.data;
            });
            done();
        },
        handleRole() {
            if (this.selectionList.length !== 1) {
                this.$message.warning('只能选择一条数据');
                return;
            }
            this.menuTreeObj = [];
            this.dataScopeTreeObj = [];
            this.apiScopeTreeObj = [];
            grantTree().then(res => {
                this.menuGrantList = res.data.data.menu;
                this.dataScopeGrantList = res.data.data.dataScope;
                this.apiScopeGrantList = res.data.data.apiScope;
                getRole(this.ids).then(res => {
                    this.menuTreeObj = res.data.data.menu;
                    this.dataScopeTreeObj = res.data.data.dataScope;
                    this.apiScopeTreeObj = res.data.data.apiScope;
                    this.box = true;
                });
            });
        },
        handleRowRole(row) {
            this.menuTreeObj = [];
            this.dataScopeTreeObj = [];
            this.apiScopeTreeObj = [];
            grantTree().then(res => {
                this.menuGrantList = res.data.data.menu;
                this.dataScopeGrantList = res.data.data.dataScope;
                this.apiScopeGrantList = res.data.data.apiScope;
                getRole(row.id).then(res => {
                    this.menuTreeObj = res.data.data.menu;
                    this.dataScopeTreeObj = res.data.data.dataScope;
                    this.apiScopeTreeObj = res.data.data.apiScope;
                    this.selectionList.push(row);
                    this.box = true;
                });
            });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning('请选择至少一条数据');
                return;
            }
            this.$confirm('确定将选择数据删除?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    return remove(this.ids);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: 'success',
                        message: '操作成功!',
                    });
                    this.$refs.crud.toggleSelection();
                });
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        refreshChange() {
            this.onLoad(this.page, this.query);
        },
        handleChange(file, fileList) {
            // proxy.$Export.xlsx(file.raw).then((data) => {
            //     data.value = data.results;
            // });
            this.$message({
                type: 'success',
                message: '操作成功!',
            });
        },
        onLoad(page, params = {}) {
            this.loading = true;
            this.data = [
                {
                    rlueId: '2025001',
                    rlueName: '规则一',
                    rlueType: '排序规则',
                    rluePriority: '1',
                    rlueStatus: '0',//0 否 1 是
                    createName: 'admin'
                }
            ]
            this.page.total = this.data.length
            //   getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
            //     this.data = res.data.data.records;
            this.loading = false;
            //     this.page.total = res.data.data.total
            //     this.selectionClear();
            //   });
        },
    },
};
</script>
