<script lang="ts" setup>
import {
  getOrgTreeList,
  getArchivesListPage,
  shareOrgInfo,
  memberInfo,
  getPermitedList,
  getSpaceMemberList,
  postPermitedList} from '@/api/hr/user/share_ctrol'

import { ElDialog, ElMessageBox,TableInstance, TreeInstance } from 'element-plus';

const props = withDefaults(defineProps<{
  uid:string,   //当前用户的uuid
  uuid:string, //文档的uuid
  spaceid?:string, //支持空间feature
  confirmFunc?:(data:string[],infos:string[])=>void, //父级组件完全接管提交流程，组件不在做相关处理
  closeFunc:(refresh?:boolean)=>void,  //父级只需销毁组件
}>(),{})

const treeRef=ref<TreeInstance>() //tree组件的引用，为了实现初始选中状态
const treeData =ref<shareOrgInfo[]>([]) // 组织结构树的数据源
const members=ref<memberInfo[]>([]) //tablelist's data
const permited=new Set<string>()  //文档成员的id列表，用集合结构为了快速实现增删修改
const treeSelected=new Array<number>() //所有选中的tree节点
const permitedInfos=new Set<string>() //文档成员的姓名职位信息集合，为了实现与成员列表的同步修改
const tableMembersRef=ref<TableInstance>() //table组件的引用，为了实现初始选中状态
const memberName=ref("")//通过姓名查找成员

function onNodeClick(data:shareOrgInfo){
  members.value=[]//这里在切换时应该清理现有数据，容易造成tableRef选中事件失效
  getArchivesListPage({adminorg:data.id, page:1,pagesize:13}).then(resp=>{
    if(resp.data.count >100){
      ElMessageBox.alert("人数过多，不再显示具体人员，请分配部门可见权限")
      return
    }
    members.value=resp.data.list
   
    //设置默认选中的人员
    setTimeout(() => {
      members.value.forEach(row => {
      if (permited.has('p0'+row.keystr)) {
          // 确保 row-key 正确并且数据一致，手动选中行, 还要设置:reserve-selection="true"！！！
          tableMembersRef.value.toggleRowSelection(row,true)
        }
      })
    }, 500)
  })
}

function onSavePermChange(){
  let _dprt= treeRef.value?.getCheckedKeys() //这里不能只获取叶子节点，因为有些员工的所属部门并不是叶子节点
  let _dprtNodes= treeRef.value?.getCheckedNodes(false,true)
  let _list = permited.keys().toArray().filter(val=>val!=='') //成员的key
  let _infos = permitedInfos.keys().toArray().filter(val=>(val!==''&&!val.includes(":"))) //成员的姓名和部门信息

  //把部门权限加入list列表
  //dprt:d101d102d303....
  _list.push("dprt:d"+_dprt?.join("d"))
  //把部门名称加入infos列表
  _dprtNodes?.forEach((item=>_infos.push(item.level+":"+item.name)))

  //由父级组件自主处理，并自动清理本弹窗组件
  if(props.confirmFunc&&_list){
    props.confirmFunc(_list,_infos)
    props.closeFunc() //关闭销毁
    return
  }

  //btoa 是浏览器默认base64码工具
  postPermitedList(props.uid,{ 
    permitList: btoa(_list.join("|")),
    permitInfos:_infos.join("|"),
    update: "true",
    uid: props.uid,
    uuid: props.uuid,
    len: _list.length
  }).then(resp=>{
    props.closeFunc(true)
  }).catch(()=>{
      ElMessageBox.alert("处理失败")
      return
  })
}

function onManualSelect(select:[],row:memberInfo){
  if(permited.has('p0'+row.keystr)){ //取消
    permited.delete('p0'+row.keystr)
    permitedInfos.delete(`${row.name}-${row.maindeparmentname}-${row.positionname}`)
  }else{
    permited.add('p0'+row.keystr) //添加
    permitedInfos.add(`${row.name}-${row.maindeparmentname}-${row.positionname}`)
  }
}

function onSelectionAll(news:memberInfo[]){
  if(news.length>0){
    members.value.forEach((item)=>{
      permited.add('p0'+item.keystr)
      permitedInfos.add(`${item.name}-${item.maindeparmentname}-${item.positionname}`)
    })
  }else{
    members.value.forEach((item)=>{
      permited.delete('p0'+item.keystr)
      permitedInfos.delete(`${item.name}-${item.maindeparmentname}-${item.positionname}`)
    })
  }
}

function onFindMemberByName(name:string){
  getArchivesListPage({keywords:name, page:1,pagesize:20}).then(resp=>{
    members.value=resp.data.list
    memberName.value=""
  })
}

onMounted(()=>{
  //在批量分享文件的时候，是没有uuid的，可以避免服务器的错误提示：uuid should not null
  if(props.uuid!==""){
    getPermitedList(props.uid,{uuid:props.uuid}).then(resp=>{
      resp.data?.permited?.forEach(item=>{
        if (item.startsWith("dprt")){
          let arr=item.replace("dprt:d","").split("d")
          arr.forEach(val=>treeSelected.push(parseInt(val)))
          return
        }
        permited.add(item) //userUuids constitue the permited list 
      });

      resp.data?.infos?.forEach(item=>{
        permitedInfos.add(item)
      })
    })
  }else if(props.spaceid!==""){
    //空间支持
    getSpaceMemberList(props.uid,{space:props.spaceid}).then(resp=>{
      resp.data?.members?.forEach(item=>{
        permited.add(item) //userUuids constitue the permited list 
      });

      resp.data?.dprts?.forEach(val=>{
        if(val.match("[a-z]")) return; //去除可能不合规的内容
        treeSelected.push(parseInt(val))
      })
    })
  }
  
  getOrgTreeList({}).then(resp=>{
    treeData.value=resp.data
  })  
})

</script>

<template>
  <el-dialog  :model-value="true" :style="{'max-height': '749px'}" v-on:close="closeFunc()">
    <template #header>
      <span>成员管理</span>
    </template>  
    <div style="display: grid;width: 100%;grid-template-columns:1fr 1fr;">
      <div class="menus_tree">
        <el-input
          v-model="memberName"
          class="w-60 mb-2"
          placeholder="查找成员"
          @change="onFindMemberByName(memberName)"
        />
        <el-tree
          ref="treeRef"
          :data="treeData"
          node-key="id"
          show-checkbox
          :default-checked-keys="treeSelected"
          :check-on-click-leaf="false"
          :style="{maxHeight:'324px','overflow-y': 'auto'}"
          :props="{label: 'name',children:'child',isLeaf:'dir'}"
          :default-expanded-keys="[313]"
          @node-click="onNodeClick"
        />
      </div>
      
    </div>
    <div class="tablelist">
        <el-table ref="tableMembersRef" 
          :data="members"
          :row-key="row => row.keystr"
          style="overflow-y: auto;height: 250px;"
          @select="onManualSelect"
          @select-all="onSelectionAll"
          >
          <el-table-column type="selection" :reserve-selection="true" width="30" />
          <el-table-column  property="name" label="成员"></el-table-column>
          <el-table-column  property="positionname" label="职位"></el-table-column>
        </el-table>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeFunc()">取消</el-button>
        <el-button type="primary" @click="onSavePermChange">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.tablelist{
    width: 100%;
    padding: 10px;
    border: 2px solid;
    border-radius: 16px;
}

</style>

<style>
    /* dialog的body内容样式设置*/
    .el-dialog{
      /* 让整个弹出窗口位置更高一些*/
      --el-dialog-margin-top:7vh; 
    }
    
</style>