<template>
    <div class="user">
        <Card :bordered="false" dis-hover>
            <bingo-list
                :columns="columns"
                :page="false"
                :showBtnType="'all'"
                :showBtnOutNum="3"
                :toolbarNew="true"
                ref="bingoList"
                :searchList="searchList"
                :dataApi="Api"
                :queryData="queryData"
                :isSearch="true"
                :isSearchAdvance="true"
                :showSwitchBtn="false"
                :autoFitWdith="false"
                :processData="processData"
                row-key="id"
                :isCustomBtn="true"
                @on-query-submit="querySubmit"
                @on-add-new="onAddNew"
                :showNewBtn="auth.add!==0"
                v-if="auth.table!==0"
            >
                <template slot="action" slot-scope="{ row, index }">
                    <div class="action-all" >
                        <Button
                            type="success"
                            size="small"
                            @click="onAddNew(row)"
                            v-if="auth.addChild!==0"
                        >
                            <i class="icon iconfont iconiconjia"></i
                            ><span class="font">新建</span></Button
                        >
                    <Button
                            type="primary"
                            size="small"
                            @click="onEditBtn(row.id)"
                            v-if="auth.edit!==0"
                        >
                            <i class="icon iconfont iconbianji"></i
                            ><span class="font">编辑</span></Button
                        >

                        <Button
                            type="error"
                            size="small"
                            @click="onDeleteBtn(row)"
                            v-if="auth.delete!==0"
                        >
                            <i class="icon iconfont iconshanchu"></i
                            ><span class="font">删除</span></Button
                        >
                        <span>
                            <Dropdown
                                class="toolbar-down-button drop-font-icon"
                                placement="left-start"
                                trigger="click"
                            >
                                <span class="font">更多</span>
                                <Icon type="ios-arrow-down" />
                                <Dropdown-menu
                                    slot="list"
                                >
                                    <Button
                                        class="btn-more"
                                        size="small"
                                        @click="allot(row)"
                                        v-if="auth.allotRole!==0"
                                    >
                                    <i class="icon iconfont iconjiaoseguanli"></i>
                                    <span class="font">分配角色</span></Button
                                    >
                                    <Button
                                        class="btn-more"
                                        size="small"
                                        @click="dataAuth(row)"
                                        v-if="row.type===2 && (auth.dataAuth!==0)"
                                    ><i class="icon iconfont iconqueding"></i>
                                    <span class="font">数据权限</span></Button
                                    >
                                </Dropdown-menu>
                            </Dropdown>
                        </span>
                    </div>
                </template>
            <!-- 高级搜索 -->
                <template slot="queryForm">
                    <bingo-grid-item>
                        <bingo-form-item label="菜单名称" prop="nameCn">
                            <Input
                                v-model="queryData.nameCn"
                                placeholder="请输入菜单名称"
                            />
                        </bingo-form-item>
                    </bingo-grid-item>
                    <bingo-grid-item>
                        <bingo-form-item label="图标" prop="icon">
                            <Input
                                v-model="queryData.icon"
                                placeholder="请输入图标"
                            />
                        </bingo-form-item>
                    </bingo-grid-item>
                    <!-- <bingo-grid-item>
                        <bingo-form-item label="是否显示" prop="isShow">
                            <Input
                                v-model="queryData.isShow"
                                placeholder="请输入是否显示"
                            />
                        </bingo-form-item>
                    </bingo-grid-item> -->
                    <!-- <bingo-grid-item>
                        <bingo-form-item label="模块id" prop="moduleId">
                            <Input
                                v-model="queryData.moduleId"
                                placeholder="请输入模块id"
                            />
                        </bingo-form-item>
                    </bingo-grid-item>
                    <bingo-grid-item>
                        <bingo-form-item label="父权限ID" prop="parentId">
                            <Input
                                v-model="queryData.parentId"
                                placeholder="请输入父权限ID"
                            />
                        </bingo-form-item>
                    </bingo-grid-item> -->
                    <bingo-grid-item>
                        <bingo-form-item label="类型" prop="type">
                            <Input
                                v-model="queryData.type"
                                placeholder="请输入类型"
                            />
                        </bingo-form-item>
                    </bingo-grid-item>
                    <bingo-grid-item>
                        <bingo-form-item label="路径" prop="url">
                            <Input
                                v-model="queryData.url"
                                placeholder="请输入路径"
                            />
                        </bingo-form-item>
                    </bingo-grid-item>
                </template>
            </bingo-list>
        </Card>
        <Modal v-model="isShowNewForm" :title="isAdd==true?'新建':'修改'" @on-ok="onOk" :width="900">
            <Form ref="formAdd" :model="formAdd" label-position="right" :label-width="90">
                <Row>
                    <Col :span="12">
                        <bingo-form-item label="上级菜单">
                            <TreeSelect v-model="formAdd.parentId" :data="menuData" transfer @on-change="onChangeSelectTree"/>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="菜单名称">
                            <Input type="text" v-model="formAdd.nameCn" placeholder="请输入菜单名称">
                            </Input>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="德文名称">
                            <Input type="text" v-model="formAdd.nameDe" placeholder="请输入德文名称">
                            </Input>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="英文名称">
                            <Input type="text" v-model="formAdd.nameEn" placeholder="请输入英文名称">
                            </Input>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="图标">
                            <Poptip
                                placement="bottom-start"
                                width="460"
                                trigger="click"
                                @on-popper-show="popperShow"
                                transfer
                            >
                            <Input v-model="formAdd.icon" placeholder="点击选择图标" type="text" readonly>
                                <i v-if="formAdd.icon" slot="prefix" class="icon iconfont" :class="'icon'+formAdd.icon"></i>
                                <Icon v-else slot="prefix" type="ios-search"></Icon>
                            </Input>
                                <div class="api" slot="content">
                                    <IconSelect ref="iconSelect" @selected="selected" />
                                </div>
                            </Poptip>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="菜单类型">
                            <Select v-model="formAdd.type" transfer>
                                <Option :value="item.value" v-for="item in typeList" :key="item.value">{{item.label}}</Option>
                            </Select>
                        </bingo-form-item>
                    </Col>
                    <!-- <Col :span="12">
                        <bingo-form-item label="模块id">
                            <Input type="text" v-model="formAdd.moduleId" placeholder="请输入模块id">
                            </Input>
                        </bingo-form-item>
                    </Col> -->
                    <!-- <Col :span="12">
                        <bingo-form-item label="父权限ID">
                            <Input type="text" v-model="formAdd.parentId" placeholder="请输入父权限ID">
                            </Input>
                        </bingo-form-item>
                    </Col> -->
                    <!-- <Col :span="12">
                        <bingo-form-item label="数据编号">
                            <Input type="text" v-model="formAdd.sn" placeholder="请输入数据编号" disabled>
                            </Input>
                        </bingo-form-item>
                    </Col>-->
                    <Col :span="12">
                        <bingo-form-item label="排序">
                            <InputNumber style="width:100%" :min="0" v-model="formAdd.sort"></InputNumber>
                        </bingo-form-item>
                    </Col>
                    <Col :span="12">
                        <bingo-form-item label="路径">
                            <Input type="text" v-model="formAdd.url" placeholder="请输入路径">
                            </Input>
                        </bingo-form-item>
                    </Col>
                    <!-- <Col :span="12">
                        <bingo-form-item label="是否显示">
                            <RadioGroup v-model="formAdd.visible">
                                <Radio :label="1">显示</Radio>
                                <Radio :label="0">隐藏</Radio>
                            </RadioGroup>
                        </bingo-form-item>
                    </Col> -->
                </Row>
            </Form>
        </Modal>
        <bingo-modal-select
        ref="modal"
        :title="'分配角色'"
        :datas="datas"
        :show-input="false"
        :columns="selectColumns"
        :field="'nameCn'"
        :value="selectedRoles"
        :keyId="'sn'"
        @on-ok="onSelectOk"
        @getData="getData">
                    <bingo-grid-item>
                        <bingo-form-item label="角色名称" prop="nameCn">
                            <Input v-model="roleArr.nameCn" placeholder=""/>
                        </bingo-form-item>
                    </bingo-grid-item>
        </bingo-modal-select>
        <Modal v-model="showData" title="数据权限" width="900">
            <Form :model="dataAuthForm" label-position="right" :label-width="90" style="overflow:hidden">
                <Col :span="12">
                    <bingo-form-item label="组件名称" prop="nameCn">
                        <Input v-model="dataAuthForm.nameCn" placeholder="" disabled/>
                    </bingo-form-item>
                </Col>
                <Col :span="12">
                    <FormItem label="" style="margin-left:-70px">
                        <Button
                            class="auth-btn"
                            type="primary"
                            customIcon="iconfont iconxinjian"
                            @click="onNewAuth"
                            >新建</Button
                        >
                    </FormItem>
                </Col>
            </Form>
            <bingo-table
                ref="authTable"
                :columns="authColumns"
                :topHeight="100"
                :pageSetting="pageSetting"
                :page="true"
                :data="authData"
                :isCustomData="true"
                >
                <template slot="action" slot-scope="{ row, index }">
                    <div class="action-all" >
                        <Button
                            type="primary"
                            size="small"
                            @click="onEditBtnAuth(row.id)"
                        >
                            <i class="icon iconfont iconbianji"></i
                            ><span class="font">编辑</span></Button
                        >

                        <Button
                            type="error"
                            size="small"
                            @click="onDeleteBtnAuth(row)"
                        >
                            <i class="icon iconfont iconshanchu"></i
                            ><span class="font">删除</span></Button
                        >
                    </div>
                </template>
                </bingo-table>
        </Modal>
        <!-- 新增权限 -->
        <Modal v-model="showAuth" :title="isAddAuth==true?'新建':'修改'" @on-ok="onOkAuth">
            <Form ref="formAuth" :model="formAuth" label-position="right" :label-width="90">
                <Row>
                        <bingo-form-item label="归属角色" prop="nameCn">
                            <Select transfer="" v-model="formAuth.formRoleSn">
                                <Option v-for="item in formRolesData" :value="item.sn" :key="item.sn">{{ item.nameCn }}</Option>
                            </Select>
                        </bingo-form-item>
                        <bingo-form-item label="数据范围" prop="nameCn">
                            <Select transfer v-model="formAuth.dataRange">
                                <Option v-for="item in dataRangeArr" :value="item.dictCode" :key="item.dictCode">{{item.dictValue}}</Option>
                            </Select>
                        </bingo-form-item>
                </Row>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import bingoList from '@/components/bingo-list';
    import bingoTable from '@/components/bingo-table';
    import Api from '@/api/system/menu';
    import roleApi from '@/api/system/role';
    import rbacApi from '@/api/system/rbac';
    import authApi from '@/api/system/auth';
    import dictApi from '@/api/platform/dict';
    import module from '@/mixins/module';
    import util from '@/utils/tool'
    import IconSelect from '@/components/IconSelect'
    import bingoModalSelect from '@/components/bingo-modal-select'
    export default {
        name:'plat-menu',
        data () {
            return {
                columns: [
                    {
                        title: '序号',
                        type: 'index',
                        width: 60,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        title: '菜单名称',
                        key: 'nameCn',
                        minWidth: 220,
                        tree: true
                    },
                    {
                        title: '排序',
                        key: 'sort',
                        minWidth: 80
                    },
                    {
                        title: '路径',
                        key: 'url',
                        minWidth: 190
                    },
                    {
                        title: '类型',
                        key: 'typeName',
                        minWidth: 80
                    },
                    // {
                    //     title: '是否显示',
                    //     key: 'visibleName',
                    //     width: 130
                    // },
                    {
                        title: '图标',
                        key: 'icon',
                        minWidth: 130
                    },
                    // {
                    //     title: '模块id',
                    //     key: 'moduleId'
                    // },
                    // {
                    //     title: '父权限ID',
                    //     key: 'parentId'
                    // },
                    {
                        title: '创建人',
                        key: 'creator',
                        minWidth: 110
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        minWidth: 120
                    },
                    {
                        title: '修改人',
                        key: 'modifier',
                        minWidth: 110
                    },
                    {
                        title: '修改时间',
                        key: 'modifyTime',
                        minWidth: 120
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        align: 'center',
                        width: 256
                    }
                ],
                Api: Api,
                authApi: authApi,
                pageSetting: {
                    pageNum: 1,
                    pageSize: 20,
                    showSizer: true
                },
                // 搜索的字段
                searchList: [
                    {
                        label: '菜单名称',
                        value: 'nameCn',
                        type: 'input'
                    },
                    {
                        label: '图标',
                        value: 'icon',
                        type: 'input'
                    },
                    // {
                    //     label: '是否显示',
                    //     value: 'visible',
                    //     type: 'input'
                    // },
                    // {
                    //     label: '模块id',
                    //     value: 'moduleId',
                    //     type: 'input'
                    // },
                    // {
                    //     label: '父权限ID',
                    //     value: 'parentId',
                    //     type: 'input'
                    // },
                    {
                        label: '类型',
                        value: 'type',
                        type: 'input'
                    },
                    {
                        label: '路径',
                        value: 'url',
                        type: 'input'
                    }
                ],
                tableData: [],
                queryData: {
                    nameCn: '',
                    nameDe: '',
                    nameEn: '',
                    icon: '',
                    visible: '',
                    moduleId: '',
                    parentId: '',
                    sn: '',
                    type: '',
                    url: ''
                },
                queryObj: {},
                isShowNewForm: false,
                formAdd: {
                    nameCn: '',
                    nameDe: '',
                    nameEn: '',
                    icon: '',
                    visible: 1,
                    moduleId: '',
                    parentId: '',
                    parentSn: '',
                    sn: '',
                    sort: 0,
                    type: 0,
                    url: ''
                },
                grid: {
                    xl: 12,
                    lg: 13,
                    md: 13,
                    sm: 24,
                    xs: 24
                },
                typeList: [
                    {
                        label: '目录',
                        value: 0
                    },
                    {
                        label: '菜单',
                        value: 1
                    },
                    {
                        label: '组件',
                        value: 2
                    },
                    {
                        label: '按钮',
                        value: 3
                    }
                ],
                isAdd: true,
                dataRangeArr: [],
                datas: [],
                selectColumns: [
                    {
                        title: '序号',
                        type: 'index',
                        width: 60,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        title: '角色名称',
                        key: 'nameCn'
                    }
                ],
                selectedRoles: [],
                roleArr: {
                    nameCn: ''
                },
                showData: false,
                dataAuthForm: {
                    nameCn: ''
                },
                formAuth: {
                    sn: '',
                    dataRange: '',
                    formRoleSn: ''
                },
                formRolesData: [],
                authColumns: [
                    {
                        title: '序号',
                        type: 'index',
                        width: 60,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        title: '角色名称',
                        key: 'nameCn'
                    },
                    {
                        title: '数据范围',
                        key: 'nameCn'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        align: 'center',
                        width: 146
                    }
                ],
                authData: [],
                isAddAuth: true,
                showAuth: false,
                menuData: [],
                tableDataArr: []
            };
        },
        created () {
            // this.getAuth();
            this.auth = JSON.parse(localStorage.getItem('auth'));
        },
        mixins: [module],
        methods: {
            // 获取权限
            // async getAuth () {
            //     let auth = await this.getPermission();
            //     this.auth = JSON.parse(JSON.stringfy(auth));
            // },
            popperShow () {
                this.$refs.iconSelect.reset();
            },
            // 选择图标
            selected (name) {
                this.formAdd.icon = name
            },
            // 弹出层查询
            querySubmit (obj) {
                if (obj) {
                    this.queryObj = obj;
                }
                this.$refs.bingoList.getTableData(this.queryObj);
            },
            onChangeSelectTree (value) {
                let _this = this;
                this.tableDataArr.forEach(item => {
                    if (item.value === value) {
                        _this.formAdd.parentSn = item.sn;
                    }
                })
            },
            // 新建
            async onAddNew (row) {
                this.isAdd = true;
                for (let i in this.formAdd) {
                    if (Array.isArray(this.formAdd[i])) {
                        this.formAdd[i] = [];
                    } else {
                        this.formAdd[i] = '';
                        if (i === 'sort' || i === 'type') { this.formAdd[i] = 0 }
                        if (i === 'visible') { this.formAdd[i] = 1 }
                    }
                }
                if (row) {
                    this.formAdd.parentId = row.id;
                    this.formAdd.parentSn = row.sn;
                }
                this.formAdd.sn = await this.getSn();
                this.formAdd.moduleId = await this.generateModuleId();
                this.isShowNewForm = true;
            },
            generateModuleId () {
                return new Promise(function (resolve, reject) {
                    Api.generateModuleId().then(res => {
                        resolve(res)
                    })
                })
            },
            // 新建确定
            onOk () {
                if (this.isAdd) {
                    Api.addTable(this.formAdd).then(res => {
                        this.$Message.success('新建成功');
                        this.$refs.bingoList.getTableData();
                    })
                } else {
                    Api.editTable(this.formAdd).then(res => {
                        this.$Message.success('修改成功');
                        this.$refs.bingoList.getTableData();
                    })
                }
            },
            // 编辑
            onEditBtn (id) {
                this.isAdd = false;
                Api.getTableById(id).then(res => {
                    this.formAdd = res;
                    this.isShowNewForm = true;
                })
            },
            // 删除
            onDeleteBtn (row) {
                this.$Modal.confirm({
                    title: '请确认',
                    content: '<p>是否确认删除?</p>',
                    onOk: () => {
                        Api.deleteTable(row.id).then((res) => {
                            this.$Message.success('删除成功');
                            this.$refs.bingoList.getTableData();
                        });
                    }
                });
            },
            // 处理数据
            processData (data, table) {
                data.forEach(item => {
                    let arr = this.typeList.filter(it => {
                        return it.value === item.type;
                    })
                    item.typeName = arr[0].label;
                    // if (item.visible === 0) {
                    //     item.visibleName = '隐藏'
                    // } else if (item.visible === 1) {
                    //     item.visibleName = '显示'
                    // }
                    if (item.createTime) {
                        item.createTime = util.format(new Date(item.createTime), 'yyyy-MM-dd');
                    }
                    if (item.modifyTime) {
                        item.modifyTime = util.format(new Date(item.modifyTime), 'yyyy-MM-dd')
                    }
                    item.title = item.nameCn;
                    item.value = item.id;
                });
                let dataCopy = JSON.parse(JSON.stringify(data));
                this.tableDataArr = dataCopy;
                this.tableDataArr.unshift({
                    title: '主类目',
                    id: 0,
                    value: 0,
                    sn: 0,
                    parentId: -1
                })
                this.menuData = findChild(-1, this.tableDataArr);
                this.menuData1 = findChild(0, dataCopy);
                function findChild (curPid) {
                    var _arr = [];
                    var items = dataCopy;
                    var length = items.length;
                    for (var i = 0; i < length; i++) {
                        items[i].path = items[i].url;
                        if (items[i].parentId === curPid) {
                            var _obj = items[i];
                            _obj.children = findChild(_obj.id);
                            if (_obj.children.length > 0) {
                                _obj._showChildren = true;
                            }
                            _arr.push(_obj);
                        }
                    }
                    return _arr;
                }
                table.tableData = this.menuData1;
            },
            // 分配角色
            allot (row) {
                this.row = row;
                let data = { sn: row.sn }
                if (row.type === 0 || row.type === 1) {
                    roleApi.getRolesByMenu(data).then(res => {
                        if (res.rows.length > 0) {
                            this.selectedRoles = res.rows.filter(item => item.isCheck === 1);
                        }
                        this.getData();
                    })
                } else if (row.type === 2) {
                    roleApi.getRolesByTable(data).then(res => {
                        if (res.rows.length > 0) {
                            this.selectedRoles = res.rows.filter(item => item.isCheck === 1);
                        }
                        this.getData();
                    })
                } else if (row.type === 3) {
                    roleApi.getRolesByButton(data).then(res => {
                        if (res.rows.length > 0) {
                            this.selectedRoles = res.rows.filter(item => item.isCheck === 1);
                        }
                        this.getData();
                    })
                }
            },
            // 获取角色列表
            getData () {
                let data = this.roleArr;
                roleApi.tableList(data).then(res => {
                    this.datas = res.rows;
                    this.$refs.modal.show = true;
                })
            },
            // 选角色
            onSelectOk (areaData) {
                let roleSns = [];
                if (areaData.length > 0) {
                    roleSns = areaData.map(item => item.sn);
                }
                let data = {
                    roleSns: roleSns,
                    sn: this.row.sn
                }
                if (this.row.type === 0 || this.row.type === 1) {
                    rbacApi.menuRoles(data).then(res => {
                        this.$Message.success('分配角色成功');
                    })
                } else if (this.row.type === 2) {
                    rbacApi.tableRoles(data).then(res => {
                        this.$Message.success('分配角色成功');
                    })
                } else if (this.row.type === 3) {
                    rbacApi.buttonRoles(data).then(res => {
                        this.$Message.success('分配角色成功');
                    })
                }
            },
            // 数据权限
            dataAuth (row) {
                this.row = row;
                this.dataAuthForm.nameCn = row.nameCn;
                let data = { sn: row.sn };
                let p1 = new Promise((resolve, reject) => {
                    roleApi.getRolesByTable(data).then(res => {
                        resolve(res.rows)
                    })
                });
                let data2 = {
                    dictGroup: 'platform',
                    dictType: 'data_permission'
                }
                let p2 = new Promise((resolve, reject) => {
                    dictApi.tableList(data2).then(res => {
                        resolve(res.rows)
                    })
                });
                let p3 = this.getAuthData();
                Promise.all([p1, p2, p3]).then(values => {
                    if (values[0].length > 0) {
                        this.formRolesData = values[0].filter(item => item.isCheck === 1);
                    }
                    this.dataRangeArr = values[1];
                    this.authData = values[2];
                    this.showData = true;
                });
            },
            // 数据权限列表
            getAuthData () {
                let data = { sn: this.row.sn };
                return new Promise((resolve, reject) => {
                    authApi.tableList(data).then(res => {
                        resolve(res.rows)
                    })
                });
            },
            // 新增权限
            async onNewAuth () {
                this.formAuth.sn = await this.getSn();
                this.isAddAuth = true;
                this.showAuth = true;
            },
            // 新增权限确定
            onOkAuth () {
                if (this.isAddAuth) {
                    let data = {
                        showType: this.formAuth.dataRange,
                        sn: this.formAuth.sn,
                        whatSn: this.row.sn,
                        whoSn: this.formAuth.formRoleSn,
                        whoType: 0
                    };
                    authApi.addTable(data).then(res => {
                        this.getAuthData();
                        this.$Message.success('新建成功')
                    })
                } else {
                    Api.editTable(this.formAuth).then(res => {
                        this.getAuthData();
                        this.$Message.success('修改成功');
                    })
                }
            },
            // 编辑权限
            onEditBtnAuth (id) {
                this.isAddAuth = false;
                authApi.getTableById(id).then(res => {
                    this.formAuth = res;
                    this.showAuth = true;
                })
            },
            // 删除数据权限
            onDeleteBtnAuth (row) {
                this.$Modal.confirm({
                    title: '请确认',
                    content: '<p>是否确认删除?</p>',
                    onOk: () => {
                        authApi.deleteTable(row.id).then((res) => {
                            this.$Message.success('删除成功');
                            this.getAuthData();
                        });
                    }
                });
            }
        },
        components: { bingoList, IconSelect, bingoModalSelect, bingoTable }
    };
</script>
<style scoped lang="less">
    .auth-btn{
        i{
            vertical-align: middle;
            margin-top: -3px;
        }
    }
</style>
