<template>
    <div>
        <el-card shadow="always" :style="'height:' + vh + 'px'">
            <div class="clearfix" slot="header">
                <b>
                    <!-- <svg-icon icon-class="menu"/> -->
                    {{ role && role.name ? '【' + role.name + '】' : '' }}组件功能分配
                </b>
            </div>
            <el-row>
                <el-col :span="18">
                    <el-tag v-if="role" type="primary" size="medium">{{ role.name }}</el-tag>
                    <el-tag v-if="menu" type="success" size="medium" style="margin-left: 5px">{{ menu.name }}</el-tag>
                    <el-tag v-if="!role" type="info" size="medium" style="margin-left: 5px">
                        <i class="el-icon-info"></i>
                        请选择角色
                    </el-tag>
                </el-col>
                <el-col :span="6" style="text-align: right">
                    <!-- <el-button type="primary" :disabled="isRoot" icon="el-icon-check" size="mini" @click="submit">提交
          </el-button> -->
                    <el-button type="primary" icon="el-icon-check" @click="submit">提交</el-button>
                </el-col>
            </el-row>
            <el-input placeholder="输入关键字检索" v-model="filterText" clearable>
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <div class="overview_scroll" :style="'margin-top:10px;overflow-y:auto;height:' + vh + 'px'">
                <el-tree
                    :style="'height:' + vhh + 'px'"
                    ref="per"
                    :default-expanded-keys="expandedKeys"
                    :data="menuOptions"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    show-checkbox
                    accordion
                    node-key="id"
                    :check-strictly="checkStrictly"
                    highlight-current
                />
            </div>
        </el-card>
    </div>
</template>

<script>
import { list as listPermission, rolelist } from '@/api/admin/permission'
import { listRolePermission, updateRolePermission } from '@/api/admin/role'

import { gongkey, userfunction } from '@/api/user'

import { sm3Digest } from '@/assets/commjs/sm3'
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
import { componentlists, updatedcomponent, getComponent, passwordConfirm } from '@/api/admin/user'
//onst cityOptions = ['上海', '北京', '广州', '深圳'];
export default {
    name: 'Permission',
    props: ['type'],
    watch: {
        filterText(val) {
            this.$refs.per.filter(val)
        }
    },
    data() {
        return {
            vh: null,
            vhh: null,
            filterText: '',
            menuOptions: [],
            expandedKeys: [],
            menu: undefined,
            initialCheckedMenuIds: [], //初始选中值
            buttonlist: [],
            checkedMenuIds: [],
            isRoot: false, // 是否是超级管理员账户
            checkStrictly: false,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            loading: false,
            role: undefined,

        }
    },
    created() {
        this.vh = window.sessionStorage.getItem('appheight') - 10
    },
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.handleConpent()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 10
            this.vhh = window.sessionStorage.getItem('appheight') - 170
        },
        //过滤
        filterNode(value, data, node) {
            if (!value) {
                return true
            }
            let _array = [] //这里使用数组存储 只是为了存储值。
            this.getReturnNode(node, _array, value)
            let result = false
            _array.forEach(item => {
                result = result || item
            })
            return result
        },
        getReturnNode(node, _array, value) {
            let isPass = node.data && node.data.name && node.data.name.indexOf(value) !== -1
            isPass ? _array.push(isPass) : ''
            this.index++
            if (!isPass && node.name != 1 && node.parent) {
                this.getReturnNode(node.parent, _array, value)
            }
        },
        roleClick(role) {
            this.role = role
            this.$refs.per.setCurrentKey(null) // 取消菜单高亮
            if (role.code == 'root') {
                // 如果是超级管理员默认勾选全部且不可编辑
                this.isRoot = true
                this.$refs.per.setCheckedNodes(this.menuOptions)
                // this.$refs.menu.menuClicks(this.menuOptions);
            } else {
                this.isRoot = false
                this.checkStrictly = true
                this.initialCheckedMenuIds = []
                let arr = []
                arr.push(role.id)
                getComponent(arr).then(response => {
                    this.initialCheckedMenuIds = response.data
                    // alert(this.initialCheckedMenuIds)
                    // console.log(this.initialCheckedMenuIds)
                    this.$refs.per.setCheckedKeys(this.initialCheckedMenuIds)
                    this.checkStrictly = false
                })
            }
        },
        submit() {
            this.$prompt('', '密码二次校验', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^.{6,16}$/,
                inputType: 'password',
                closeOnClickModal: false,
                inputErrorMessage: '长度在 6 到 16 个字符',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        gongkey({ loginName: window.sessionStorage.cnloginname }).then(response => {
                            if (response.code === 'A0000') {
                                var publicKey = response.data
                                // console.log("获取公钥后赋值" + publicKey);
                                var sm3Pwd = sm3Digest(instance.inputValue) //SM3加密
                                var jiamipassword = ''
                                jiamipassword = sm2(sm3Pwd + '|' + instance.inputValue, publicKey, 0) //SM2公钥加密

                                passwordConfirm(jiamipassword).then(response => {
                                    if (response.code === 'A0000') {
                                        done()
                                        const checkedMenuIds = this.$refs.per
                                            .getCheckedNodes(false, true)
                                            .map(node => node.id)
                                        // 判断选中菜单ID是否变动
                                        if (
                                            this.initialCheckedMenuIds.length == checkedMenuIds.length &&
                                            this.initialCheckedMenuIds.sort().every(function (v, i) {
                                                return v == checkedMenuIds[i]
                                            })
                                        ) {
                                            this.$message.warning('数据未变动')
                                            return
                                        } else {
                                            // console.log(checkedMenuIds)
                                            // var id=this.role.id
                                            //var idList=checkedMenuIds
                                            var data = {
                                                id: this.role.id,
                                                idList: checkedMenuIds
                                            }
                                            updatedcomponent(data).then(response => {
                                                this.$message.success('角色分配组件成功')
                                            })
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        done()
                    }
                }
            })
        },
        handleConpent() {
            componentlists().then(response => {
                this.menuOptions = response.data
                this.expandedKeys = this.menuOptions.map(node => node.id) //展开所有节点
            })
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__body,
.el-main {
    padding: 10px;
    // background: #abacac;
}
::v-deep .el-tag:not(.el-tag--dark) {
    background-color: #edf8f6;
    border-color: #dbf0ed;
    color: #4ab5a5;
    height: 36px;
    line-height: 36px;
}
::v-deep .el-tree {
    position: relative;
    cursor: default;
    /* background: #FFF; */
    // color: #323131;
    overflow-y: auto;
}
::-webkit-scrollbar {
    width: 8px !important;
    height: 14px;
}
</style>
