<template>
    <div>
        <el-card shadow="always" :style="'height:' + vh + 'px'">
            <div class="clearfix" slot="header">
                <b>
                    <b>
                        <!-- <svg-icon icon-class="menu"/> -->
                        {{ role && role.name ? '【' + role.name + '】' : '' }}资源分配
                    </b>
                </b>
            </div>
            <el-row>
                <el-col :span="12">
                    <el-tag v-if="role && role.name" size="medium" type="success">{{ role.name }}</el-tag>
                    <el-tag v-else type="info" size="medium">
                        <i class="el-icon-info"></i>
                        请选择角色
                    </el-tag>
                </el-col>
                <el-col :span="12" style="text-align: right">
                    <!-- <el-button :disabled="isRoot" type="primary" icon="el-icon-check" size="mini" @click="handleSubmit">
            提交
         </el-button> -->
                    <el-button type="primary" icon="el-icon-check" @click="handleSubmit">提交</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-select
                    v-show="false"
                    v-model="ExpandedNum"
                    @change="handleExpandNumChange"
                    placeholder="选择展开级别"
                    size="mini"
                    style="width: 100px; left: 0px"
                >
                    <el-option label="不展开" :value="0"></el-option>
                    <el-option label="展开1" :value="1"></el-option>
                    <el-option label="展开2" :value="2"></el-option>
                    <el-option label="展开3" :value="3"></el-option>
                </el-select>
                <el-tree
                    :style="'height:' + vhh + 'px'"
                    ref="menu"
                    node-key="id"
                    :default-expanded-keys="expandedKeys"
                    :data="menuOptions"
                    :props="defaultProps"
                    :expand-on-click-node="true"
                    :highlight-current="true"
                    :filter-node-method="filterNode"
                    show-checkbox
                    accordion
                    :check-strictly="checkStrictly"
                />
            </div>
        </el-card>
    </div>
</template>

<script>
import { list as listMenu } from '@/api/admin/menu'
import { listRoleMenu, updateRoleMenu } from '@/api/admin/role'
import { gongkey, userfunction } from '@/api/user'
import { passwordConfirm } from '@/api/admin/user'
import { sm3Digest } from '@/assets/commjs/sm3'
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
export default {
    name: 'Menu',
    watch: {
        filterText(val) {
            this.$refs.menu.filter(val)
        }
    },
    data() {
        return {
            vh: null,
            vhh: null,
            ExpandedNum: 2,
            filterText: '',
            menuOptions: [],
            expandedKeys: [],
            role: {},
            initialCheckedMenuIds: [], //初始选中值
            buttonlist: [],
            checkedMenuIds: [],
            isRoot: false, // 是否是超级管理员账户
            checkStrictly: false,
            defaultProps: {
                children: 'children',
                label: 'title'
            }
        }
    },
    created() {
        this.loadMenus()
        this.vh = window.sessionStorage.getItem('appheight') - 130
    },
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)

        this.loadMenus()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 10
            this.vhh = window.sessionStorage.getItem('appheight') - 170
        },
        //判断需要展开层级
        handleExpandNumChange(menuOptions) {
            if (this.ExpandedNum > 0) {
                this.setExpandKeys(menuOptions)
            }
        },
        //层级展开递归方法
        setExpandKeys(dataList, n) {
            if (!n) n = 1
            for (let i = 0; i < dataList.length; i++) {
                if (n <= this.ExpandedNum) {
                    //this.expandID=[]
                    this.expandedKeys.push(`${dataList[i].id}`)
                    if (dataList[i].hasOwnProperty('children')) {
                        const children = dataList[i].children
                        this.setExpandKeys(children, n + 1)
                    }
                }
            }
        },
        //过滤
        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.title && node.data.title.indexOf(value) !== -1
            isPass ? _array.push(isPass) : ''
            this.index++
            if (!isPass && node.title != 1 && node.parent) {
                this.getReturnNode(node.parent, _array, value)
            }
        },
        loadMenus() {
            var arrlist = []
            // var arrchildren=[]
            var butlist = []
            listMenu().then(response => {
                this.menuOptions = response.data

                this.menuOptions.forEach(m => {
                    m.children.forEach(n => {
                        //  n.children.forEach(d=>{
                        this.expandedKeys.push(n.id)
                        this.handleExpandNumChange(this.menuOptions)
                        //  })
                    })
                })
                // this.expandedKeys = this.menuOptions.map(node => node.id) //展开所有节点
            })
        },
        handleSubmit() {
            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()
                                    //let  data={}
                                    const checkedMenuIds = this.$refs.menu
                                        .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(this.role)
                                        // var roleIndex=this.role.roleIndex
                                        // var functionIndexList=checkedMenuIds
                                        var data = {
                                            id: this.role.id,
                                            idList: checkedMenuIds
                                        }
                                        updateRoleMenu(data).then(response => {
                                            // console.log(response.data)
                                            this.$message.success('角色分配资源成功')
                                        })
                                    }
                                }
                            })
                        }
                    })
                
                           
                           
                    } else {
                        done()
                    }
                }
            })
                .then(({ value }) => {
                  
                })
                .catch(() => {})
        },
        roleClick(role) {
            this.role = role
            this.$refs.menu.setCurrentKey(null) // 取消菜单高亮
            if (role.code == 'root') {
                // 如果是超级管理员默认勾选全部且不可编辑
                //debugger
                this.isRoot = true
                this.$refs.menu.setCheckedNodes(this.menuOptions)
                // this.$refs.menu.menuClicks(this.menuOptions);
            } else {
                this.isRoot = false
                this.checkStrictly = true
                this.initialCheckedMenuIds = []
                let p = {
                    id: role.id
                }
                listRoleMenu(p).then(response => {
                    let ids = []
                    response.data.forEach(item => {
                        ids.push(item.id)
                    })
                    this.initialCheckedMenuIds = ids
                    // alert(this.initialCheckedMenuIds)
                    //console.log(this.initialCheckedMenuIds)
                    this.$refs.menu.setCheckedKeys(this.initialCheckedMenuIds)
                    this.checkStrictly = false
                })
            }
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__body,
.el-main {
    padding: 10px;
    // background: #e9ebeb;
}

::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>
