<template>
    <awsui-layout id="manageList" class="text-general-color">
        <awsui-header :height="(parseInt(header1Height) + parseInt(header2Height)) + 'px'">
            <div style="width: 100%;height: 100%;">
                <awsui-row :style="{height: header1Height}">
                    <awsui-col id="header" :span="24" :style="{height: header1Height}" style="padding: 10px 0 10px 10px;">
                        <!-- logo -->
                        <div id="teamLogo" class="inline-block">
                            <div id="headerLogo" class="team-icon-div inline-block" :style="{height: iconHeight, width: iconHeight, 'line-height': iconHeight, 'background-color': currTeam.teamLogo.color}">
                                <i class="awsui-iconfont" style="font-size: 32px;color: #fff" v-html="currTeam.teamLogo.code"></i>
                            </div>
                        </div>
                        <!-- teamDetail -->
                        <div id="teamDetail" class="inline-block">
                            <div class="inline-block" :style="{'padding-left': headerTitlePaddingLeft}">
                                <div id="headerTitle" style="height: 25px;position: relative;top: 11px;" class="text-overflow-hidden">
                                    <span style="font-size: 18px;">{{currTeam.teamName}}</span>
                                    <span v-if="!currTeam.isRun">
                                        <span style="font-size: 12px;" >(</span>
                                        <span style="font-size: 12px;" class="text-important-color">已停用</span>
                                        <span style="font-size: 12px;" >)</span>
                                    </span>
                                    <span style="font-size: 12px;" class="text-second-color">（关联"{{currTeam.wsName}}"）</span>
                                </div>
                                <div id="headerDesc" class="text-overflow-hidden" style="height: 19px;position: relative;top: 14px;">
                                    <span style="font-size: 12px;">{{currTeam.teamDesc}}</span>
                                </div>
                            </div>
                        </div>
                        <!-- button -->
                        <div id="manageButton" v-if="currTeam.teamManager" class="inline-block" :style="{width: manageButtonWidth, 'height': '20px'}">
                            <div style="position: absolute;right: -15px;">
                                <awsui-button style="width: 100px;" class="button-general-color-reverse" plain @click="manageRole">管理角色</awsui-button>
                                <awsui-button style="width: 100px;margin-left: 15px;" class="button-general-color" type="primary" @click="addMember">添加成员</awsui-button>
                            </div>
                        </div>
                    </awsui-col>
                </awsui-row>
                <awsui-row :style="{height: header2Height}">
                    <awsui-col :span="17" style="height: 100%;">
                        <div style="height: 100%;padding-left: 10px;">
                            <span>小组共<span style="color: #D9001B;">{{tempTableData.length}}名</span>成员，其中<span style="color: #D9001B;" v-html="getManageUserCount() + '名'"></span>管理员</span>
                        </div>
                    </awsui-col>
                    <awsui-col :span="7" style="height: 100%;margin-left: 0">
                        <div style="height: 100%;width: 260px;position: absolute;right: 0px;">
                            <awsui-input v-model="searchInput" @input="search" placeholder="搜索"></awsui-input>
                        </div>
                    </awsui-col>
                </awsui-row>
            </div>
        </awsui-header>
        <awsui-main>
            <div id="tableMain" ref="tableMain">
                <div v-if="!currTeam.teamManager" key="table1">
                    <el-table
                            ref="table"
                            :height="mainHeight"
                            :row-style="{height:'50px'}"
                            :cell-style="{padding:'0px'}"
                            :data="tableData"
                            style="width: 100%;"
                            highlight-current-row>
                        <el-table-column
                                prop="userName"
                                label="姓名"
                                min-width="150px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.userName"></span><span v-if="scope.row.close" class="text-important-color">[已注销]</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="roleName"
                                label="小组角色"
                                min-width="150px">
                        </el-table-column>
                        <el-table-column
                                prop="deptName"
                                label="部门"
                                min-width="150px">
                        </el-table-column>
                        <el-table-column
                                prop="email"
                                label="电子邮件"
                                min-width="150px">
                        </el-table-column>
                    </el-table>
                </div>
                <div v-if="currTeam.teamManager" key="table2">
                    <el-table
                            ref="table"
                            :height="mainHeight"
                            :row-style="{height:'50px'}"
                            :cell-style="{padding:'0px'}"
                            :data="tableData"
                            style="width: 100%;"
                            highlight-current-row
                            @cell-mouse-enter="showCheckbox"
                            @cell-mouse-leave="hideCheckbox"
                            :cell-class-name="hideCheckBoxCell"
                            @row-click="clickTableRow"
                            @selection-change="handlecheckedUsersChange">
                        <el-table-column
                                type="selection"
                                width="45"
                                align="center">
                        </el-table-column>
                        <el-table-column
                                prop="userName"
                                label="姓名"
                                min-width="150px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.userName"></span><span v-if="scope.row.close" class="text-important-color">[已注销]</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="roleName"
                                label="小组角色"
                                min-width="150px">
                        </el-table-column>
                        <el-table-column
                                prop="deptName"
                                label="部门"
                                min-width="150px">
                        </el-table-column>
                        <el-table-column
                                prop="email"
                                label="电子邮件"
                                min-width="150px">
                        </el-table-column>
                        <el-table-column
                                prop="operate"
                                label=""
                                align="center">
                            <template slot-scope="scope">
                                <div style="/*width: 30px;display: inline-block;*/">
                                    <div class="operate-icon-display">
                                        <el-tooltip v-if="!scope.row.isOlderVersion && scope.row.hasUserPerm" content="权限复制" placement="bottom" :hide-after=2000>
                                            <i class="awsui-iconfont" style="cursor: pointer;padding-right: 10px;" @click="copyUser(scope.row.userId)">&#xe8be;</i>
                                        </el-tooltip>
                                        <el-tooltip v-if="!scope.row.isOlderVersion && scope.row.hasUserPerm" content="用户权限" placement="bottom" :hide-after=2000>
                                            <i class="awsui-iconfont" style="cursor: pointer;padding-right: 10px;" @click="updateUser(scope.row.userId)">&#xe615;</i>
                                        </el-tooltip>
                                        <el-tooltip content="修改角色" placement="bottom" :hide-after=2000>
                                            <i class="iconfont icon-jiaoseguanli" style="cursor: pointer;padding-right: 10px;" @click="updateRole(scope.row.userId)"></i>
                                        </el-tooltip>
                                        <el-tooltip v-if="scope.row.userId != currTeam.userId" content="删除成员" placement="bottom" :hide-after=2000>
                                            <i class="iconfont icon-lajitong1" style="cursor: pointer;" @click="removeUser(scope.row.userId)"></i>
                                        </el-tooltip>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </awsui-main>
        <awsui-footer :height="footerHeight" v-show="showFooter" key="operateFooter">
<!--            <div style="border-top: 1px solid #F2F2F2;height: 100%;">-->
            <div style="height: 100%;">
                <div style="padding: 8px 8px 8px 14px;">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
                    <awsui-button style="width: 100px;margin-left: 15px;" class="button-general-color" type="primary" @click="updateRoles">修改角色</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>取消</awsui-button>
                </div>
            </div>
        </awsui-footer>
        <role-manage
                ref="roleManage"
                :visible.sync="roleManage.visible"
                :teamId="teamId"
                :userIds="roleManage.userIds"
                :type="roleManage.type"
                v-on:cancel="roleManage.visible = false"
                v-on:getResult="roleManageDone"
                :title="roleManage.title"/>
        <member-add
            ref="memberAdd"
            :visible.sync="memberAdd.visible"
            :teamId="teamId"
            v-on:cancel="memberAdd.visible = false"
            v-on:getResult="memberAddDone"
            :title="memberAdd.title"
            />
        <role-update
            ref="roleUpdate"
            :visible.sync="roleUpdate.visible"
            :teamId="teamId"
            :isUser="true"
            :roleId="roleUpdate.roleId"
            :userid="roleUpdate.userid"
            v-on:cancel="roleUpdate.visible = false"
            v-on:setUserRole="setUserRole"
            v-on:getResult="updateUserDone"/>

        <perm-copy
          :visible.sync="memberCopy.visible"
          :teamId="teamId"
          :userid ="memberCopy.userid"
          :teamMembers="memberCopy.teamMembers"
          v-on:cancel="memberCopy.visible = false"
          v-on:getResult="memberCopyDone"
          :title="memberCopy.title"
        />

    </awsui-layout>
</template>

<script>
    import RoleManage from "../role/RoleManage";
    import RoleUpdate from "../role/RoleUpdate";
    const header1Height = '80px';
    const header2Height = '30px';
    const footerHeight = '45px';
    import awsuiAxios from "../../awsuiAxios";
    import MemberAdd from "../member/MemberAdd";
    import PermCopy  from "../role/PermCopy";
    export default {
        name: "ManageList",
        components: {MemberAdd, RoleManage, RoleUpdate,PermCopy},
        props: {
            teamId: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                header1Height: header1Height,
                header2Height: header2Height,
                iconHeight: '56px',
                headerTitlePaddingLeft: '10px',
                manageButtonWidth: '250px',
                mainHeight: (parseInt(this.$store.getters.getTopMainHeightFn) - (this.showFooter ? footerHeight : 0)) - parseInt(header1Height) - parseInt(header2Height) + 'px',
                footerHeight: footerHeight,
                searchInput: '',
                tableData: [],
                tempTableData: [],
                showFooter: false,
                checkAll: false,
                checkedUsers: [],// 多选已选中结果记录
                singleSelectedRepository: {},// 单个文件快捷菜单操作文件记录
                isIndeterminate: false,
                currTeam: {
                    userId: '',
                    teamId: '',
                    teamName: '',
                    teamLogo: {
                        color: '',
                        code: ''
                    },
                    teamDesc: '',
                    wsId: '',
                    wsName: '',
                    teamManager: false,
                    isRun: false // 启用中
                },
                roleManage: {
                    visible: false,
                    title: '设置角色',
                    userIds: [],
                    type: ''
                },
                memberAdd: {
                    visible: false,
                    title: '添加小组成员'
                },
                memberCopy:{
                  visible: false,
                  title: '权限复制',
                  userid: '',
                  teamMembers:[]
                },
                roleUpdate: {
                  visible: false,
                  userid:'',
                  roleId: ''
                },
            }
        },
        mounted() {
            this.initData();
        },
        methods: {
            initData() {// 查询小组信息
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal.cooperation_manage_team_detail_query',
                        teamId: that.teamId
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if (ro.result == 'ok') {
                        const data = ro.data;
                        that.currTeam.userId = data.userId;
                        that.currTeam.teamId = data.teamId;
                        that.currTeam.teamName = data.teamName;
                        that.currTeam.teamDesc = data.teamDesc;
                        that.currTeam.teamLogo = data.teamLogo;
                        that.currTeam.wsId = data.wsId;
                        that.currTeam.isRun = data.run;
                        that.currTeam.wsName = data.wsName;
                        that.currTeam.teamManager = data.teamManager;
                        that.tempTableData = JSON.parse(JSON.stringify(data.members));
                        that.initCurrTeamHeaderWidth();
                        that.search();
                    } else {
                        that.$message.error(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            search() {// 搜索
                this.closeFooter();
                if (this.searchInput && this.searchInput.trim() != '') {// 根据条件搜索
                    const data1 = [];
                    for (let i = 0; i < this.tempTableData.length; i++) {
                        if (this.tempTableData[i].userName.indexOf(this.searchInput) > -1) {
                            const temp = JSON.parse(JSON.stringify(this.tempTableData[i]));
                            temp.userName = temp.userName.replace(new RegExp(this.searchInput,'g'), '<span style="color: #4E7FF9">' + this.searchInput + '</span>');
                            data1.push(temp);
                        }
                    }
                    this.tableData = data1;
                } else {// 显示全部
                    this.tableData = this.tempTableData;
                }
            },
            initCurrTeamHeaderWidth() {
                const headerWidth = document.getElementById('header').offsetWidth - 10;
                const width = headerWidth - parseInt(this.iconHeight) - (this.currTeam.teamManager ? parseInt(this.manageButtonWidth) : 0) - 10 + 'px';
            },
            closeFooter() {
                this.handleCheckAllChange(false);
                this.showFooter = false;
                this.refreshMainHeight();
            },
            refreshMainHeight() {
                this.mainHeight = (parseInt(this.$store.getters.getTopMainHeightFn) - (this.showFooter ? parseInt(footerHeight) : 0)) - (parseInt(header1Height)) - (parseInt(header2Height)) + 'px';
            },
            hideCheckBoxCell(row) {
                return "hideCheckBoxCell";
            },
            showCheckbox(row, column, cell, event) {
                cell.parentNode.querySelector(".el-table-column--selection").querySelector(".el-checkbox__input").style.visibility = "visible";
            },
            hideCheckbox(row, column, cell, event) {
                let ck = cell.parentNode.querySelector(".el-table-column--selection").querySelector(".el-checkbox__input");
                if (ck != null && this.checkedUsers.indexOf(row) < 0) {
                    ck.style.visibility = "hidden";
                }
            },
            clickTableRow(row, column, event) {
                this.$refs.table.setCurrentRow(row);
            },
            handleCheckAllChange(val) {// 全选事件
                if (val) {
                    this.$refs.table.clearSelection();
                    this.tableData.forEach(row => {
                        this.$refs.table.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.table.clearSelection();
                }
                this.isIndeterminate = false;
            },
            handlecheckedUsersChange(val) {// 多选变化事件
                const that = this;
                that.checkedUsers = val;
                let checkedCount = val.length;
                if (checkedCount > 0) {
                    that.showFooter = true;
                    //控制多选选中后不隐藏
                    for (let i = 0; i < checkedCount; i++) {
                        let index = that.tableData.indexOf(val[i]);
                        const childNodes = that.tbody[0].childNodes;
                        if (childNodes != undefined) {
                            const selectChildNode = childNodes[index];
                            const selectTd = selectChildNode.childNodes[0];
                            if (selectTd && selectTd.querySelector(".el-checkbox__input")) {
                                selectTd.querySelector(".el-checkbox__input").style.visibility = "visible"
                            }
                        }
                    }
                } else {
                    that.showFooter = false;
                    for (let j = 0; j < that.tableData.length; j++) {
                        const childNodes = that.tbody[0].childNodes;
                        if (childNodes != undefined) {
                            const selectChildNode = childNodes[j];
                            const selectTd = selectChildNode.childNodes[0];
                            if (selectTd && selectTd.querySelector(".el-checkbox__input")) {
                                selectTd.querySelector(".el-checkbox__input").style.visibility = "hidden"
                            }
                        }
                    }
                }
                that.refreshMainHeight();
                that.checkAll = checkedCount === that.tableData.length;
                that.isIndeterminate = checkedCount > 0 && checkedCount < that.tableData.length;
            },
            getManageUserCount() {
                let count = 0;
                for (let i = 0; i < this.tempTableData.length; i++) {
                    if (this.tempTableData[i].roleType == 0) {
                        count++;
                    }
                }
                return count;
            },
            /***********角色管理*************/
            updateRole(userId) {// 修改角色
                this.roleManage.title = "角色设置";
                this.roleManage.userIds = [userId];
                this.roleManage.type = 'roleConfig';
                this.roleManage.visible = true;
            },
            updateUser(userId){
              this.roleUpdate.userid = userId;
              this.roleUpdate.visible = true;
            },
            copyUser(userId){
              this.memberCopy.userid = userId;
              this.memberCopy.teamMembers = this.tableData;
              this.memberCopy.visible = true;
            },
            updateUserDone(result) {// 角色修改完成
              this.roleUpdate.visible = false;
              if (result == 'ok') {
                this.initData();
              }
            },
            setUserRole(roleId){
              this.roleUpdate.roleId = roleId;
            },
            updateRoles() {// 批量修改角色
                if (this.checkedUsers.length == 0) {
                    this.$message({message: '请选择需要修改角色的用户',type: 'warning'});
                    return;
                }
                const userIds = [];
                for (let i = 0; i < this.checkedUsers.length; i++) {
                    userIds.push(this.checkedUsers[i].userId);
                }
                this.roleManage.title = "角色设置";
                this.roleManage.userIds = userIds;
                this.roleManage.type = 'roleConfig';
                this.roleManage.visible = true;
            },
            manageRole() {
                this.roleManage.title = "角色管理";
                this.roleManage.userIds = [];
                this.roleManage.type = 'roleManage';
                this.roleManage.visible = true;
            },
            roleManageDone(result) {
                this.roleManage.visible = false;
                if (result == 'ok') {
                    this.initData();
                }
            },
            /****************成员添加、删除*****************/
            addMember() {
                this.memberAdd.visible = true;
            },
            memberAddDone(result) {
                this.memberAdd.visible = false;
                if (result == 'ok') {
                    this.initData();
                }
            },
            memberCopyDone(result) {
              this.memberCopy.visible = false;
              if (result == 'ok') {
                this.initData();
              }
            },
            removeUser(userId) {
                this.removeUserRequest([userId]);
            },
            removeUsers() {
                if (this.checkedUsers.length == 0) {
                    this.$message({message: '请选择需要删除的成员',type: 'warning'});
                    return;
                }
                const userIds = [];
                for (let i = 0; i < this.checkedUsers.length; i++) {
                    userIds.push(this.checkedUsers[i].userId);
                }
                if (userIds.indexOf(this.currTeam.userId) > -1) {
                    this.$message({message: '删除成员中不能包含自己，请重新选择',type: 'warning'});
                    return;
                }
                this.removeUserRequest(userIds)
            },
            removeUserRequest(userIds) {
                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.cooperation_manage_team_member_remove',
                            teamId: that.teamId,
                            userIds: JSON.stringify(userIds)
                        }
                    };
                    // 查询数据
                    awsuiAxios.post(params).then(function (ro) {
                        if (ro.result == 'ok') {
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            that.initData();
                        } else {
                            that.$message({message: ro.msg,type: 'warning'});
                        }
                    }).catch(error=>{
                        console.log(error);
                    })
                }).catch(() => {
                });
            }
        },
        computed: {
            tbody() {
                return this.$refs.tableMain.querySelector(".el-table__body-wrapper").querySelector(".el-table__body").getElementsByTagName("tbody");
            },
            listenTopMainHeight() {
                return this.$store.getters.getTopMainHeightFn;
            }
        },
        watch : {
            listenTopMainHeight: function (newd, old) {
                this.refreshMainHeight();
                this.initCurrTeamHeaderWidth();
            }
        }
    }
</script>

<style scoped>
    #manageList >>> .awsui-main {
        padding: 0px 20px !important;
    }
    #tableMain >>> .hideCheckBoxCell .el-checkbox__input {
        visibility: hidden;
    }
    #tableMain >>> .el-table__header-wrapper  .el-checkbox{
        display:none
    }
    #tableMain >>> .el-table__row .operate-icon-display{
        display: none;
    }
    #tableMain >>> .el-table__row:hover .operate-icon-display{
        display: inline-block;
    }
    .inline-block {
        display: inline-block;
    }
    .team-icon-div {
        text-align: center;
        border-radius: 15%;
    }
    .text-overflow-hidden {
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
    }
</style>