<template>
  <div class="flex-start el-unidirectionalTransfer">
    <div class="el-unidirectionalTransfer__left-panel">
      <div class="el-unidirectionalTransfer__header">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
        >全选
          <span>{{`${value.length}/${leafNodeIdList.length}`}}</span>
        </el-checkbox>
      </div>
      <div :class="['el-unidirectionalTransfer__body', hasFooter ? 'is-with-footer' : '']">
        <el-input
          class="el-unidirectionalTransfer__filter"
          v-model="query"
          size="small"
          :placeholder="filterPlaceholder"
          @mouseenter.native="inputHover = true"
          @mouseleave.native="inputHover = false"
          v-if="filterable"
          :clearable="false"
        >  
        <i slot="suffix"
          :class="['el-input__icon', 'el-icon-' + inputIcon]"
          @click="clearQuery"
        ></i>
        </el-input>
        <el-tree
          ref="tree"
          :data="data"
          class="el-unidirectionalTransfer__list"
          :class="{ 'is-filterable': filterable, 'istree': tree }"
          show-checkbox
          :filter-node-method="filterNode"
          :node-key="props.id"
          :default-checked-keys="value"
          :default-expanded-keys="value"
          :props="props"
          @check-change="handleCheckChange"
        >
        </el-tree>
      </div>
    </div>
    <div class="el-unidirectionalTransfer__right-panel">
      <div class="el-unidirectionalTransfer__header">
        <div>已选房间（{{ value.length }}）</div>
      </div>
      <div class="el-unidirectionalTransfer__body">
        <div class="p-16">  
          <div
            class="flex-between mb-16"
            v-for="(item, index) in lastChildrenList"
            :key="index"
          >
          <div class="text-14">{{ item[props.label] }}</div>
          <i
              class="el-icon-close pointer ml-16"
              @click="delRoom(item)"
          ></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ElUnidirectionalTransfer',
  props: {
    filterPlaceholder: {
      type: String,
      default: '请输入搜索内容'
    },
    filterable: Boolean,
    filterMethod: Function,
    tree: Boolean,
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    props: {
      type: Object,
      default() {
        return {
          label: 'label',
          id: 'id',
          children: 'children'
        };
      }
    }
  },
  data() {
    return {
      query: '',
      inputHover: false,
      leafNodeList: [],
      leafNodeIdList: [] // 子节点id数组
    };
  },
  computed: {
    lastChildrenList() {
      this.leafNodeList = [];
      this.leafNodeIdList = [];
      this.data.forEach(e => {
        const childrenList = e[this.props.children];
        if (!childrenList) {
          this.leafNodeList.push(e);
        } else {
          this.recursionData(childrenList);
        }
      });
      this.leafNodeIdList = this.leafNodeList.map(e => e[this.props.id]);
      return this.leafNodeList.filter(e => this.value.includes(e[this.props.id]));
    },
    isIndeterminate() {
      const checkedLen = this.value.length;
      return checkedLen > 0 && checkedLen < this.leafNodeIdList.length;
    },
    checkAll: {
      get() {
        return this.value.length === this.leafNodeIdList.length;
      },
      set() {}
    },
    hasFooter() {
      return !!this.$slots.default;
    },
    inputIcon() {
      return this.query.length > 0 && this.inputHover
        ? 'circle-close'
        : 'search';
    }
  },
  watch: {
    query(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    handleCheckAllChange(val) {
      const list = val ? this.leafNodeIdList : [];
      this.$refs.tree.setCheckedKeys(list);
      this.handleCheckChange();
    },
    delRoom(item) {
      const checkedKeys = this.value.filter(e => e !== item[this.props.id]);
      const checkedNodes = this.lastChildrenList;
      this.$refs.tree.setCheckedKeys(checkedKeys);
      this.emitData(checkedKeys, checkedNodes);
    },
    handleCheckChange() {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      this.emitData(checkedKeys, checkedNodes);
    },
    emitData(allCheckedKeys, checkedNodes) {
      const checkedKeys = allCheckedKeys.filter(e => this.leafNodeIdList.includes(e));
      let checkedNodesFilter = [];
      checkedNodes.forEach(e => {
        if (!e[this.props.children]) {
          checkedNodesFilter.push({
            id: e[this.props.id],
            label: e[this.props.label]
          });
        }
      });
      this.$emit('input', checkedKeys);
      this.$emit('change', checkedKeys, checkedNodesFilter);
    },
    // 递归源数据
    recursionData(childrenList) {
      childrenList && childrenList.forEach(c => {
        this.leafNodeList.push(c);
        this.recursionData(c[this.props.children]);
      });
    },
    clearQuery() {
      if (this.inputIcon === 'circle-close') {
        this.query = '';
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      if (typeof this.filterMethod === 'function') {
        return this.filterMethod(value, data);
      }
      if (this.props.label) {
        return data[this.props.label].indexOf(value) !== -1;
      }
      return data.label.indexOf(value) !== -1;
    }
  }
};
</script>
