<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" @filter="filterChange">

            <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" size="small" icon="el-icon-delete">导入</el-button>
                </el-upload> -->
            </template>
            <template #menu-right>

            </template>
            <template #rlueId="{ row }">
                <el-text v-if="row.rlueStatus" type="primary">{{ row.rlueId }}</el-text>
                <el-text v-else type="danger">{{ row.rlueId }}</el-text>
            </template>
            <template #rlueStatus="{ row }">
                <el-switch v-model="row.rlueStatus" @change="rlueStatusFn" />
            </template>
            <template #rluePriority="{ row }">
                <el-tag v-if="row.rlueStatus">{{ row.rluePriority }}</el-tag>
                <el-tag type="error" v-else>{{ row.rluePriority }}</el-tag>
            </template>
            <template #menu="{ row }">
                <el-button type="primary" text icon="el-icon-tickets" plain
                    style="border: 0; background-color: transparent !important" @click.stop="updateLog(row)"
                    size="medium">修改记录
                </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" size="medium">取 消</el-button>
                    <el-button type="primary" @click="submit" size="medium">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog title="修改记录" append-to-body v-model="updateVisible" width="820px">
            <avue-crud :option="optionLog" :table-loading="loading" :data="dataLog" 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">
            </avue-crud>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateVisible = false" size="medium">取 消</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 {
            updateVisible: false,
            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: {
                size: 'medium',
                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: 100,
                menuWidth: 350,
                dialogWidth: 600,
                dialogClickModal: false,
                searchEnter: true,
                excelBtn: true,
                filterBtn: true,
                index: false,
                searchShowBtn: false,
                column: [

                    {
                        label: '规则ID',
                        prop: 'rlueId',
                        search: false,
                        sortable: true,
                        filter: true,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '名称',
                        prop: 'rlueName',
                        search: true,
                        sortable: true,
                        searchLabelWidth:80,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '类型',
                        prop: 'rlueType',
                        search: true,
                        sortable: true,
                        searchLabelWidth:80,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '优先级',
                        prop: 'rluePriority',
                        search: false,
                        sortable: true,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '状态',
                        prop: 'rlueStatus',
                        search: false,
                        sortable: true,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '创建人',
                        prop: 'createName',
                        search: false,
                        sortable: true,
                        span: 12,
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名称',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        searchLabelWidth:40,
                        label: '',
                        prop: 'serchTxt',
                        search: true,
                        hide: true,
                        display: false,
                        searchPlaceholder: '关键字模糊搜索',
                        span: 12,
                        searchRange: true,
                        suffixIcon: "el-icon-date",
                        prefixIcon: "el-icon-search"
                    },

                ],
            },
            optionLog: {
                size: 'medium',
                tip: false,
                simplePage: true,
                searchShow: false,
                border: true,
                index: true,
                selection: true,
                viewBtn: true,
                searchEnter: true,
                menu: false,
                addBtn: false,
                index: false,
                column: [
                    {
                        label: '规则ID',
                        prop: 'rlueId',
                    },
                    {
                        label: '名称',
                        prop: 'rlueName',
                    },
                    {
                        label: '修改人',
                        prop: 'updateName',

                    },
                    {
                        label: '修改时间',
                        prop: 'updateTime',
                        width: 150,

                    },

                ],
            },
            dataLog: [],
            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;
            });
        },
        filterChange(result) {
            console.log('result-----------------------',result)
        // this.$message.success('过滤器' + JSON.stringify(result))
        },
        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: '操作成功!',
            });
        },
        updateLog() {
            this.updateVisible = true
            this.dataLog = [
                {
                    rlueId: '2025001',
                    rlueName: '规则一',
                    createName: 'admin',
                    updateTime: '2025-09-05 12:04:40',
                    updateName: 'admin',
                },
                {
                    rlueId: '2025001',
                    rlueName: '规则一',
                    createName: 'admin',
                    updateTime: '2025-09-04 12:04:40',
                    updateName: '张迪',
                }
            ]
        },
        rlueStatusFn(val) {
            if (val) {
                this.$message({
                    type: 'success',
                    message: '启用成功!',
                });
            } else {
                this.$message({
                    type: 'error',
                    message: '禁用成功!',
                });
            }
        },
        onLoad(page, params = {}) {
            this.loading = true;
            this.data = [
                {
                    rlueId: '2025001',
                    rlueName: '规则一',
                    rlueType: '排序规则',
                    rluePriority: '1',
                    rlueStatus: false,//false 否 true 是
                    createName: 'admin'
                },
                {
                    rlueId: '2025002',
                    rlueName: '规则二',
                    rlueType: '排序规则',
                    rluePriority: '2',
                    rlueStatus: true,//false 否 true 是
                    createName: '张迪'
                },
                {
                    rlueId: '2025003',
                    rlueName: '规则三',
                    rlueType: '排序规则',
                    rluePriority: '3',
                    rlueStatus: true,//false 否 true 是
                    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>
