<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="tree-panel">
          <el-tree
            ref="tree"
            :data="deplist"
            node-key="sa_saleareaid"
            default-expand-all
            highlight-current
            :check-strictly="true"
            :check-on-click-node="false"
            :expand-on-click-node="false"
            :show-checkbox="true"
            @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_agent" @change="$emit('onAgentParams',saleareaids,checkedMenbers,isonlymanager_agent)">仅组织负责人可见</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-checkbox-group :disabled="pageOnlyRead" v-model="checkedMenbers" @change="handleCheckedChange">
              <div style="margin-bottom:10px" v-for="item in menberData" :key="item.index">
                <el-checkbox v-if="searchValue" v-show="item.agentname === searchValue" :label="item.sa_agentsid">{{item.agentname}}</el-checkbox>
                <el-checkbox v-else :label="item.sa_agentsid">{{item.agentname}}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {mapGetters} from 'vuex'

export default {
  props:["defaultData",'scrollHeight','obiectName','obiectId'],
  components:{
  },
  computed:{
    ...mapGetters({
      pageOnlyRead:"pageOnlyRead"
    })
  },
  data () {
    return {
      deplist:[], // 部门树状结构数据
      responseData:[], // 部门信息
      menberData:[], // 人员信息
      checkedMenbers:[], // 授权人员信息
      saleareaids:[], // 选中的部门
      onCheckedMenber:[], // 当前查询人员列表选中的人员
      searchValue:'', // 搜索人员
      clickdepid:'', // 点击的部门id
      isonlymanager_agent:false,
      checkAll:false,
      isIndeterminate:false,
    }
  },
  methods:{
    // 查询区域
    async department () {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_area_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["areaname"],
          remarks:node["remarks"],
          isused:node["isused"],
          sa_saleareaid:node['sa_saleareaid'],
          parentid:node['parentid'],
          status:node['status'],
          disabled:that.pageOnlyRead,
          children: []
        }
          
        if (node.subarea && node.subarea.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subarea.length; index++) {
            // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
            elNode.children.push(convertToElementTree(node.subarea[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },

    // 根据组织架构范围查询人员
    async menberList (val) {
      let param = {
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_agent",
        "content": {
            "pageNumber": 1,
            "pageSize": 10000,
            "sa_saleareaids":val,
            "containssub":0,
            "where": {
              "condition": ""
            }
        }
      }
      const res = await this.$api.requested(param)
      this.menberData = res.data
      this.checkedmenber()
    },
    // 获取当前查询的人员范围选中的人员
    checkedmenber () {
      let sa_agentsid = this.defaultData.sa_agentsid
      let arr = []
      sa_agentsid.filter(e=>{
        this.menberData.forEach(m=>{
          if (e === m.sa_agentsid) {
            arr.push(e)
          }
        })
      })
      this.onCheckedMenber = arr
    },
    // 全选部门
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3]);
    },
    // 点击部门
    nodeClick (row,node,comp) {
      this.checkAll = false
      this.clickdepid = row.sa_saleareaid
      this.menberList([row.sa_saleareaid])
    },
    // 勾选部门
    nodeCheck (checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys) {
    },
    // 监听部门勾选变化
    checkChange (a,b,c) {
      let arr = this.saleareaids.filter((e)=>{
        if (e !== a.sa_saleareaid) return e
      })
      if (b) {
        if (this.clickdepid === a.sa_saleareaid) {
          let Adata = this.checkedMenbers.filter(itemF=>!this.onCheckedMenber.some(ele=>ele===itemF))
          this.checkedMenbers = Adata
        }
        this.menberData = []
        this.saleareaids.push(a.sa_saleareaid)
      } else {
        this.saleareaids = arr
      }
      this.saleareaids = [...new Set(this.saleareaids)]
      this.$refs.tree.setCheckedKeys(this.saleareaids)
      this.$emit('onAgentParams',this.saleareaids,this.checkedMenbers,this.isonlymanager_agent)
    },
    // 勾选人员
    handleCheckedChange (val) {
      let arr = this.saleareaids.filter((e)=>{
        if (e !== this.clickdepid) return e
      })
      this.$refs.tree.setCheckedKeys(arr)

      this.$emit('onAgentParams',this.saleareaids,this.checkedMenbers,this.isonlymanager_agent)
    },
    // 执行全选
    handleCheckAllChange(val) {
      let arr = this.menberData.map(e=>{
        return e.sa_agentsid
      })
      let arr1 = this.saleareaids.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('onAgentParams',this.saleareaids,this.checkedMenbers,this.isonlymanager_agent)
      } else {
        let Adata = this.checkedMenbers.filter(itemF=>!arr.some(ele=>ele===itemF))
        this.checkedMenbers = Adata
        this.$emit('onAgentParams',this.saleareaids,this.checkedMenbers,this.isonlymanager_agent)
      }
    },
  },
  mounted () {
    setTimeout(() => {
      this.department()
    }, 1000);
  },
  watch:{
    pageOnlyRead () {
    },
    defaultData (val) {
      this.saleareaids = val.sa_saleareaid
      this.checkedMenbers = val.sa_agentsid
      this.isonlymanager_agent = val.isonlymanager_agent
      this.$refs.tree.setCheckedKeys(val.sa_saleareaid)
      this.department()
    }
  }
}

</script>
<style>
.tree-panel{
  max-height: 500px;
  overflow: scroll;
}
.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>