<template>
    <!--  弹出框  -->
    <el-popover
      placement="bottom-start"
      :disabled="disabled"
      v-model="visible">
      <!--  选中的值  -->
      <div  slot="reference" class="tags-box">
        <i v-if="sNodeList.length > 0 && !disabled" class="el-icon-circle-close close-icon" @click="clear"></i>
        <el-tag type="success" v-for="v in sNodeList" :key="v.id">{{v.name}}</el-tag>
      </div>

      <!--  文本框    -->
      <el-input style="width: 100%;margin-bottom: 20px;" v-model="queryForm.value" placeholder="请输入过滤值" clearable></el-input>
      <!--  下拉框   -->
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="14" :xs="24">
          <el-select  v-model="queryForm.type" placeholder="请选择过滤机构类型" clearable>
            <el-option
              v-for="dict in dict.type.org_type_number"
              :key="dict.value"
              :label="dict.label"
              :value="`${dict.value}`"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="10" :xs="24" >
          <el-checkbox v-model="checked">按过滤机构类型勾选</el-checkbox>
        </el-col>
      </el-row>
      <!--  机构树   -->
      <div class="tree-box">
        <el-tree
          ref="tree"
          :data='orgTree'
          :props="props"
          node-key="id"
          show-checkbox
          check-strictly
          :expand-on-click-node="false"
          :default-checked-keys="nodes"
          @node-click="handleNodeClick"
          @check="onCheck"
          :filter-node-method="filterNode">
        </el-tree>
      </div>
  </el-popover>
</template>

<script>
import {deptTreeSelect} from "@/api/system/public";

export default {
  dicts:['org_type_number'],
  props: {
    defaultNode: {
      type: Array,
      required: false
    },
    disabled:{
      type: Boolean,
      default:false,
      required: false
    }
  },
  data (){
    return {
      //清除图标
      showClearable:false,
      //弹窗显示
      visible:false,
      //结构树
      orgTree:null,
      //自定义字段
      props: {
        label: 'name',
      },
      //过滤条件
      queryForm:{
        value:null,
        type:null,
      },
      //受否全选
      checked:false,
      //默认展示的node
      //defaultNode:[],
      //已选中的node
      sNodeList:[],
      nodes:[],
    }
  },
  mounted(){
    this.getDeptTree();
  },
  watch: {
    defaultNode: {
      deep: true,
      handler(n) {
        this.$nextTick(() => {
          this.sNodeList = n;
          this.nodes = n;
        });
      },
    },
    queryForm:{
      deep:true,
      handler(n,o) {
        this.$refs.tree.filter(n);
      },
    },
  },
  // computed: {
  //   defaultNode:
  //   //pv: sync("value"),
  // },
  model:{
    prop: 'defaultNode',
    event: 'change'
  },
  methods:{
    clear(){
      this.sNodeList = [];
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.tree.setCurrentKey(null);
      this.$emit("selectNode", JSON.stringify(this.sNodeList));
    },
    /** 查询机构树 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.orgTree = response.data;
      });
    },
    filterNode(value,data,node){
      if (this.queryForm.value && this.queryForm.type) {
        return data.name.indexOf(this.queryForm.value) >= 0 && data.type == this.queryForm.type;
      }
      if (this.queryForm.value) {
        return data.name.indexOf(this.queryForm.value) >= 0;
      }
      if (this.queryForm.type) {
        return data.type == this.queryForm.type;
      }
      return true
    },
    handleNodeClick(){

    },
    onCheck(data, checked, tree) {
        if (this.queryForm.type && this.checked) {
          let subOrgIds = [];
          let currentCheckedIndex = checked.checkedKeys.findIndex(
            (x) => {
              x == data.id
            }
          );
          checked.checkedKeys.splice(currentCheckedIndex, 1);
          let checkValue = currentCheckedIndex > -1;
          this.getSubOrgIdsByOrgType(data, this.queryForm.type, subOrgIds);
          console.log(subOrgIds,checkValue,'subOrgIds')
          if (!checkValue) {
            subOrgIds.forEach((x) => checked.checkedKeys.push(x.id));
          } else {
            subOrgIds.forEach((x) => {
              let index = checked.checkedKeys.findIndex((y) => x.id == y);
              if (index > -1) {
                checked.checkedKeys.splice(index, 1);
              }
            });
          }
          console.log(checked,'checked')
          this.$refs.tree.setCheckedKeys(checked.checkedKeys);
      }
      this.sNodeList = this.$refs.tree.getCheckedNodes();
      this.$emit("selectNode", JSON.stringify(this.sNodeList));
    },
    getSubOrgIdsByOrgType(topOrg, orgType, orgIdList) {
        if (!topOrg) return;
        if (topOrg.type == orgType) {orgIdList.push(topOrg)};
        if (topOrg.children && topOrg.children.length > 0) {
          topOrg.children.forEach((item) => {
            this.getSubOrgIdsByOrgType(item, orgType, orgIdList);
          });
        }
    },
  }
}
</script>

<style scoped lang="scss">
  .tags-box{
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    color: #606266;
    outline: 0;
    padding: 0 15px 0 5px;
    width: 100%;
    min-height: 40px;
    max-height: 40px;
    position: relative;
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    >span{
      margin: 5px 10px;
    }
    &:hover{
      .close-icon{
        display: block;
        color: #666;
      }
    }
    .close-icon{
      position: absolute;
      top:30%;
      right: 5px;
      display: none;
      cursor: pointer;
    }
  }
  .tree-box{
    margin-top: 20px;
    max-height: 300px;
    overflow: auto;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
  }
</style>
