<template>
   <el-select 
          ref="select"
          :multiple="multiple" 
          :value="selectValue" 
          @remove-tag="handleRemoveTag"
          @clear="handleClear" 
          @visible-change	="handleVisibleChange"
          :filter-method="handleFilterMethod"
          :loading="loading"
          v-on="$listeners" 
          v-bind="$attrs">
          <el-option style="height:auto;background-color: white;">
            <el-ztree
                class="select-ztree" 
                ref="tree"
                :setting="setting"
                :nodes="nodes" 
                @onClick="onClick"
                @onCheck="onCheck"
                @onCreated="handleCreated"
                />  
          </el-option>
        </el-select>
</template>
<script>
import ElSelect from './select.vue';
import ElOption from './option.vue';
export default {
  name: 'ElSelectZtree',
  components: {
    ElSelect,
    ElOption
  },
  props: {
    value: {
      required: true
    },
    // 参考 ztree 设置
    setting: {
      type: Object,
      default: function() {
        return {};
      }
    },
    // 参考 ztree 设置
    nodes: {
      type: Array,
      default: function() {
        return [];
      }
    },
    // 多选？
    // 不能与radio共用
    multiple: {
      type: Boolean,
      default: false
    },
    // 使用radio?
    // 不能与multiple共用
    radio: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    model: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  },
  data() {
    return {
      selectValue: this.multiple ? [] : {},
      optionValue: [],
      ztreeObj: '',
      isSearch: false,
      loading: true
    };
  },
  methods: {
    onClick: function(evt, treeId, treeNode) {

      if (this.multiple) {
        this.ztreeObj.cancelSelectedNode();
        this.ztreeObj.checkNode(treeNode, !treeNode.checked, true, true);
        this.ztreeObj.updateNode(treeNode);
      } else {

        var val = this.multiple ? [] : '';
        var label = treeNode.name.replace(/<\/?.+?>/g, '');
        if (this.radio) {
          this.ztreeObj.cancelSelectedNode();
          this.ztreeObj.checkNode(treeNode, !treeNode.checked, true, false);
          this.ztreeObj.updateNode(treeNode);
          val = treeNode.checked ? {
            value: treeNode.id,
            currentLabel: label
          } : this.multiple ? [] : '';
        } else {
          val = {
            value: treeNode.id,
            currentLabel: label
          };
        }

        this.selectValue = val;
        this.model = val;
        this.$emit('change', treeNode);
        this.hideDropDown();
        if (this.isSearch) {
          this.handleFilterMethod('');
        }
      }
    },
    onCheck: function(evt, treeId, treeNode) {
      if (this.multiple) {
        this.handleChangeOption(evt, treeId, treeNode);
      } else {

        var val = this.multiple ? [] : '';
        var label = treeNode.name.replace(/<\/?.+?>/g, '');
        if (this.radio) {
          this.ztreeObj.cancelSelectedNode();
          this.ztreeObj.checkNode(treeNode, true, true, false);
          this.ztreeObj.updateNode(treeNode);
          val = treeNode.checked ? {
            value: treeNode.id,
            currentLabel: label
          } : this.multiple ? [] : '';
        } else {
          val = {
            value: treeNode.id,
            currentLabel: label
          };
        }

        this.selectValue = val;
        this.model = val;
        this.$emit('change', treeNode);
        this.hideDropDown();
        if (this.isSearch) {
          this.handleFilterMethod('');
        }

      }
    },
    handleChangeOption(evt, treeId, treeNode) {
      var checkedNodes = this.ztreeObj.getCheckedNodes(true).filter(item => {return !item.children;});
      console.log('checkedNodes', checkedNodes);
      let temp = checkedNodes.map(item => {
        return {
          value: item.id,
          currentLabel: item.name.replace(/<\/?.+?>/g, '')
        };
      });
      this.selectValue = temp;
      this.model = checkedNodes;
    },
    handleCreated: function(ztreeObj) {
      this.ztreeObj = ztreeObj;
      ztreeObj.setting.callback.beforeClick = ((treeId, treeNode)=>{
        if (!this.multiple && treeNode.children) {
          return false;
        }
      });
      ztreeObj.setting.callback.beforeCheck = ((treeId, treeNode)=>{
        if (!this.multiple && treeNode.children) {
          return false;
        }
      });
      ztreeObj.expandNode(ztreeObj.getNodes()[0], true);
      this.loading = false;
    },
    handleRemoveTag(val) {
      var checkedNodes = this.ztreeObj.getCheckedNodes(true);
      let node = checkedNodes.find(item => {
        return item.id === val;
      });
      if (node) {
        this.ztreeObj.cancelSelectedNode(false);
        this.ztreeObj.checkNode(node, false, true, true);
        this.ztreeObj.updateNode(node);
      }
    },
    handleClear() {
      let checkedNodes = this.ztreeObj.getCheckedNodes(true);
      checkedNodes.forEach(node => {
        this.ztreeObj.cancelSelectedNode(false);
        this.ztreeObj.checkNode(node, false, true, false);
        this.ztreeObj.updateNode(node);
      });
      this.selectValue = this.multiple ? [] : '';
      this.model = this.multiple ? [] : '';
    },
    handleFilterMethod(val) {
      if (val === '') {
        this.$refs.tree.resetFuzzySearch();
        this.isSearch = false;
      } else {
        this.$refs.tree.fuzzySearch(val, true, true);
        this.isSearch = true;
      }
    },
    handleVisibleChange(val) {
      if (!val && this.isSearch) {
        this.handleFilterMethod('');
      }
    },
    hideDropDown() {
      this.$refs.select.visible = false;
    }
  }
};
</script>