<template>
  <!--  弹出框  -->
  <el-popover placement="bottom-start" :disabled="disabled" v-model="visible">
    <!--  tag盒子  -->
    <div slot="reference" class="tags-box" :class="!disabled|| 'tags-box-disabled'">
      <span v-show="sNodeList.length > 0" class="tags-num">{{sNodeList.length}}</span>
      <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.shortName }}</el-tag>
    </div>
    <!--  文本框    -->
    <el-input style="width: 100%; margin-bottom: 20px" v-model="queryForm.value" @input="serchTreeHandler"
      placeholder="请输入查询机构名称"></el-input>
    <!--  下拉框   -->
    <el-row :gutter="20" type="flex" align="middle">
      <el-col :span="14" :xs="24">
        <el-select :disabled="disable" :popper-append-to-body="false" v-model="queryForm.type" placeholder="请选择过滤机构类型" clearable
          @change="serchTreeHandler">
          <el-option v-for="dict in dict.type.sys_org_type" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-col>
      <el-col :span="10" :xs="24">
        <el-checkbox v-if="checkShow" :disabled="!queryForm.type" v-model="checked">按过滤机构类型勾选</el-checkbox>
      </el-col>
    </el-row>
    <!--  机构树   -->
    <div class="tree-box">
      <el-tree ref="tree" :data="orgTree" :props="treeProps" node-key="id" show-checkbox :check-strictly="true"
        :expand-on-click-node="false" :default-checked-keys="nodes" :default-expanded-keys="nodes"
        @node-click="handleNodeClick" @check="onCheck" :filter-node-method="filterNode">
      </el-tree>
    </div>
  </el-popover>
</template>

<script>
export default {
  dicts: ["sys_org_type"],
  props: {
    //默认选中的node
    defaultNode: {
      type: Array,
      default: () => [],
      required: false,
    },
    //行社机构
    hangsheTree: {
      type: Boolean,
      default: false,
    },
    defaultProps: {
      type: Object,
      default: () => {
        return {
          children: "children",
          label: "shortName",
        };
      },
    },
    //自定义请求
    customRequest: {
      type: Function,
    },
    //组件禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    checkShow: {
      type: Boolean,
      default: false,
    },
    queryData: {
      type: Number,
      default: null,
      required: false,
    },
    // 机构类型筛选条件禁用
    disable: {
      type: Boolean,
      default: false,
      required: false,
    },
    // 机构树上能选择的机构类型
    enabledCheckOrgTypes: {
      type: [Number,Array],
      default: ()=>[],
      required: false,
    }
  },
  data() {
    return {
      //清除图标
      showClearable: false,
      //弹窗显示
      visible: false,
      //结构树
      orgTree: null,
      //过滤条件
      queryForm: {
        value: null,
        type: null,
      },
      //受否全选
      checked: false,
      //已选中的node
      sNodeList: [],
      //默认显示及展开的node
      nodes: [],
      treeProps:{
          disabled: this.getNodedisabled,
          children: "children",
          label: "shortName",
      }
    };
  },
  mounted() {
    this.getDeptTree();
  },
  watch: {
    defaultNode: {
      immediate: true,
      handler(n) {
        if(!n || n.length == 0){
          this.nodes = [];
          this.sNodeList = [];
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys([]);
          });
          return
        }
        this.nodes = this.defaultNode;
        this.$nextTick(() => {
          let arr = [];
          this.defaultNode.forEach(v => {
            let node = this.$refs.tree.getNode(v);
            arr.push(node.data)
          })
          this.sNodeList = arr;
        });
      },
    },
    queryData: {
      handler(n) {
        if (n) {
          this.queryForm.type = parseInt(n);
          this.serchTreeHandler();
        }
      },
      // queryForm: {
      //   deep: true,
      //   handler(n, o) {

      //     if(!n.value&&!n.type){
      //       this.$refs.tree.filter({});
      //     }else{

      //       this.$refs.tree.filter(n);
      //     }
      //   },
      // },
    },
    defaultProps: {
      handler(n) {
        if (n) {
         this.treeProps.label=n.label;
         this.treeProps.children=n.children;
        }
      },
    }

  },
  methods: {
    clear() {
      this.queryForm.value=null;
      this.sNodeList = [];
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.tree.setCurrentKey(null);
      this.nodes = [];
      this.$emit("selectNode",[]);
      this.$emit("selectNodeId", []);
    },
    //筛选条件变化
    serchTreeHandler() {
      this.$refs.tree.filter(this.queryForm);
    },
    /** 查询机构下拉树结构 */
    getDeptTree() {
      if (this.customRequest) {
        this.customRequest().then((response) => {
          this.treeList = response.data;
          return
        });
      }
      this.orgTree = this.$store.getters.orgTree;
      if (this.hangsheTree) {
        this.orgTree = this.$store.getters.depTree;
      }
    },
    getNodedisabled(node) {
      if (this.enabledCheckOrgTypes) {
        if (Array.isArray(this.enabledCheckOrgTypes)) {
          if (this.enabledCheckOrgTypes.length>0 && this.enabledCheckOrgTypes.findIndex((x) => x === node.type) == -1) {
            return true;
          }
        }
        else {
          if (this.enabledCheckOrgTypes !== node.type) {
            return true;
          }
        }
      }
      return false;
    },
    filterNode(value, data, node) {
      if (this.queryForm.value && this.queryForm.type) {
        return (
          data.name.indexOf(this.queryForm.value) !== -1 &&
          data.type == this.queryForm.type
        );
      }
      if (this.queryForm.value) {
        return data.name.indexOf(this.queryForm.value) !== -1;
      }
      if (this.queryForm.type) {
        return data.type == this.queryForm.type;
      }
      return true;
    },

    handleNodeClick() {
    },
    onCheck(data, checked, tree) {
      console.log(1111123213123)
      if (this.checked) {
        let checkNodes = this.$refs.tree.getCheckedNodes();
        let type = this.queryForm.type;
        let recursionFn = function (tree) {
          tree.forEach((item) => {
            if (type == item.type) {
              checkNodes.push(item);
              //console.log('name',checkNodes.indexOf(item))
              //checkNodes.indexOf(item) >= 0? checkNodes.splice(checkNodes.indexOf(item),1):checkNodes.push(item);
            }
            if (item.children?.length > 0) {
              recursionFn(item.children)
            } else {
              return;
            }
          });
        }
        // 递归查询
        recursionFn(data.children);
        let arr = checkNodes.filter(v => {
          return v.type == this.queryForm.type
        });
        this.$refs.tree.setCheckedNodes(arr);
        this.sNodeList = this.$refs.tree.getCheckedNodes();
      }else {
        this.sNodeList = this.$refs.tree.getCheckedNodes();
      }
      let arr = this.sNodeList.map(v=>{return v.id});
      this.$emit("selectNode", this.sNodeList);
      this.$emit("selectNodeId", arr);
    },

    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);
        });
      }
    },
  },
  model: {
    prop: "defaultNode",
    event: "selectNodeId",
  },
};
</script>

<style scoped lang="scss">
.tags-box {
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #606266;
  outline: 0;
  padding: 0 40px 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;
    cursor: pointer;
    &:hover {
      color: #aaa;
    }
  }
}
.tags-box-disabled{
  cursor: default;
}
.tags-num{
  color:#ccc;
  position: absolute;
  right: 20px;
  top:-4px;
}
.tree-box {
  margin-top: 20px;
  max-height: 300px;
  overflow: auto;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  user-select: none;
}
</style>
