<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="tree-panel">
          <el-tree
              ref="tree"
              :data="deplist"
              node-key="departmentid"
              default-expand-all
              highlight-current
              :check-strictly="true"
              :check-on-click-node="false"
              :expand-on-click-node="false"
              :show-checkbox="false"
              @node-click="nodeClick"
              @check="nodeCheck"
              @check-change="checkChange">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }} &nbsp;<i v-if="data.status === 1" class="el-icon-user-solid"></i></span>
              <span>
                <slot name="operation" :data="data"></slot>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="12">
<!--        <div class="flex-align-center flex-between normal-margin">-->
<!--          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全 选</el-checkbox>-->
<!--          <el-checkbox v-model="isonlymanager_dept" @change="$emit('onParams',departmentids,checkedMenbers,isonlymanager_dept)">仅组织负责人可见</el-checkbox>-->
<!--        </div>-->
        <div>
          <el-input size="small" v-model="searchValue" class="normal-margin" placeholder="搜索人员" clearable></el-input>
          <div :style="{ height: scrollHeight?scrollHeight:'400px'}"  style="overflow-y:scroll">
            <el-radio-group :disabled="pageOnlyRead" v-model="checkedMenbers" @change="handleCheckedChange">
              <div style="margin-bottom:10px" v-for="item in menberData" :key="item.index">
                <el-radio v-if="searchValue" v-show="item.name === searchValue" :label="item.hrid">{{item.name}}</el-radio>
                <el-radio v-else :label="item.hrid">{{item.name}}</el-radio>
              </div>
            </el-radio-group>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name: "dep_auth",
  props:["defaultData",'scrollHeight','obiectName','obiectId'],
  components:{
  },
  computed:{
    ...mapGetters({
      pageOnlyRead:"pageOnlyRead"
    })
  },
  data () {
    return {
      deplist:[], // 部门树状结构数据
      responseData:[], // 部门信息
      menberData:[], // 人员信息
      checkedMenbers:[], // 授权人员信息
      departmentids:[], // 选中的部门
      onCheckedMenber:[], // 当前查询人员列表选中的人员
      searchValue:'', // 搜索人员
      clickdepid:'', // 点击的部门id
      isonlymanager_dept:false,
      checkAll:false,
      isIndeterminate:false,
    }
  },
  methods:{
    // 查询部门
    async department () {
      console.log(this.$route.query.id,this.obiectId)
      const res = await this.$api.requested({
        "classname": "webmanage.department.department",
        "method": "querydepartment_auth",
        "content": {
          "obiectId":this.$route.query.id?this.$route.query.id:this.obiectId,
          "obiectName": this.obiectName
        },

      })
      // 数据格式转换成elementui-tree所需的格式
      this.responseData = res.data
      this.deplist = this.createMenu(res.data)
      this.$emit('onClick',{data:this.deplist[0],parent:[]})

      // 如果存在默认组织数据就执行
    },

    createMenu (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        // 新节点
        var elNode = {
          label: node["depname"],
          parentid:node['parentid'],
          departmentid:node["departmentid"],
          value:node["departmentid"],
          remarks:node["remarks"],
          isused:node["isused"],
          changedate:node['changedate'],
          changeby:node['changeby'],
          createdate:node['createdate'],
          createby:node['createby'],
          depno:node['depno'],
          status:node['status'],
          disabled:that.pageOnlyRead,
          children: []
        }

        if (node.subdep && node.subdep.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subdep.length; index++) {
            // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
            elNode.children.push(convertToElementTree(node.subdep[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },

    // 根据组织架构范围查询人员
    async menberList (val) {
      let param = {
        "classname": "webmanage.hr.hr",
        "method": "query_hrList",
        "content": {
          "nocahe":true,
          "pageNumber": 1,
          "pageSize": 10000,
          "departmentids":val,
          "containssub":0,
          "where": {
            "condition": ""
          }
        }
      }
      const res = await this.$api.requested(param)
      this.menberData = res.data
      console.log(this.menberData)
      this.checkedmenber()
    },
    // 获取当前查询的人员范围选中的人员
    checkedmenber () {
      let hrid = this.defaultData.hrid
      let arr = []
      hrid.filter(e=>{
        this.menberData.forEach(m=>{
          if (e === m.hrid) {
            arr.push(e)
          }
        })
      })
      this.onCheckedMenber = arr
    },
    // 点击部门
    nodeClick (row,node,comp) {
      this.checkAll = false
      this.clickdepid = row.departmentid
      this.menberList([row.departmentid])
      console.log(this.clickdepid)
      // this.onCheckedMenber.length === this.menberData.length?this.checkAll = true:this.checkAll = false
    },
    // 勾选部门
    nodeCheck (checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys) {
    },
    // 监听部门勾选变化
    checkChange (a,b,c) {
      let arr = this.departmentids.filter((e)=>{
        if (e !== a.departmentid) return e
      })
      if (b) {
        if (this.clickdepid === a.departmentid) {
          let Adata = this.checkedMenbers.filter(itemF=>!this.onCheckedMenber.some(ele=>ele===itemF))
          this.checkedMenbers = Adata
        }

        this.menberData = []
        this.departmentids.push(a.departmentid)
      } else {
        this.departmentids = arr
      }
      this.departmentids = [...new Set(this.departmentids)]
      this.$refs.tree.setCheckedKeys(this.departmentids)
      this.$emit('onParams',this.departmentids,this.checkedMenbers,this.isonlymanager_dept)
    },
    // 勾选人员
    handleCheckedChange (val) {
      let arr = this.departmentids.filter((e)=>{
        if (e !== this.clickdepid) return e
      })
      this.$refs.tree.setCheckedKeys(arr)

      this.$emit('onParams',this.departmentids,this.checkedMenbers,this.isonlymanager_dept)
    },
    // 执行全选
    handleCheckAllChange(val) {
      let arr = this.menberData.map(e=>{
        return e.hrid
      })
      let arr1 = this.departmentids.filter((e)=>{
        if (e !== this.clickdepid) return e
      })
      this.$refs.tree.setCheckedKeys(arr1)
      this.isIndeterminate = false;
      if (this.checkAll) {
        this.checkedMenbers = this.checkedMenbers.concat(arr)
        this.$emit('onParams',this.departmentids,this.checkedMenbers,this.isonlymanager_dept)
      } else {
        let Adata = this.checkedMenbers.filter(itemF=>!arr.some(ele=>ele===itemF))
        this.checkedMenbers = Adata
        this.$emit('onParams',this.departmentids,this.checkedMenbers,this.isonlymanager_dept)
      }
    },
  },
  mounted () {
    setTimeout(() => {
      this.department()
    }, 1000);
  },
  watch:{
    defaultData (val) {
      this.departmentids = val.departmentid
      this.checkedMenbers = val.hrid
      this.isonlymanager_dept = val.isonlymanager_dept
      this.$refs.tree.setCheckedKeys(val.departmentid)
      this.department()
    }
  }
}
</script>

<style scoped>
.tree-panel .el-tree {
  background: none;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  background: none;
}
</style>
  <style scoped>
  .tree-panel{
    padding: 16px;
    font-size: 14px;
    /* width:300px; */
    background: #FAFAFA;
  }
</style>