<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24" style="padding:0 16px">
        <el-input size="small" v-model="param.content.where.condition" class="normal-margin" placeholder="搜索人员" clearable @keyup.enter.native="searchChange"></el-input>
      </el-col>
      <el-col :span="12">
        <div class="tree-panel">
          <div :class="['allData',{'active':active}]" @click="allClick">全部</div>
          <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>
          <div :style="{ height: scrollHeight?scrollHeight:'400px'}"  style="overflow-y:scroll">
            <el-skeleton style="width: 240px" :loading="loading" animated>
              <template slot="template">
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
                <el-skeleton-item variant="text" style="width: 100%;" />
              </template>
              <template>
                <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.enterprisename === searchValue" :label="item.sa_agentsid">{{item.enterprisename}}</el-checkbox>
                    <el-checkbox v-else :label="item.sa_agentsid">{{item.enterprisename}}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </template>
            </el-skeleton>
            
          </div>
        </div>
      </el-col>
    </el-row>
<!--    <div class="footer">
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">{{`已选${checkedMenbers.length}\\${allDataLength}`}}</el-checkbox>
    </div>-->
  </div>
</template>

<script>

import {mapGetters} from 'vuex'

export default {
  props:["defaultData",'scrollHeight','obiectName','obiectId'],
  components:{
  },
  inject:['rowData'],
  computed:{
    ...mapGetters({
      pageOnlyRead:"pageOnlyRead"
    })
  },
  data () {
    return {
      loading:true,
      active:true,
      allDataLength:'',
      deplist:[], // 部门树状结构数据
      responseData:[], // 部门信息
      menberData:[], // 人员信息
      checkedMenbers:[], // 授权人员信息
      saleareaids:[], // 选中的部门
      onCheckedMenber:[], // 当前查询人员列表选中的人员
      searchValue:'', // 搜索人员
      clickdepid:'', // 点击的部门id
      isonlymanager_agent:false,
      checkAll:false,
      isIndeterminate:false,
      param: {
        "id":20221011144903,
        "content": {
            "pageNumber": 1,
            "pageSize": 10000,
            "sa_saleareaids":[],
            "containssub":1,
            "where": {
              "condition": "",
              "status": "ACTIVE"
            }
        }
      }
    }
  },
  methods:{
    searchChange () {
      this.active = true
      this.$refs.tree.setCurrentKey(null)
      this.param.content.isAll = 1
      this.menberList([])
    },
    allClick () {
      this.active = true
      this.$refs.tree.setCurrentKey(null)
      this.param.content.isAll = 1
      this.menberList([])
    },
    // 查询区域
    async department () {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_area_auth",
        "content": {
          "obiectId":this.rowData() ? this.rowData().sa_customerpoolid:0,
          "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) {
      this.param.content.sa_saleareaids = val
      const res = await this.$api.requested(this.param)
      this.menberData = res.data
      this.loading = false
      if(this.allDataLength == '') this.allDataLength = this.menberData.length
      // this.allDataLength = this.menberData.length
      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
    },
    // 点击部门
    nodeClick (row,node,comp) {
      this.checkAll = false
      this.param.content.isAll = 0
      this.clickdepid = row.sa_saleareaid
      this.menberList([row.sa_saleareaid])
      this.active = false
      // this.onCheckedMenber.length === this.menberData.length?this.checkAll = true:this.checkAll = false
    },
    // 勾选部门
    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 = 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()
      this.allClick()
    }, 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 .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;
  margin: 0 16px;
  font-size: 14px;
  /* width:300px; */
  background: #FAFAFA;
}
.footer {
  padding-left:16px;
  border-top: 1px solid #cccccc;
}
.allData {
  height: 26px;
  line-height: 26px;
  font-size: 14px;
  cursor: pointer;
  padding-left: 6px;
  margin-bottom: 6px;
}
.allData:hover {
  background: #f5f7fa;
}
.active {
  background: #4F7BFD !important;
  border-radius: 3px;
  color: #ffffff;
  margin-bottom: 6px;
  padding-left: 6px;
}
</style>