<template>
<div class="ContainerBox">
    <!-- 备注区域 -->
    <section class="remarkBox">
        <div class="remarkInfo">
            <i class="el-icon-warning-outline el-icon-flag"></i>
            <span>
            1. 您可以将组织内的用户设置为{{$SuperviseStr.depart}}管理员，协助您管理{{$SuperviseStr.depart}}及用户。<br/>
            2. {{$SuperviseStr.depart}}管理员在{{$SuperviseStr.depart}}管理及用户管理中只能查看并管理自己可管理的{{$SuperviseStr.depart}}，无法管理所有{{$SuperviseStr.depart}}。<br/>
            3. {{$SuperviseStr.depart}}管理员与通讯录权限不一致，例：某用户所在{{$SuperviseStr.depart}}的通讯录权限为“只能查看自己”，即使该用户可管理多个{{$SuperviseStr.depart}}，在查看通讯录时仍然只能查看自己。
            </span>
        </div>
    </section>

    <!-- 按钮区域 -->
    <section class="buttonBox">
        <el-row>
         <el-col :span="12">
            <el-button type="primary" @click="addDept">添加{{$SuperviseStr.depart}}管理员</el-button>
            <el-button @click="exportDepartAdminList">导出</el-button>
            <el-button type="danger" :disabled="disabled" @click="patchDel">批量删除</el-button>
         </el-col>
         <el-col :span="12">
              <el-row :gutter="12">
                    <el-col :span='10'>
                        <el-input
                        v-model="params.keyword"
                        placeholder="输入姓名/账号/手机号"
                        clearable                        
                        />
                    </el-col>
                    <el-col :span='6'>
                        <selectTree
                        ref="selectTree"
                        @getValue="checkChange"
                        @selectClickT="selectClickT"
                        :curValue="defaulData"
                        :treeData="getTreeDepartlist"  
                        @loadingTreeDataEventHandler = "loadingDepartTreeDataEventHandler"               
                        :obj="{                  
                            id: 'id',
                            label: 'name',
                            children: 'children',
                        }"
                        checkStrictly 
                        clearable	
                        filterable	
                        collapseTags 
                        multiple
                        placeholder='请选择部门'                
                        ></selectTree>
                    </el-col>
                    <el-col :span='6'>
                        <selectTree
                        ref="selectTree"
                        @getValue="checkChange2"
                        @selectClickT="selectClickT2"
                        :curValue="defaulData2"
                        :treeData="getTreeDepartlist"  
                        @loadingTreeDataEventHandler = "loadingDepartTreeDataEventHandler"        
                        :obj="{                  
                            id: 'id',
                            label: 'name',
                            children: 'children',
                        }"
                        checkStrictly 
                        clearable	
                        filterable	
                        collapseTags 
                        multiple
                        placeholder='请选择可管理的部门'                
                        ></selectTree>
                    </el-col>
                    <el-col :span='2'>
                        <el-button type="primary" @click="search" >查询</el-button> 
                    </el-col>
             </el-row>
        </el-col>
        </el-row>
    </section>

    <!-- 选中表格内容展示区域 -->
    <section class="TableSelectBox" v-if="multipleSelection.length">
       <span><i class="el-icon-warning-outline el-icon-flag"></i>已选中：<span v-for="(item,index) in multipleSelection" :key="index">{{item.name}}<b v-if="index!=multipleSelection.length-1">,</b></span></span>
    </section>

    <!-- 内容区域 -->
    <section class="contentBox">
        <el-table :data="DepartAdminTableData" ref="districtTable"  max-height="750" default-expand-all  row-key="id"  @selection-change="handleSelectionChange" @select-all="handleSelectionAllChange">
             <el-table-column  type="selection"   width="55">
            </el-table-column>           
            <el-table-column v-for="(item,index) in tableColumn" :key="index" :prop="item.prop" :label="item.label" :width="item.width" v-if="item.show" :fixed='item.label=="姓名"'>
                <template slot-scope="scope">
                    <span v-if="item.prop=='permissionType'"> 
                    </span>  
                    <span v-else-if="item.prop=='joinedManagedAdminName'"> 
                       <a>{{(scope.row[item.prop]?.length>50?(scope.row[item.prop].substring(0,50)+" ..."):scope.row[item.prop])}}</a>
                    </span> 
                    <span v-else>{{scope.row[item.prop]}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="">
                <template slot-scope="scope">
                    <el-button @click="editDept(scope.row)" type="text" size="small" class="primaryColor">编辑</el-button>
                    <el-button @click="delDept(scope.row)" type="text" size="small" class="dangerColor">删除</el-button>               
                </template>
            </el-table-column>
        </el-table>
         <!-- 分页页签 -->
      <pages
        :total="params.total"
        :currentPage.sync="params.pageIndex"
        :pageSize="params.pageSize"
        @handleCurrentChangeSub="handleCurrentChange"
        @handleSizeChangeSub="handleSizeChange"
      ></pages>
    </section>
    
    <!-- 添加编辑部门管理员弹窗 -->
    <DeptAdminDialog :showdialog.sync="showdialog" v-if="showdialog" 
    :paramData="openDepartParam.data" :paramOperType="openDepartParam.operType"
    @refurlist="refurlist" ref="popChildren"></DeptAdminDialog>

</div>
</template>
<script>
import {StaffDepartmentListApi,StaffDepartmentAdminListApi,delDepartmentsAdminApi,exportDepartAdminList
} from "@/api/staffApi.js"
import DeptAdminDialog from './components/DeptAdminDialogV2.vue'
import selectTree from "./components/SelectTree";

export default {
    data(){
        return {
            params: {
                //搜索条件
                pageIndex: 1,
                pageSize: 10,
                keyword: "",
                departIds: [],
                total: 0,
            },
            loadedDepart: false,
            tableData: [],
            DepartAdminTableData: [],
            defaulData: [],
            defaulData2: [],
            getTreeDepartlist: [],
            getTreeDepartlist2: [],
            multipleSelection: [],//全选列表
            tableColumn: [
                { prop: "name", label: "姓名", width: "180", show: true },
                { prop: "telephone", label: "手机号", width: "180", show: true },
                { prop: "departName", label: `所在${$SuperviseStr.depart}`, width: "180", show: true },
                { prop: "joinedManagedAdminName", label: `可管理的${$SuperviseStr.depart}`, width: "", show: true },
            ],
            showdialog: false,
            showdialogImport: false,
            showdialogMove: false,
            showdialogIm: false,
            showdialogUser: false,
            disabled: true,//默认禁用
            isAllSelect: false,//是否全选
            displayOrderShow: false,
            homeTemplateBoradType: localStorage.getItem('homeTemplateBoradType') || '',
            openDepartParam: {
                data: {},
                operType: 0
            }
        }
    },
    components:{
        DeptAdminDialog,
        selectTree, //注册组件

    },
    mounted(){
        if(this.homeTemplateBoradType=='rtpayTemplate'){//rt环境
            this.tableColumn=[
              {prop:"name",label:"姓名",width:"180",show:true},
              {prop:"telephone",label:"账号",width:"180",show:true},
              {prop:"departName",label:`所在${$SuperviseStr.depart}`,width:"180",show:true},
              {prop:"joinedManagedAdminName",label:`可管理的${$SuperviseStr.depart}`,width:"",show:true},
            ]
        }else if(localStorage.getItem('appidSupervise')&&JSON.parse(localStorage.getItem('appidSupervise')).appId=='__d1qEDy3wYq8VF5KvUoE'){//监控端--机构用户管理
            this.tableColumn=[
              {prop:"name",label:"姓名",width:"180",show:true},
              {prop:"telephone",label:"账号",width:"180",show:true},
              {prop:"departName",label:`所在${$SuperviseStr.depart}`,width:"180",show:true},
              {prop:"joinedManagedAdminName",label:`可管理的${$SuperviseStr.depart}`,width:"",show:true},
            ]
        }
        else{
            this.tableColumn=[
              {prop:"name",label:"姓名",width:"180",show:true},
              {prop:"telephone",label:"手机号",width:"180",show:true},
              {prop:"departName",label:`所在${$SuperviseStr.depart}`,width:"180",show:true},
              {prop:"joinedManagedAdminName",label:`可管理的${$SuperviseStr.depart}`,width:"",show:true},
            ]
        }
      this.tableDatalist()//表格列表
      this.tableDataDepartAdminlist()//部门管理员表格列表
    },
    watch:{
      multipleSelection(){//复选框选中启用按钮
          if(this.multipleSelection.length){
              this.disabled=false
          }else{
              this.disabled=true
          }
      }
    },
    methods:{
        exportDepartAdminList(){
           
      //导出
      let obj2 = { domainId:localStorage.domainId };
      exportDepartAdminList(this.params, obj2).then((response) => {
        const content = response;
        const blob = new Blob([content]);
        const fileName = `部门管理员.xlsx`;
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      });
 

        },
        search() {
            //查询
            this.$set(this.params,'pageIndex',1)//重置第一页
            let obj2 = { domainId: this.$route.query.domainId };
            StaffDepartmentAdminListApi(this.params, obj2).then((response) => {
                if (response.data) {
                    this.DepartAdminTableData = response.data.data;
                    this.params.total = response.data.total;
                }
            });
        },
        tableDataDepartAdminlist(){//表格列表
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId
            StaffDepartmentAdminListApi(this.params,obj2).then(response=>{
               if(response.data){
                 this.DepartAdminTableData=response.data.data
                  this.params.total = response.data.total;
                //  this.sortTableData(this.tableData)
               }
            })
        },
        loadingDepartTreeDataEventHandler(keyword) {
            console.log("触发此事件的功能");

            var self = this;
            if (!self.loadedDepart) {
                let obj = { domainId: this.$route.query.domainId }//获取url域domainId
                StaffDepartmentListApi(obj).then(response => {
                    if (response.data) {
                        var result = response.data;
                        self.sortTableData(result)
                        self.tableData = result;

                        self.getTreeDepartlist = self.tableData;
                        self.getTreeDepartlist2 = self.tableData;
                    }
                })
                self.loadedDepart = true;
            }


            console.log(self.getTreeDepartlist);
        },
        tableDatalist(){//表格列表
            //被注释掉的代码
            //this.loadingDepartTreeDataEventHandler("");
        },
        sortTableData(arr){//递归排序
            if(arr.length){
                arr.forEach(item=>{
                    item.displayOrderNumber=item.displayOrder
                    if(item.children.length){
                        this.sortTableData(item.children)
                    }                    
                })
            }
        },
        selectClickT(val) {
            console.log("selectClickT");
            this.getTreeDepartlist=val
        },
        selectClickT2(val) {
            console.log("selectClickT2");
            console.log(val)
            this.getTreeDepartlist2=val
        },
        checkChange(key, data) {
            //selectTree组件-复选框选中的数据
            this.$set(this.params, "departIds", key);
        },
        checkChange2(key, data) {
            //selectTree组件-复选框选中的数据
            this.$set(this.params, "adminDepartIds", key);
        },
        handleCurrentChange(val) {
            this.params.pageIndex = val;
            this.tableDataDepartAdminlist();
        },
        handleSizeChange(val) {
            //切换每页条数
            this.params.pageIndex=1 //重置第一页
            this.params.pageSize = val;
            this.tableDataDepartAdminlist();
        },
        handleSelectionChange(val) {//选中全选
          this.multipleSelection = val;
        },      
        handleSelectionAllChange(selection,first){//全选
            if (!first) {
                this.isAllSelect = !this.isAllSelect;
            }
            selection.map(el => {
                if (el.children) {
                    el.children.map(j => {
                        this.toggleSelection(j, this.isAllSelect);
                    });
                    if (el.children.length > 0) {
                        this.handleSelectionAllChange(el.children, true);
                    }
                }
            });
        }, 
        toggleSelection(row, select) {//全选选中与取消选中           
            if (select) {
                this.$refs.districtTable.toggleRowSelection(row, select);//全选选中
            } else {
                this.$refs.districtTable.clearSelection();//取消选中
            }
        },
        addDept() {//新增             
            this.showdialog = true;
            this.openDepartParam.operType = 0;
            this.openDepartParam.data = {};
            //this.$refs.popChildren.getTableRow({}, 0);          
        },
        editDept(row) {//编辑
            this.showdialog = true;
            this.openDepartParam.operType = 1;
            this.openDepartParam.data = row;
            //this.$refs.popChildren.getTableRow(row, 1);
        },
        delDept(row){//删除
            //删除选中表格数据
            let ids=[row.employeeId]
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId            
            if (Object.keys(row) != "") {
                this.$confirm("此操作将永久删除此对应数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                })
                .then(() => {                    
                    delDepartmentsAdminApi(ids,obj2).then((response) => {  
                      if (response.status==200) {                       
                        this.tableDataDepartAdminlist()//表格列表
                      }
                    }).catch(error=>{
                        console.log(error)
                    });
                })
                .catch(error => {
                    console.log(error)
                    console.log(error.response)
                    // this.radio = ""; //清空选中
                });
            }
        },
        patchDel(){//批量删除           
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId            
            if (this.multipleSelection.length) {
                this.$confirm("此操作将永久删除此对应数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                })
                .then(() => {
                     let ids=[]
                    this.multipleSelection.forEach(item=>{
                        ids.push(item.employeeId)
                    })
                    delDepartmentsAdminApi(ids,obj2).then((response) => {
                         if (response.status==200) {  
                          this.tableDataDepartAdminlist()
                         }
                    });
                })
                .catch(() => {
                    // this.radio = ""; //清空选中
                });
            }
        },
        importDept(){
           this.showdialogImport = true;
        },
        moveDept(){
           this.showdialogMove = true;
           this.$refs.MovepopChildren.getTableRow(this.multipleSelection, 0);      
        },
        ImDept(){
           this.showdialogIm = true;
           this.$refs.ImpopChildren.getTableRow(this.multipleSelection, 0);      
        },   
        close(row){//关闭排序
           this.tableDatalist()//表格列表
        },
        totalMemberClick(row){//点击部门成员数弹窗
           this.showdialogUser = true;
           this.$refs.UserpopChildren.getTableRow(row, 0);     
        },
        refurlist(){//弹窗后刷新列表
        //    this.tableDatalist()//表格列表
           this.tableDataDepartAdminlist()
        }
    }
}
</script>
<style lang="scss">
.ContainerBox{
    .remarkBox{
        .remarkInfo{
            background: #fafafa;              
            color: #666666;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            line-height: 30px;
            padding: 10px;
            display: flex;
            .el-icon-flag{margin-top:9px;color: #ffc108;margin-right:10px;}
        } 
    }
    .primaryColor{color: #108ee9;}
    .dangerColor{color: red;}
    .bluelink{color: #409eff;}       
    .TableSelectBox{
        display: flex;
        background: #e6f3fc;
        color: #666666;
        border: 1px solid #d4f0fc;
        border-radius:4px;
        margin-top:10px;
        margin-bottom:10px;
        padding: 5px 0;
        span{
            line-height: 20px;
            i{margin-left:5px;margin-right:5px;color:#2e8ad7}
        }
    }
} 

.displayOrderInput{
    display: flex; 
    align-items: center;
    i{
        margin-left:10px;cursor: pointer;
        display: flex;
        align-items: center;
    }
}

.el-tree__empty-block{
    display: none;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>