<template>
    <div class="authContainer">
        <div class="content">
            <div class="list_container userList">
                <el-breadcrumb separator-class="el-icon-arrow-right" :class="'title'">
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
                <el-row v-for="(item, index) in userList" :key="index">
                    <div @click="changeUser(item)">{{ item.username }}</div>
                </el-row>
            </div>
            <div class="list_container layerList" v-show="isShowLayerList">
                <div class="batchSetRegion">
                    <el-button type="text" @click="openBatchSetRegion">批量设置行政区划权限</el-button>
                </div>
                <el-breadcrumb separator-class="el-icon-arrow-right" :class="'title'">
                    <el-breadcrumb-item v-for="(str, index) in breadcrumbLayerArr" :key="index" :title="str">{{ str }}
                    </el-breadcrumb-item>
                </el-breadcrumb>
                <el-tree ref="layerTree" :data="layerList" show-checkbox node-key="id"
                    :default-expanded-keys="[0, 1, 2, 3, 4, 5, 6]" @check="layerCheck" :props="defaultLayerListProps"
                    :expand-on-click-node="false">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span v-if="node.level != 1">
                            <el-button type="text" size="mini" @click="() => openSetRegion(data, node)">设置行政区划权限
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
            <div class="list_container regionList" v-show="isShowRegionList">
                <el-breadcrumb separator-class="el-icon-arrow-right" :class="'title'">
                    <el-breadcrumb-item v-for="(str, index) in breadcrumRegionbArr" :key="index" :title="str">{{ str }}
                    </el-breadcrumb-item>
                </el-breadcrumb>
                <el-tree ref="regionTree" :data="regionList" show-checkbox node-key="areaCode"
                    :default-expanded-keys="[130000]" @check="regionCheck" :props="defaultRegionListProps"></el-tree>
            </div>
            <div class="list_container batchRegionList" v-show="isShowBatchRegionList">
                <el-breadcrumb separator-class="el-icon-arrow-right" :class="'title'">
                    <el-breadcrumb-item>批量设置行政区划权限</el-breadcrumb-item>
                </el-breadcrumb>
                <el-tree ref="batchRegionTree" :data="regionList" show-checkbox node-key="areaCode"
                    :default-expanded-keys="[130000]" @check="batchRegionCheck" :props="defaultRegionListProps">
                </el-tree>
            </div>
        </div>
        <div class="footer">
            <div>
                <el-button @click="download">示例文档下载</el-button>
                <el-button @click="save">保存设置</el-button>
                <el-button @click="cancal">取消设置</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import api from "@/api/authManage";
export default {
    props: {},
    data() {
        return {
            breadcrumbLayerArr: [""],
            breadcrumRegionbArr: [""],

            isShowLayerList: false,
            isShowRegionList: false,
            isShowBatchRegionList: false,

            userList: [],
            regionList: null,
            defaultLayerListProps: {
                children: 'models',
                label: 'title'
            },
            defaultRegionListProps: {
                children: 'children',
                label: 'areaName'
            },

            authInfo: {},

            nowLayerId: null,
            nowUserId: null,

            haveChange: false, // 是否做了修改
            exampleWord: systemConfig.exampleWord
        }
    },
    created() {
        let that = this;
        $.getJSON("/static/config/hebei.json", function (result) {
            that.regionList = result;
            // that.getRegion(0)
        });
        this.getAllUserList();
    },
    mounted() {

    },
    methods: {
        download() {
            const elink = document.createElement('a')
            elink.href = this.exampleWord;
            elink.setAttribute('download', "接口示例文档.docx")
            elink.style.display = 'none'
            document.body.appendChild(elink)
            setTimeout(() => {
                elink.click()
                document.body.removeChild(elink)
            }, 66)
        },
        getRegion(index) {
            let that = this;
            api.getRegionByCode({
                cityCode: this.regionList[0].children[index].cityCode
            }).then((result) => {
                if (result.code == 200) {
                    that.regionList[0].children[index].children = result.content;
                    if (that.regionList[0].children.length - 1 > index) {
                        let d = index + 1;
                        that.getRegion(d);
                        console.log(JSON.stringify(that.regionList))
                    }
                }
            }).catch((err) => {

            });
        },
        // 获取所有用户
        getAllUserList() {
            let that = this
            let obj = Object.assign({}, systemConfig.defaultUser)
            obj.active = false;
            this.userList.push(obj);
            api.getAllUser().then((result) => {
                if (result.code == 200) {
                    let arr = result.content;
                    arr.unshift();
                    that.userList.concat(arr.map(function (item) {
                        item.active = false;
                        return item
                    }))
                } else {
                    checkRequestCode(result)
                }
            }).catch((err) => {
                that.$message({
                    type: "error",
                    message: err
                })
            });
        },

        // 获取单个用户的当前权限
        getSingleUserAuthInfo(userId) {
            let that = this;
            return new Promise((resolve, reject) => {
                api.getSingleUserAuth({ userId: userId }).then((result) => {
                    if (result.code == 200) {
                        resolve(result.content);
                    } else {
                        checkRequestCode(result)
                        reject();
                    }
                }).catch((err) => {
                    that.$message({
                        type: "error",
                        message: err
                    })
                    reject();
                });
            });
        },

        // 保存当前用户用户权限
        saveNowUserAuth() {
            let that = this
            let keysArr = Object.keys(this.authInfo);
            let authInfo = {};
            keysArr.map(function (key) {
                authInfo[key] = that.handleRegion(that.authInfo[key]);
            })
            return new Promise((resolve, reject) => {
                api.saveNowUserAuth({ userId: that.nowUserId, contents: JSON.stringify(authInfo) }).then((result) => {
                    if (result.code == 200) {
                        that.authInfo = {}
                        that.$message({
                            type: "success",
                            message: "用户权限保存成功！"
                        })
                        resolve(result.content);

                    } else {
                        checkRequestCode(result)
                        reject();
                    }
                }).catch((err) => {
                    that.$message({
                        type: "error",
                        message: err
                    })
                    reject();
                });
            });
        },

        // 切换用户
        changeUser(item) {
            let that = this;
            if (this.haveChange) {
                // 是否保存当前用户的权限设置？
                this.$confirm('是否保存对当前用户权限的设置或改动？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 转入保存逻辑
                    that.saveNowUserAuth()
                        .then(() => {
                            that.getAuthAndShowLayer(item);
                        })
                        .catch((err) => {
                            that.$confirm(err + '，是否继续切换用户？', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                that.getAuthAndShowLayer(item);
                            }).catch(() => { });
                        });
                }).catch(() => {
                    that.getAuthAndShowLayer(item)
                });
            } else {
                this.getAuthAndShowLayer(item)
            }
        },

        // 获取当前用户权限，并 打开图层列表，关闭区划列表
        getAuthAndShowLayer(item) {
            let that = this;
            this.nowLayerId = null
            this.nowUserId = null
            this.haveChange = false;
            return new Promise((resolve, reject) => {
                this.getSingleUserAuthInfo(item.id).then((content) => {
                    that.authInfo = content == -1 ? {} : JSON.parse(content);
                    that.$refs.layerTree.setCheckedKeys(Object.keys(that.authInfo)); // 设置选中图层
                    that.isShowLayerList = true;
                    that.isShowRegionList = false;
                    that.isShowBatchRegionList = false;
                    that.breadcrumbLayerArr = [item.username, "图层权限"];
                    that.nowUserId = item.id;
                    resolve();
                }).catch((err) => {
                    reject();
                });
            });

        },

        // 勾选图层
        layerCheck(item, statusObj) {
            let that = this
            this.haveChange = true;
            let obj = Object.assign({}, JSON.parse(JSON.stringify(this.authInfo)))
            this.authInfo = {}
            let layerSelectedArr = this.$refs.layerTree.getCheckedKeys(true);
            layerSelectedArr.map(function (layerId) {
                if (obj.hasOwnProperty(layerId)) {
                    that.authInfo[layerId] = obj[layerId]
                } else {
                    that.authInfo[layerId] = []
                }
            })
            if (!this.nowLayerId) return;
            if (layerSelectedArr.indexOf(this.nowLayerId) == -1) {
                this.isShowRegionList = false;
                this.nowLayerId = null
            }
            if (layerSelectedArr.length == 0) {
                this.isShowBatchRegionList = false;
                this.$refs.batchRegionTree.setCheckedKeys([]);
            }
        },

        // 打开 行政区划
        openSetRegion(data, node) {
            if (node.checked) {
                if (this.authInfo[data.id].length == 0) {
                    this.$refs.regionTree.setCheckedKeys([])
                } else {
                    this.$refs.regionTree.setCheckedKeys(this.authInfo[data.id])
                }
            } else {
                this.$message({
                    type: "warning",
                    message: "未设置当前用户有此图层的查看权限，不能设置当前图层的区划权限！"
                })
                return;
            }
            // title设置
            this.breadcrumRegionbArr = [].concat(this.breadcrumbLayerArr)
            this.breadcrumRegionbArr[1] = data.title;
            this.breadcrumRegionbArr.push("行政区划权限")
            this.isShowRegionList = true;
            this.isShowBatchRegionList = false;
            this.nowLayerId = data.id
        },

        // 勾选区划 single
        regionCheck(item, statusObj) {
            this.haveChange = true;
            this.authInfo[this.nowLayerId] = statusObj.checkedKeys
        },

        // 打开 批量设置行政区划模块
        openBatchSetRegion() {
            let that = this;
            let layerSelectedArr = this.$refs.layerTree.getCheckedKeys(true);
            this.$confirm('使用批量设置行政区划权限功能会清空当前选中用户的所有已设置的行政区划权限，是否继续使用？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    if (layerSelectedArr.length == 0) {
                        that.$message({
                            type: "warning",
                            message: "当前未有选择图层，无法使用批量设置行政区划权限功能。"
                        })
                        return;
                    }
                    this.isShowBatchRegionList = true;
                    this.isShowRegionList = false;
                })
                .catch(() => { })
        },

        // 勾选区划 batch 
        batchRegionCheck(item, statusObj) {
            let that = this;
            this.haveChange = true;
            let keys = Object.keys(this.authInfo);
            keys.map(function (layerId) {
                that.authInfo[layerId] = statusObj.checkedKeys
            })
        },

        // 整理行政区划
        handleRegion(arr) {
            if (arr.length == 0) return [];
            let provinceArr = arr.filter(function (num1) {
                return num1 % 10000 == 0
            })
            let cityArr = arr.filter(function (num2) {
                return num2 % 100 == 0
            })
            let countryArr = arr.filter(function (num2) {
                return num2 % 100 != 0
            })
            if (provinceArr.length != 0) {
                return provinceArr;
            } else {
                if (cityArr.length != 0) {
                    let resetCountryArr = countryArr.filter(function (num3) {
                        let integer = parseInt(num3 / 100) * 100
                        return !cityArr.some(function (num) {
                            return num == integer
                        })
                    })
                    return cityArr.concat(resetCountryArr);
                } else {
                    return countryArr
                }
            }
        },

        // 解析行政区划
        analysisRegion(arr) {
            if (arr.length == 0) return [];
            let provinceArr = arr.filter(function (num1) {
                return num1 % 10000 == 0
            })
            let cityArr = arr.filter(function (num2) {
                return num2 % 100 == 0
            })
            let countryArr = arr.filter(function (num2) {
                return num2 % 100 != 0
            })


            if (provinceArr.length != 0) {
                return provinceArr;
            } else {
                if (cityArr.length != 0) {
                    let resetCountryArr = countryArr.filter(function (num3) {
                        let integer = parseInt(num3 / 100) * 100
                        return !cityArr.some(function (num) {
                            return num == integer
                        })
                    })
                    return cityArr.concat(resetCountryArr);
                } else {
                    return countryArr
                }
            }
        },


        // 保存设置
        save() {
            let that = this;
            this.saveNowUserAuth().then((result) => {
                that.haveChange = false
                that.isShowLayerList = false;
                that.isShowRegionList = false;
                that.isShowBatchRegionList = false;
            }).catch((err) => {
                
            });
        },

        // 取消设置
        cancal() {
            this.authInfo = {}

            this.breadcrumbLayerArr = [""];
            this.breadcrumRegionbArr = [""];

            this.nowLayerId = null;
            this.nowUserId = null;

            this.haveChange = false

            this.isShowLayerList = false;
            this.isShowRegionList = false;
            this.isShowBatchRegionList = false;
        }
    },
    computed: {
        layerList() {
            return this.$store.state.menuDataList.map(function (item) {
                item.title = item.name;
                return item
            })
        },
    },
    watch: {
        isShowRegionList(newVal, oldVal) {
            if (!newVal) {
                this.$refs.regionTree.setCheckedKeys([]);
            }
        },
        isShowBatchRegionList(newVal, oldVal) {
            if (newVal) {
                for (const key in this.authInfo) {
                    if (Object.hasOwnProperty.call(this.authInfo, key)) {
                        this.authInfo[key] = [];
                    }
                }
            }
        },
        // layerSelectedArr(newArr, oldArr) {
        //     if (newArr.length == 0) {
        //         this.isShowBatchRegionList = false;
        //         this.$refs.batchRegionTree.setCheckedKeys([]);
        //     }
        // }
    },
}
</script>

<style lang="less" scoped>
.authContainer {
    width: 100%;
    height: 100%;
    background: #ffffff;
    font-family: "Arial Normal", "Arial";
    font-weight: 400;
    font-style: normal;
    color: #aaaaaa;
    position: relative;

    .content {
        height: calc(100% - 60px);

        .list_container {
            height: calc(100% - 40px);
            width: calc(100% / 3 - 40px);
            float: left;
            overflow: hidden;
            overflow-y: auto;
            margin: 20px 20px;
            border: 1px solid #eeeeee;
            border-radius: 10px;
            box-sizing: border-box;
            position: relative;

            &.userList {
                .el-row {
                    height: 40px;
                    line-height: 40px;
                    color: #000000;
                    margin: 0 10px;
                    padding-left: 10px;
                    border-bottom: 1px solid #eeeeee;
                    font-size: 16px;

                    &:hover {
                        background-color: #eeeeee;
                        cursor: pointer;
                    }

                    &.active {
                        background-color: #eeeeee;
                    }
                }
            }

            .custom-tree-node {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                padding-right: 8px;
            }

            .title {
                height: 40px;
                line-height: 40px;
                margin: 0 10px;
                border-bottom: 1px solid #eeeeee;
                box-sizing: border-box;
                font-size: 18px;
                color: #000000;

                /deep/ .el-breadcrumb__inner {
                    font-weight: bold !important;
                }

                /deep/ .el-breadcrumb__item {
                    float: unset;

                    &:nth-child(1)>.el-breadcrumb__inner {
                        max-width: 120px;
                    }

                    &:nth-child(2)>.el-breadcrumb__inner {
                        max-width: 180px;
                    }

                    >.el-breadcrumb__inner {
                        display: inline-block;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        cursor: pointer;
                    }

                    >i {
                        display: inline-block;
                        vertical-align: top;
                        margin-top: 11px;
                    }

                    &:last-child .el-breadcrumb__separator {
                        display: none;
                    }
                }
            }

            &.batchRegionList {
                .title {
                    /deep/ .el-breadcrumb__item {
                        &:nth-child(1)>.el-breadcrumb__inner {
                            max-width: 200px;
                        }
                    }
                }
            }

            .batchSetRegion {
                position: absolute;
                top: 0px;
                right: 7px;
            }
        }
    }

    .footer {
        box-sizing: border-box;
        padding: 0 20px;

        >div {
            float: right;
        }
    }
}
</style>