<template>
    <el-container id="user" style="width: 100%;">
        <el-header :height="headerHeight">
            <el-col :span="24" style="position: relative;top: 10px;">
                <div style="display:inline-block;float:left;">
                    <awsui-button style="width: 100px;" class="button-general-color" type="primary" @click="addUser">添加用户</awsui-button>
                </div>
                <div style="display:inline-block;float:right;width:320px;padding-right: 20px;">
                    <el-input
                            placeholder="搜索"
                            prefix-icon="el-icon-search"
                            v-model="searchInput"
                            @input="searchUser"
                            size="small"
                            clearable>
                    </el-input>
                </div>
            </el-col>
        </el-header>
        <el-main :style="{height: mainHeight}">
            <div class="text-general-color category-title"><p style="padding-left: 5px;" v-html="'管理用户（' + data1.length + '）'"></p></div>
            <div v-show="data1.length == 0" style="height: 200px;"></div>
            <template v-for="item in data1">
                <div style="display: inline;margin-right: 40px;" @mouseenter="enter(item.id, '0')" @mouseleave="leave(item.id, '0')">
                    <el-card shadow="hover" style="width: 300px;display: inline-block;margin-top: 15px;">
                        <div style="display: inline-block;width: 15px;margin-left: 5px;height: 20px;line-height: 20px;vertical-align: middle;">
                            <div :style="{'display': (item.showCheckBox || item.checked) ? 'inline-block' : 'none'}">
                                <el-checkbox v-model="item.checked" @change="handleCheckChange(item.id, '0')"></el-checkbox>
                            </div>
                        </div>
                        <div style="display: inline;width: 30px;margin: 0 15px;">
                            <img class="user_photo_img radius3" :src="item.userPhoto">
                        </div>
                        <div class="text-over-hidden" style="display: inline-block;width: 220px;height: 20px;line-height: 20px;vertical-align: middle;">
                            <span class="text-general-color" v-html="item.name"></span>
                            &nbsp;&nbsp;
                            <span class="text-second-color" style="font-size:12px;-webkit-transform: scale(0.9);">{{item.role}}</span>
                        </div>
                    </el-card>
                </div>
            </template>
            <div class="text-general-color category-title"><p style="padding-left: 5px;" v-html="'梳理用户（' + data2.length + '）'"></p></div>
            <template v-for="item in data2">
                <div style="display: inline;margin-right: 40px;" @mouseenter="enter(item.id, '1')" @mouseleave="leave(item.id, '1')">
                    <el-card shadow="hover" style="width: 300px;display: inline-block;margin-top: 15px;">
                        <div style="display: inline-block;width: 15px;margin-left: 5px;height: 20px;line-height: 20px;vertical-align: middle;">
                            <div :style="{'display': (item.showCheckBox || item.checked) ? 'inline-block' : 'none'}">
                                <el-checkbox v-model="item.checked" @change="handleCheckChange(item.id, '0')"></el-checkbox>
                            </div>
                        </div>
                        <div style="display: inline;width: 30px;margin: 0 15px;">
                            <img class="user_photo_img radius3" :src="item.userPhoto">
                        </div>
                        <div class="text-over-hidden" style="display: inline-block;width: 220px;height: 20px;line-height: 20px;vertical-align: middle;">
                            <span class="text-general-color" v-html="item.name"></span>
                            &nbsp;&nbsp;
                            <span class="text-second-color" style="font-size:12px;-webkit-transform: scale(0.9);">{{item.role}}</span>
                        </div>
                    </el-card>
                </div>
            </template>
        </el-main>
        <el-footer v-show="showFooter" :height="footerHeight">
            <div style="border-top: 1px solid #F2F2F2;height: 44px;">
                <div style="padding: 8px;margin-left: 20px;">
                    <el-checkbox style="margin-right: 10px;" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
                    <awsui-button style="width: 100px;" class="button-general-color" type="primary" @click="changeRole()">变更角色</awsui-button>
                    <awsui-button style="width: 100px;" class="button-general-color-reverse2" plain @click="removeUsers()">删除用户</awsui-button>
                    <awsui-button style="width: 100px;" class="button-general-color-reverse3" plain @click="closeFooter">取消</awsui-button>
                </div>
            </div>
        </el-footer>
        <el-drawer
                id="drawer"
                ref="drawer"
                title="添加用户"
                :visible.sync="drawerVisible"
                custom-class="text-general-color"
                :destroy-on-close=true
                :wrapperClosable=false
                size="700px"
                direction="rtl"
                :before-close="handleDrawerClose"
                @opened="handleOpenedDrawer">
            <div id="drawerDiv" style="width: 100%;height: 100%;border-top: 1px solid #F2F2F2;">
                <div :style="{'height': drawerMainHeight, 'overflow': 'auto', 'margin': '10px 20px'}">
                    <div class="text-general-color category-title"><p style="padding-left: 5px;">管理用户</p></div>
                    <el-input size="medium" readonly placeholder="请选择" @click.native="choiceBpmOrgUser('0')"></el-input>
                    <p style="margin: 10px 0;" v-html="'已选择（'+ drawerData1.length +'）'"></p>
                    <div>
                        <template v-for="item in drawerData1">
                            <div :name="item.id" class="row">
                                <div class="text-over-hidden" style="display: inline-block;width: 88%;">
                                    <span>{{item.name}}</span>
                                </div>
                                <div class="operate-icon-display" style="position: relative;top: -6px;">
                                    <i style="display: inline-block;cursor: pointer;" class="awsui-iconfont" @click="removeDrawerUser(item.id, '0')">&#58918;</i>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="text-general-color category-title"><p style="padding-left: 5px;">梳理用户</p></div>
                    <el-input size="medium" readonly placeholder="请选择" @click.native="choiceBpmOrgUser('1')"></el-input>
                    <p style="margin: 10px 0;"v-html="'已选择（'+ drawerData2.length +'）'"></p>
                    <div>
                        <template v-for="item in drawerData2">
                            <div :name="item.id" class="row">
                                <div class="text-over-hidden" style="display: inline-block;width: 88%;">
                                    <span>{{item.name}}</span>
                                </div>
                                <div class="operate-icon-display" style="position: relative;top: -6px;">
                                    <i style="display: inline-block;cursor: pointer;" class="awsui-iconfont" @click="removeDrawerUser(item.id, '1')">&#58918;</i>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
                <div id="drawerFooter" :style="{'height': drawerFooterHeight, 'visibility': 'hidden', 'background-color': '#F5F7FA'}">
                    <div style="margin-top: 10px;margin-right: 5px;float: right;">
                        <awsui-button style="width: 100px;" class="button-general-color" type="primary" @click="saveDrawer">保存</awsui-button>
                        <awsui-button style="width: 100px;" class="button-general-color-reverse3" plain @click="closeDrawer">取消</awsui-button>
                    </div>
                </div>
            </div>
        </el-drawer>
        <BPMOrgAddress
            ref="bpmOrgAddress"
            :visible.sync="bpmOrg.visible"
            :addressType="bpmOrg.addressType"
            :highSecurityFilter="bpmOrg.highSecurityFilter"
            :multiple=true
            v-on:cancel="bpmOrg.visible = false"
            v-on:getResult="saveBpmOrgCompnentResult"
            :title="bpmOrg.title"
        ></BPMOrgAddress>
    </el-container>
</template>

<script>
    import awsuiAxios from "../../awsuiAxios";
    import BPMOrgAddress from "../../components/common/BPMOrgAddress/component";
    export default {
        name: "User",
        components: {BPMOrgAddress},
        data() {
            return {
                headerHeight: '50px',
                footerHeight: '45px',
                mainHeight: (parseInt(this.$store.getters.getTopMainHeightFn) - 50 - (this.showFooter ? 45 : 0)) + 'px',
                searchInput: '',
                isIndeterminate: true,
                checkAll: false,
                showFooter: false,
                data1: [],
                dataTemp1: [],
                data2: [],
                dataTemp2: [],
                drawerVisible: false,
                drawerMainHeight: '0px',
                drawerFooterHeight: '50px',
                drawerData1: [],
                drawerData2: [],
                bpmOrg: {
                    visible: false,
                    addressType: "user",
                    title: "选择用户",
                    highSecurityFilter: 'sysAdmin,auditor',
                    source: '0'// 组件是由谁触发的，0 管理员选择用户，1普通用户选择用户
                }
            }
        },
        mounted() {
            this.initData();
        },
        methods: {
            initData() {// 初始化数据查询
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_user_data_query'
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        const data1 = ro.data.data1;
                        for (let i = 0; i < data1.length; i++) {
                            data1[i].checked = false;
                            data1[i].showCheckBox = false;
                        }
                        const data2 = ro.data.data2;
                        for (let i = 0; i < data2.length; i++) {
                            data2[i].checked = false;
                            data2[i].showCheckBox = false;
                        }
                        that.data1 = data1;
                        that.data2 = data2;
                        that.dataTemp1 = JSON.parse(JSON.stringify(that.data1));
                        that.dataTemp2 = JSON.parse(JSON.stringify(that.data2));
                    } else {
                        that.$message(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            enter(id, type) {// 鼠标进入卡片
                if (type == '0') {
                    for (let i = 0; i < this.data1.length; i++) {
                        if (this.data1[i].id == id) {
                            this.data1[i].showCheckBox = true;
                            break;
                        }
                    }
                }
                if (type == '1') {
                    for (let i = 0; i < this.data2.length; i++) {
                        if (this.data2[i].id == id) {
                            this.data2[i].showCheckBox = true;
                            break;
                        }
                    }
                }
            },
            leave(id, type) {// 鼠标移出卡片
                if (type == '0') {
                    for (let i = 0; i < this.data1.length; i++) {
                        if (this.data1[i].id == id) {
                            this.data1[i].showCheckBox = false;
                            break;
                        }
                    }
                }
                if (type == '1') {
                    for (let i = 0; i < this.data2.length; i++) {
                        if (this.data2[i].id == id) {
                            this.data2[i].showCheckBox = false;
                            break;
                        }
                    }
                }
            },
            handleCheckChange(id) {// 多选变更
                const that = this;
                let count = 0;
                for (let i = 0; i < that.data1.length; i++) {
                    const curr = that.data1[i];
                    if (curr.checked) {
                        count++;
                    }
                }
                for (let i = 0; i < that.data2.length; i++) {
                    const curr = that.data2[i];
                    if (curr.checked) {
                        count++;
                    }
                }
                that.isIndeterminate = count > 0 && count < (that.data1.length + that.data2.length);
                that.checkAll = count == that.data1.length + that.data2.length;
                that.showFooter = count > 0;
            },
            handleCheckAllChange(val) {// 全选变更
                if (val) {// 全选
                    for (let i = 0; i < this.data1.length; i++) {
                       this.data1[i].checked = true;
                    }
                    for (let i = 0; i < this.data2.length; i++) {
                        this.data2[i].checked = true;
                    }
                } else {// 取消全选
                    for (let i = 0; i < this.data1.length; i++) {
                        this.data1[i].checked = false;
                    }
                    for (let i = 0; i < this.data2.length; i++) {
                        this.data2[i].checked = false;
                    }
                    this.showFooter = false;
                }
                this.isIndeterminate = false;
            },
            changeRole() {// 一键变更角色
                const changeIds = [];
                for (let i = 0; i < this.data1.length; i++) {
                    if (this.data1[i].checked) {
                        changeIds.push(this.data1[i].id);
                    }
                }
                for (let i = 0; i < this.data2.length; i++) {
                    if (this.data2[i].checked) {
                        changeIds.push(this.data2[i].id);
                    }
                }
                if (changeIds.length == 0) {
                    this.$message({message: '请选择需要变更角色的用户',type: 'warning'});
                    return;
                }
                // 三员模式下安全保密员不允许删除
                var secAdminUsers = this.getSecAdminUsers(changeIds);
                if (secAdminUsers[0].length > 0) {
                    this.$message({message: '三员模式下安全保密员用户' + secAdminUsers[1].join('、') + '不允许变更',type: 'warning'});
                    return;
                }
                if (changeIds.indexOf('admin') > -1) {
                    this.$message({message: 'admin管理员用户不允许变更',type: 'warning'});
                    return;
                }
                // 变更
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_user_role_change',
                        userIds: changeIds.join(',')
                    }
                };
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        if (ro.data.isExit) {// 将自己从管理员变更为普通用户，退出系统
                            that.$message({
                                message: '变更成功，即将退出系统',
                                type: 'warning',
                                onClose: function() {
                                    const src = wHref +  "?sid=" + that.$store.state.sessionId + "&cmd=com.actionsoft.apps.coe.pal_user_logout";
                                    window.location.replace(src);
                                }
                            });
                            return;
                        }
                        that.$message({
                            message: '变更成功',
                            type: 'success'
                        });
                        that.closeFooter();
                        that.initData();
                    } else {
                        that.$message(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            removeUsers() {// 删除用户
                const removeIds = [];
                for (let i = 0; i < this.data1.length; i++) {
                    if (this.data1[i].checked) {
                        removeIds.push(this.data1[i].id);
                    }
                }
                for (let i = 0; i < this.data2.length; i++) {
                    if (this.data2[i].checked) {
                        removeIds.push(this.data2[i].id);
                    }
                }
                if (removeIds.length == 0) {
                    this.$message({message: '请选择需要删除的用户',type: 'warning'});
                    return;
                }
                // 三员模式下安全保密员不允许删除
                var secAdminUsers = this.getSecAdminUsers(removeIds);
                if (secAdminUsers[0].length > 0) {
                    this.$message({message: '三员模式下安全保密员用户' + secAdminUsers[1].join('、') + '不允许删除',type: 'warning'});
                    return;
                }
                if (removeIds.indexOf('admin') > -1) {
                    this.$message({message: 'admin管理员用户不允许删除',type: 'warning'});
                    return;
                }
                // 删除
                const that = this;
                that.$confirm('确定要删除吗？', '提示', {
                    confirmButtonText: '确定',
                    confirmButtonClass: 'button-general-color',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const params = {
                        url:'jd',
                        data:{
                            cmd: 'com.actionsoft.apps.coe.pal_user_remove',
                            userIds: removeIds.join(',')
                        }
                    };
                    awsuiAxios.post(params).then(function (ro) {
                        if(ro.result == 'ok') {
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            that.closeFooter();
                            that.initData();
                        } else {
                            that.$message(ro.msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    })
                }).catch(() => {
                });
            },
            closeFooter() {// 关闭底部操作栏
                this.handleCheckAllChange(false);
            },
            searchUser() {// 搜索
                this.closeFooter();
                if (this.searchInput && this.searchInput.trim() != '') {// 根据条件搜索
                    const data1 = [];
                    for (let i = 0; i < this.dataTemp1.length; i++) {
                        if (this.dataTemp1[i].name.indexOf(this.searchInput) > -1) {
                            const temp = JSON.parse(JSON.stringify(this.dataTemp1[i]));
                            temp.name = temp.name.replace(new RegExp(this.searchInput,'g'), '<span style="color: #4E7FF9">' + this.searchInput + '</span>');
                            data1.push(temp);
                        }
                    }
                    this.data1 = data1;
                    const data2 = [];
                    for (let i = 0; i < this.dataTemp2.length; i++) {
                        if (this.dataTemp2[i].name.indexOf(this.searchInput) > -1) {
                            const temp = JSON.parse(JSON.stringify(this.dataTemp2[i]));
                            temp.name = temp.name.replace(new RegExp(this.searchInput,'g'), '<span style="color: #4E7FF9">' + this.searchInput + '</span>');
                            data2.push(temp);
                        }
                    }
                    this.data2 = data2;
                } else {// 显示全部
                    this.data1 = this.dataTemp1;
                    this.data2 = this.dataTemp2;
                }
            },
            addUser() {// 新增用户
                this.drawerVisible = true;
            },
            handleDrawerClose(done) {
                done();
            },
            handleOpenedDrawer() {// 打开抽屉之后执行，加载现有用户数据
                this.drawerMainHeight = (document.getElementById('drawer').offsetHeight - parseInt(this.drawerFooterHeight)) - 64 - 20 + 'px';
                document.getElementById('drawerFooter').style.visibility = "visible";
                // 初始化数据
                // 获取现有的用户，tempdata1，tempdata2，
                this.drawerData1 = JSON.parse(JSON.stringify(this.dataTemp1));
                this.drawerData2 = JSON.parse(JSON.stringify(this.dataTemp2));
            },
            removeDrawerUser(userId, type) {// 在抽屉中临时删除
                if (type == '0' && userId == 'admin') {
                    this.$message({message: 'admin管理员用户不允许删除',type: 'warning'});
                    return;
                }
                // 三员模式下安全保密员不允许删除
                if (type == '0') {
                    var secAdminUsers = this.getSecAdminUsers([userId]);
                    if (secAdminUsers[0].length > 0) {
                        this.$message({message: '三员模式下安全保密员用户[' + secAdminUsers[1].join('、') + ']不允许删除',type: 'warning'});
                        return;
                    }
                }

                const that = this;
                that.$confirm('确定要删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 临时删除抽屉数据
                    let data = [];
                    if (type == '0') {
                        data = this.drawerData1;
                    } else if (type == '1') {
                        data = this.drawerData2;
                    }
                    for (let i = 0; i < data.length; i++) {
                        if (userId == data[i].id) {
                            data.splice(i, 1);
                            break;
                        }
                    }
                }).catch(() => {

                });
            },
            saveDrawer() {// 保存drawer结果
                // 校验
                // admin必须包含在管理员内
                // let isValid = false;
                // for (let i = 0; i < this.drawerData1.length; i++) {
                //     if (this.drawerData1[i].id == 'admin') {
                //         isValid = true;
                //     }
                // }
                // if (!isValid) {
                //     this.$message({message: '校验失败，admin管理员用户不允许变更角色、删除',type: 'warning'});
                //     return;
                // }
                const managerUsers = [];// 管理用户
                const generalUsers = [];// 普通用户
                for (let i = 0; i < this.drawerData1.length; i++) {
                    managerUsers.push(this.drawerData1[i].id);
                }
                for (let i = 0; i < this.drawerData2.length; i++) {
                    generalUsers.push(this.drawerData2[i].id);
                    if (managerUsers.indexOf(this.drawerData2[i].id) > -1) {
                        this.$message({message: '用户[' + this.drawerData2[i].name + ']不能同时设置为管理员和普通用户',type: 'warning'});
                        return;
                    }
                }

                const that = this;
                // 保存
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_user_save',
                        managerUsers: managerUsers.join(','),
                        generalUsers: generalUsers.join(',')
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        that.$message({message: '保存成功',type: 'success'});
                        that.closeDrawer();// 关闭抽屉
                        that.showFooter = false;
                        that.initData();// 初始化数据
                    } else if (ro.result == 'warning'){
                        that.$message({message: ro.msg,type: 'warning'});
                    } else {
                        that.$message.error(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            closeDrawer() {// 关闭
                this.$refs.drawer.closeDrawer();
            },
            choiceBpmOrgUser(source) {// 选择用户
                this.bpmOrg.source = source;
                this.bpmOrg.visible = true;
            },
            saveBpmOrgCompnentResult(data) {// 保存bpm选择结果
                this.bpmOrg.visible = false;
                let temp = [];
                if (this.bpmOrg.source == '0') {// 添加到管理员
                    temp = this.drawerData1;
                } else {
                    temp = this.drawerData2;
                }
                const repeatIds = [];
                for (let i = 0; i < temp.length; i++) {
                    for (let j = 0; j < data.length; j++) {
                        if (temp[i].id == data[j].id) {
                            repeatIds.push(temp[i].id);
                        }
                    }
                }
                for (let i = 0; i < data.length; i++) {
                    if (repeatIds.indexOf(data[i].id) < 0) {
                        temp.push(data[i]);
                    }
                }
            },
            getSecAdminUsers(userIds) {// 检查并获取给定用户的安全保密员用户
                let result = [[],[]];
                for (let i = 0; i < this.dataTemp1.length; i++) {
                    if (this.dataTemp1[i].isSecAdminUser && userIds.indexOf(this.dataTemp1[i].id) > -1) {
                        result[0].push(this.dataTemp1[i].id);
                        result[1].push(this.dataTemp1[i].name);
                    }
                }
                for (let i = 0; i < this.dataTemp2.length; i++) {
                    if (this.dataTemp2[i].isSecAdminUser && userIds.indexOf(this.dataTemp2[i].id) > -1) {
                        result[0].push(this.dataTemp2[i].id);
                        result[1].push(this.dataTemp2[i].name);
                    }
                }
                return result;
            }
        },
        computed: {
            listenTopMainHeight() {
                return this.$store.getters.getTopMainHeightFn;
            }
        },
        watch: {
            listenTopMainHeight: function (newd, old) {
                this.mainHeight = (parseInt(this.$store.getters.getTopMainHeightFn) - 50 - (this.showFooter ? 45 : 0)) + 'px'
                if (this.drawerVisible) {// drawer高度自适应
                    this.drawerMainHeight = (document.getElementById('drawer').offsetHeight - parseInt(this.drawerFooterHeight)) - 64 - 20 + 'px';
                }
            }
        }
    }
</script>

<style scoped>
    #user >>> .el-main {
        padding: 0px 20px;
    }
    #user >>> .el-footer {
        padding: 0;
    }
    #user >>> .el-card__body {
         padding: 10px 0;
    }
    #user >>> .el-drawer__header {
        margin-bottom: 17px;
        color: #606266;
        font-size: 17px;
    }
    #drawerDiv .row .operate-icon-display{
        display: none;
    }
    #drawerDiv .row:hover .operate-icon-display{
        display: inline-block;
    }
    #drawerDiv .row:hover{
        background-color: #F5F7FA;
    }
    .row {
        display: inline-block;
        width: 155px;
        height: 25px;
        line-height: 25px;
        border-right: 1px solid #F2F2F2;
        padding-left: 4px;
        margin-right: 5px;
    }
    .category-title {
        height: 25px;
        line-height: 25px;
        vertical-align: center;
        margin: 10px 10px 5px 0px;
        border-left: 3px solid #4E7FF9;
    }
    .user_photo_img {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        position: relative;
        top: -0px;
    }
    .text-over-hidden {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>