<template>
  <div style="padding:1vh;">
    <div v-show="getTreeData.length > 0">
      <div class="search">
        <q-input v-model="searchText" dense outlined @input="onChange" clearable label="搜索（支持两字以上的名字搜索）"/>
      </div>
      <div style="padding-top: 5vh">
        <Tree
          v-if="getTreeData.length > 0"
          ref="tree"
          v-model="selectedKeys"
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :treeData="getTreeData"
          :defaultExpandedKeys="defaultExpandedKeys"
          @select="onSelect"
          @check="onCheck"
        >

          <template slot="title" slot-scope="node">
              <span style="color: rgb(33, 186, 69);" v-if="getselectKeysStr.indexOf(node.key)>-1" >√</span>
              <span v-if="node.title.indexOf(searchValue) > -1">
                {{node.title.substr(0, node.title.indexOf(searchValue))}}
                <span style="color: #f50">{{searchValue }}</span>
                {{node.title.substr(node.title.indexOf(searchValue) + searchValue.length) }}
                <span style="color: #64b5fe">{{ node.no ? node.no:'' }}</span>
              </span>
              <span v-else>
                {{ node.title }} 
                <span style="color: #64b5fe;">{{ node.no  ? node.no:'' }}</span>
              </span>
          </template>
        </Tree>
      </div>
    </div>
    <div v-show="!getTreeData.length > 0">
      正在加载组织机构组件...
    </div>
  </div>
</template>

<script>
  import Tree from 'ant-design-vue/lib/tree';
  import 'ant-design-vue/dist/antd.css';
  import AInputSearch from "ant-design-vue/es/input/Search";
  import {deptall} from "@/service/user/user";

  const dataList = []
  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {//高首骊
      const node = data[i]
      // const key = node.key
      dataList.push({//key,
        title: node.title,
        key: node.key,
        no:node.no,
        avatar:node.avatar,
        id: node.id,
        label: node.label,
        pid: node.pid,
        scopedSlots: {title: 'title'}
      })
      if (node.children) {
        generateList(node.children, node.key)
      }
      node.scopedSlots = {title: 'title'}
    }
  }

  const getParentKey = (key, tree) => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children)
        }
      }
    }
    return parentKey
  }
  export default {
    components: {
      AInputSearch,
      Tree
    },
    name: "organization-ant",
    data() {
      return {
        treeData: [],
        searchValue: '',
        searchText: '',// 自定义
        expandedKeys: [1000001],
        defaultExpandedKeys: [1000001],
        autoExpandParent: true,
        // v-model
        checkedKeys: [],
        // 选择的key
        selectedKeys: [],
        selectedParent: [],
        // 准备提交的选中的部门
        checkedDepartment: [],
        // 准备提交的选中的人类对象
        checkedPeople: [],
        checkNodes: [],
        // 选中部门下的所有人
        checkedPeopleWithDepartment: []
      };
    },
    props: {
      value: {
        type: Array
      }
    },
    computed: {
      getTreeData() {
        // this.initTree();
        // generateList(this.$store.state.orgTreeData)
        // console.log(this.treeData)
        if (this.treeData.length > 0) {
          console.log('计算属性，组织机构，ok');
          this.$emit('ok', 'ok')
        }
        return  this.treeData;
      },
      getselectKeysStr(){
        // alert(this.selectedKeys.map(item=>item).join(","))
        return this.selectedKeys.map(item=>item).join(",")
      }
    },
    created() {
      this.initTree();
    },
    mounted() {
    },
    methods: {
      // 初始化树
      async initTree(){
        let Res = await deptall();
        let resdata = Res.data.data;
        this.treeData.push(resdata)
        generateList(this.treeData);
      },
      onExpand(expandedKeys) {
        // console.log('onExpand', expandedKeys)
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      onCheck(checkedKeys) {
        // console.log('onCheck', checkedKeys)
        // this.checkedKeys = checkedKeys
      },
      onSelect(selectedKeys, info) {
        if(selectedKeys.length==0 || selectedKeys[0]>1000000){return}
        let index = this.selectedKeys.indexOf(selectedKeys[0])
        if(index == -1 && selectedKeys[0]<1000000){
          this.selectedKeys.push(selectedKeys[0]);
        }
        // console.log(this.selectedKeys)
      },
      onChange(e) {
        if (!e) {
          return;
        }
        
        const value = e;
        // const value = e.target.value.toString();
        console.log('正在搜索...' + value);
        console.log('查找中'.value)
        const expandedKeys = dataList.map((item) => {
          // console.log("item",item)
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.getTreeData)
          }
          return null
        }).filter((item, i, self) => item && self.indexOf(item) === i)

        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })
      },
      readyToDeepin() {
        this.checkedDepartment = [];
        this.checkedPeople = [];
        this.checkedPeopleWithDepartment = []
      },
      //  一些递归方法
      deepinTreeData(tree) {
        tree.forEach(node => {
          // 判断是否选中当前节点
          if (this.selectedKeys.indexOf(node.key) > -1) {
            // 判断是否是部门，是部门
            if (node.key > 1000000) {
              this.checkedDepartment.push(node);
            } else {
              //  是人
              this.checkedPeople.push(node);
            }
          } else {
            // 未选中当前节点
            if (node.children) {
              // 执行递归
              this.deepinTreeData(node.children);
            }
          }
        });
      },
      // 递归部门所有人
      deepinChildren(tree) {
        tree.forEach(node => {
          // 判断是否是人
          if (node.key > 1000000) {
            //  是部门
            if (node.children) {
              this.deepinChildren(node.children);
            }
          } else {
            //  是人
            this.checkedPeopleWithDepartment.push(node);
          }
        });
      },
      orderStaffNode(){
        //对选择的人根据选择顺序排序
        let staffNode = []
        for(var i=0;i<this.selectedKeys.length;i++){
          let key = this.selectedKeys[i]
          if(key<1000000){//小于百万的为人员。大于为机构
            let node =this.checkedPeople.filter(item =>item.key==key)[0]
            if(node){
              staffNode.push(node);
            }
          }
        }
        return staffNode
      }
    },
    watch: {
      selectedKeys(val) {
        // 深度遍历组织机构树
        this.readyToDeepin();//清空check的部门和人员
        this.deepinTreeData(this.treeData);

        // 执行递归后，向父组件附件筛选出的数据
        this.$emit('staffNode', this.checkedPeople);
        // this.$emit('departmentNode', this.checkedDepartment);

        // console.log("你到底提交了吗", this)

        // this.deepinChildren(this.checkedDepartment);
        // this.$emit('checkedPeopleWithDepartment', this.checkedPeopleWithDepartment);
        // this.value = this.checkedKeys;
        // console.log("你到底提交了吗?????")
        // this.$emit('input', val);
      },
      // checkedKeys(val){
        // this.readyToDeepin();//清空check的部门和人员
        // this.deepinTreeData(this.treeData);//先把选择的节点，分为人员checkedPeople和部门checkedDepartment
        // this.deepinChildren(this.checkedDepartment);//遍历部门，获取部门下的人checkedPeopleWithDepartment
        // this.$emit('checkStaffNode', this.checkedPeople.concat(this.checkedPeopleWithDepartment));

        //单纯的提交选择的key给父组件
        // let keys = val.filter(item=>item<1000000)
        // this.$emit('checkStaffKey', keys);
      // },
      value(newValue) {
        // console.log('this.value', newValue);
        this.selectedKeys = newValue
        // this.checkedKeys = newValue
      }
    },
  }

  // 筛选方法 结束
</script>

<style scoped>
.search{
  border: 1px solid rgb(208, 208, 220);
  position: fixed;width: 16vw;
  background-color: #fff;
  z-index: 9999;
  padding-left: 1vh;
  padding-top: 1vh;
}
</style>
