<template>
<div class="ContainerBox">
    <div v-if="domainAdmin||permissionsStr.indexOf('RoleManage')>-1">
    <!-- 备注区域 -->
    <section class="remarkBox">
        <div class="remarkInfo">
            <i class="el-icon-warning-outline el-icon-flag"></i>
            <span>
            1. 您可以为在职{{$SuperviseStr.employee}}授权角色权限，授权权限后，{{$SuperviseStr.employee}}登录系统即可看到并操作相应功能。<br/>
            2. 应用下的角色不互通，请准确勾选相应应用的权限。
            </span>
        </div>
    </section>

    <!-- 按钮区域 -->
    <section class="buttonBox">
        <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="12">
                <div>
                <el-button type="primary" :disabled="disabled" @click="addAuth">批量设置权限</el-button>
                <!-- <el-button>导出授权列表</el-button> -->
                <el-button type="danger" :disabled="disabled" @click="patchDel">批量清除</el-button>
                </div>
            </el-col>
            <el-col :span="12">
                <div class="rightBox">
                <el-input  v-model="params.keyword" placeholder="输入姓名/账号/手机号/证件号码" clearable style="width:80%" />
                <selectTree
                ref="selectTree"
                @getValue="checkChange"
                @selectClickT="selectClickT"
                :curValue="defaulData"
                :data="getTreeDepartlist"     
                :obj="{                  
                    id: 'id',
                    label: 'name',
                    children: 'children',
                }"
                checkStrictly 
                clearable	
                filterable	
                multiple		
                collapseTags
                :placeholder="placeholderSelectDepart"	
                ></selectTree>
                <el-select v-model="params.occupationTypes" multiple collapse-tags placeholder="选择职业类型" style="margin:0 10px">
                   <el-option v-for="(item,index) in occupationTypeArr" :label="item.label" :value="item.value" :key="index"></el-option>  
                </el-select>
                <el-button type="primary" @click="search">查询</el-button>
                </div>
            </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="tableDataAuth" ref="districtTable"  max-height="500" 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=='permission'">
                        <el-popover
                            placement="right-end"
                            title="应用权限"
                            width="100%"
                            trigger="hover"
                            :content="scope.row.permission">
                            <span slot="reference" class="slotinfo">{{scope.row.permission}}</span>
                        </el-popover>
                    </span>
                    
                    <span v-else>{{scope.row[item.prop]}}</span>
                </template>
            </el-table-column>  
            
            <el-table-column
                label="操作"
                min-width="180">
                <template slot-scope="scope">
                    <el-button @click="Edit(scope.row)" type="text" size="small" class="primaryColor">授权</el-button>
                    <el-button @click="clear(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>
    
    <!-- 添加授权弹窗 -->
    <AuthDialog :showdialog.sync="showdialog"  @refurlist="refurlist" ref="popChildren"></AuthDialog>
    <!-- 办理离职弹窗 -->
    <!-- <UserEmployeeBackDialog :showdialogBack.sync="showdialogBack" :getTreeDepartlist="tableData" @refurlist="refurlist" ref="popChildrenBack"></UserEmployeeBackDialog> -->
    <!-- 导入合同弹窗 -->
    <!-- <ImportContractDialog :showdialogImport.sync="showdialogImport" :getTreeDepartlist="tableData" @refurlist="refurlist" ref="ImportpopChildren"></ImportContractDialog> -->
   </div>

   <div v-else class="noAuth">您不是组织管理员或部门管理员,没有授权权限！</div>

</div>
</template>
<script>
import {StaffDepartmentListApi,AuthListApi,AddAuthListApi} from "@/api/staffApi.js"
import AuthDialog from './components/AuthDialog.vue'
import UserEmployeeBackDialog from './components/UserEmployeeBackDialog.vue'
import ImportContractDialog from './components/ImportContractDialog.vue'
import selectTree from "@/components/SelectTree";
export default {
    inject:['permissions'],
    computed:{
      permissionsStr(){//获取权限列表
          return this.permissions()
      }
    },
    data(){
        return{
          tableData:[],
          tableDataAuth:[],
          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:"occupationType",label:"职业类型",width:"180",show:true},
              {prop:"permission",label:"应用权限",width:"",show:true},
          ],
          params:{//搜索条件
            pageIndex:1,
            pageSize:10,
            keyword:'',             
            total:0
          },
          showdialog:false,   
          showdialogBack:false,
          disabled:true,//默认禁用
          isAllSelect:false,//是否全选
          displayOrderShow:false,
          showdialogImport:false,//导入合同
          credentialTypesoptions:[//证件类型
              {value:"IdCard",label:"居民身份证/户口簿"},
              {value:"IdCardOfXiangGang",label:"香港特区护照/身份证明"},
              {value:"IdCardOfAoMen",label:"澳门特区护照/身份证明"},
              {value:"IdCardOfTaiwan",label:"台湾居民来往大陆通行证"},
              {value:"Passport",label:"外国护照"},
              {value:"Arms",label:"退伍军人证"},
              {value:"PoliceNo",label:"警号"},
          ],
          occupationTypeArr:[],
          authenticatedStatusesoptions:[//实名状态
              {value:"UnAuthenticated",label:"未认证"},
              {value:"Authenticating",label:"认证中"},
              {value:"Failed",label:"认证失败"},
              {value:"Passed",label:"已认证"}
          ],
          defaulData:[],
          HighSearchFlag:false,//默认不显示高级搜索
          getTreeDepartlist:[],
          placeholderSelectDepart:`请选择${$SuperviseStr.depart}`,
          homeTemplateBoradType:localStorage.getItem('homeTemplateBoradType')||'',
          domainAdmin:localStorage.getItem("domainAdmin")=='true'?true:false,//是否是组织管理员
        }
    },
    components:{
        selectTree, //注册组件
        AuthDialog,  
        UserEmployeeBackDialog,
        ImportContractDialog,
    },
    updated() {//更新生命周期触发
        this.$refs.districtTable&&this.$refs.districtTable.doLayout() //重新刷新页面解决fix固定列问题
    },
    mounted(){    
     if(this.homeTemplateBoradType=='rtpayTemplate'){
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'}]
         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:"occupationType",label:"职业类型",width:"180",show:true},
              {prop:"permission",label:"应用权限",width:"",show:true},
          ]
     }else if(localStorage.getItem('appidSupervise')&&JSON.parse(localStorage.getItem('appidSupervise')).appId=='__d1qEDy3wYq8VF5KvUoE'){//监控端--机构用户管理
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'},{label:'保安员',value:'SecurityGuard'},{label:'警官',value:'Police'}]
         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:"occupationType",label:"职业类型",width:"180",show:true},
              {prop:"permission",label:"应用权限",width:"",show:true},
          ]
     }
     else{
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'},{label:'保安员',value:'SecurityGuard'}]
         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:"occupationType",label:"职业类型",width:"180",show:true},
              {prop:"permission",label:"应用权限",width:"",show:true},
          ]
     }
    //   this.tableDatalist()//部门列表--下拉部门搜索条件
      this.AuthList()//列表表格
    },
    watch:{
      multipleSelection(){
          if(this.multipleSelection.length){
              this.disabled=false
          }else{
              this.disabled=true
          }
      }  
    },
    updated() {//更新生命周期触发
        this.$refs.districtTable.doLayout() //重新刷新页面解决fix固定列问题
    },
    methods:{
        selectClickT(val){
            console.log(val)
            this.getTreeDepartlist=val
        }, 
        async addAuth(){//添加授权
          // 先刷新列表数据，确保获取最新的员工信息
          await this.AuthList();
          // 根据选中的ID从最新列表中找到对应的员工数据
          const updatedSelection = this.multipleSelection.map(selected => {
            return this.tableDataAuth.find(item => item.id === selected.id) || selected;
          });
          this.showdialog=true         
          this.$refs.popChildren.getTableRow(updatedSelection, 0);   
        }, 
        async Edit(row){//编辑
          // 先刷新列表数据，确保获取最新的员工信息
          await this.AuthList();
          // 从最新列表中找到对应的员工数据
          const updatedRow = this.tableDataAuth.find(item => item.id === row.id) || row;
          this.showdialog=true         
          this.$refs.popChildren.getTableRow([updatedRow], 1);   
        },    
        // importContract(){//
        //    this.showdialogImport=true     
        // },      
        search(){//查询
          this.params.pageIndex = 1;//重置第一页
          let obj2={domainId:this.$route.query.domainId}
          AuthListApi(this.params,obj2).then(response=>{
               if(response.data.data){
                   this.tableDataAuth=response.data.data
                   this.params.total=response.data.total
               }
          })
        },  
        tableDatalist(){//部门列表-表格列表
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId
            StaffDepartmentListApi(obj2).then(response=>{
               if(response.data){
                 this.tableData=response.data
                 this.sortTableData(this.tableData)
               }
            })
        },
        sortTableData(arr){//递归排序
            if(arr.length){
                arr.forEach(item=>{
                    item.displayOrderNumber=item.displayOrder
                    if(item.children.length){
                        this.sortTableData(item.children)
                    }                    
                })
            }
            console.log(this.tableData)
        },
        AuthList(){//列表表格-查询结果
           let obj2={domainId:this.$route.query.domainId}
           AuthListApi(this.params,obj2).then(response=>{
               if(response.data.data){
                   this.tableDataAuth=response.data.data
                   this.params.total=response.data.total
               }
           })
        },
        checkChange(key, data) {//selectTree组件-复选框选中的数据
            console.log(key)
            console.log(data)
            this.$set(this.params,"departIds",key)
        },
        handleCurrentChange(val){//分页切换页码
            console.log(val)
            this.params.pageIndex=val
            this.AuthList()
        },
        handleSizeChange(val){//切换每页条数
           console.log(val)
            this.params.pageSize=val
            this.AuthList()
        },
        handleSelectionChange(val) {//选中全选
          console.log(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.$refs.popChildren.getTableRow({}, 0);          
        },
        BackEmp(row){//编辑
          this.showdialogBack = true;
          this.$refs.popChildrenBack.getTableRow(row, 1);
        },
        clear(row){//清除
            //删除选中表格数据
            let employeeIds=[row.id]
            let roleIds=[]
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId            
            if (Object.keys(row) != "") {
                this.$confirm("此操作将清除当前用户的应用权限, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                })
                .then(() => {
                    AddAuthListApi(employeeIds,roleIds,obj2).then(() => {
                      this.AuthList()//表格列表
                    });
                })
                .catch(() => {
                    
                });
            }
        },
        download(row){
            if(row.attachment){
                window.open(row.attachment)
            }
        },
        patchDel(){//批量删除           
            let obj2={domainId:this.$route.query.domainId}//获取url域domainId            
            if (this.multipleSelection.length) {
                this.$confirm("此操作将清除选择用户对应的应用权限, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                })
                .then(() => {
                    let employeeIds=[]
                    this.multipleSelection.forEach(item=>{
                        employeeIds.push(item.id)
                    })
                    let roleIds=[]
                    AddAuthListApi(employeeIds,roleIds,obj2).then(() => {
                      this.AuthList()//表格列表
                    });
                })
                .catch(() => {
                    // this.radio = ""; //清空选中
                });
            }
        },
        importEmployee(){
           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);      
        }, 
        refurlist(){//弹窗后刷新列表
           this.AuthList()//表格列表
        }
    }
}
</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;}
        } 
    }
    .rightBox{
        display: flex;justify-content: flex-end;
        .el-input{margin-right:10px;}
    }
    .HighSearchBox{
        margin-top:15px;
    }
    .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;
    // .el-input{width: 80%;}
    i{
        margin-left:10px;cursor: pointer;
        display: flex;
        align-items: center;
    }
}

.slotinfo{overflow: hidden; text-overflow: ellipsis; display:-webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;}
.noAuth{text-align: center;font-size: 24px;margin: 50px auto;}
</style>