<template>
  <div class="el-tree-dialog">
    <el-dialog
      :append-to-body="true"
      :title="title"
      :visible="visible"
      custom-class="custom-dialog"
      @close="close">
      <el-row :gutter="20">
        <el-col class="el-tree-dialog__col" :span="12">
          <div class="el-tree-dialog__head">待选</div>
          <el-input class="el-tree-dialog__input"
            placeholder="输入关键字进行过滤"
            v-model="filterUncheckText">
          </el-input>
          <div class="el-tree-dialog__content">
            <el-tree
                class="el-tree-dialog__tree"
                ref="tree"
                :filter-node-method="filterNode"
                :data="data"
                :lazy="lazy"
                :load="load"
                :render-content="renderWrapContent()"
                :check-strictly="checkStrictly"
                :default-expanded-keys="defaultExpandedKeys"
                :default-checked-keys="defaultCheckedKeys"
                :show-checkbox="showCheckbox"
                node-key="id"
                @check-change="checkChange"
                @node-click="nodeClick">
            </el-tree>
          </div>
        </el-col>
        <el-col class="el-tree-dialog__col" :span="12">
          <div class="el-tree-dialog__head">已选</div>
          <el-input class="el-tree-dialog__input"
            placeholder="输入关键字进行过滤"
            v-model="filterCheckText">
          </el-input>
          <div class="el-tree-dialog__content">
            <div class="el-tree-dialog__nodes" ref="nodes">
              <template v-for="(i, index) in filterCheckNodes">
                <div class="el-tree-dialog__node" :key="`${i.id}${index}`">
                  <span class="el-tree-dialog__node__label" :title="i.label">{{i.label}}</span>
                  <span class="el-icon-close el-tree-dialog__node__icon" @click="cancelCheck(i)"></span>
                </div>
              </template>
              <template v-for="(i, index) in placeNodes">
                <div class="el-tree-dialog__placenode" :key="index"></div>
              </template>
            </div>
          </div>
        </el-col>
      </el-row>
      <template slot="header">
        <slot name="header"></slot>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clickDialogDisable">{{this.cancelText}}</el-button>
        <el-button type="primary" @click="clickDialogConfirm">{{this.confirmText}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ElDialog from 'element-ui-for-gov/packages/dialog';
import ElTree from 'element-ui-for-gov/packages/tree';
import ElInput from 'element-ui-for-gov/packages/input';
import ElRow from 'element-ui-for-gov/packages/row';
import ElCol from 'element-ui-for-gov/packages/col';
import ElButton from 'element-ui-for-gov/packages/button';
import Radio from 'element-ui-for-gov/packages/radio';
export default {
  name: 'ElTreeDialog',
  components: {
    ElDialog,
    ElTree,
    ElInput,
    ElRow,
    ElCol,
    ElButton,
    Radio
  },
  props: {
    title: {
      type: String,
      default: '选择用户组'
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array
    },
    renderContent: {
      type: Function
    },
    clickDisable: {
      type: Function
    },
    clickConfirm: {
      type: Function,
      default() {
        return ()=>{};
      }
    },
    checkStrictly: {
      type: Boolean,
      default() {
        return false;
      }
    },
    defaultExpandedKeys: {
      type: Array,
      default() {
        return [];
      }
    },
    defaultCheckedKeys: {
      type: Array,
      default() {
        return [];
      }
    },
    getLeafOnly: {
      type: Boolean,
      default() {
        return false;
      }
    },
    showCheckbox: {
      type: Boolean,
      default() {
        return true;
      }
    },
    lazy: {
      type: Boolean,
      default: false
    },
    load: {
      type: Function,
      default() {
        return () => {};
      }
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    confirmText: {
      type: String,
      default: '确定'
    }
  },
  data() {
    return {
      radio: '',
      radioNode: {},
      filterUncheckText: '',
      filterCheckText: '',
      currentNodes: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (!this.showCheckbox) {
        this.radio = this.defaultCheckedKeys[0];
        let node = this.findNode(this.radio, this.data || []) || {};
        this.radioNode = node;
        this.currentNodes = [node];
      }
    });
  },
  methods: {
    stopRadio(e) {
      e.stopPropagation();
    },
    renderWrapContent() {
      if (this.renderContent && typeof this.renderContent === 'function') {
        return (h, { node, data, store }) => {
          return (<span class="wrap-tree-node">
            {(!this.showCheckbox && !node.hideCheckbox) && <Radio nativeOnClick={this.stopRadio} value={this.radio} onInput={this.$_handleRadio} label={data.id}></Radio>}
            {this.renderContent(h, { node, data, store })}
          </span>);
        };
      } else {
        return (h, { node, data, store }) => {
          return (
            <span class="wrap-tree-node">
              {(!this.showCheckbox && !node.hideCheckbox) && <Radio nativeOnClick={this.stopRadio} value={this.radio} onInput={this.$_handleRadio} label={data.id}></Radio>}
              <span class="el-icon-folder wrap-tree-node__icon"></span>
              <span>{node.label}</span>
            </span>);
        };
      }
    },
    findNode(id, array) {
      for (let i = 0; i < array.length;i++) {
        if (array[i].id === id) {
          return array[i];
        }
        if (array[i].children && array[i].children.length) {
          return this.findNode(id, array[i].children);
        }
      }
    },
    close() {
      this.$emit('update:visible', false);
    },
    getNodes() {
      if (!this.showCheckbox) {
        return this.radioNode;
      }
      let tree = this.$refs.tree;
      let nodes = tree && tree.getCheckedNodes(this.getLeafOnly);
      return nodes;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    checkChange(...value) {
      this.currentNodes = this.getNodes();
      this.$emit('check-change', ...value);
    },
    nodeClick(...value) {
      this.$emit('node-click', ...value);
    },
    clickDialogDisable() {
      if (this.clickDisable && typeof this.clickDisable === 'function') {
        this.clickDisable();
        return;
      }
      this.close();
    },
    clickDialogConfirm() {
      if (this.clickConfirm && typeof this.clickConfirm === 'function') {
        this.clickConfirm(this.getNodes());
      }
      this.close();
    },
    cancelCheck(node) {
      if (!this.showCheckbox) {
        this.radio = '';
        this.radioNode = {};
        this.currentNodes = [];
      } else {
        this.$refs.tree && this.$refs.tree.setChecked(node.id, false);
        this.currentNodes = this.getNodes();
      }
    },
    $_handleRadio(value) {
      this.radio = value;
      let node = {};
      try {
        node = this.$refs.tree && this.$refs.tree.getNode(value).data || {};
      } catch (e) {
        console.log(e);
      }
      this.radioNode = node;
      this.currentNodes = [node];
      this.$emit('check-change', node);
    }
  },
  computed: {
    filterCheckNodes() {
      return this.currentNodes.filter((item) => {
        return item.label && (item.label.indexOf(this.filterCheckText) !== -1);
      });
    },
    placeNodes() {
      return this.filterCheckNodes && this.filterCheckNodes.length && (3 - (this.filterCheckNodes.length % 3));
    }
  },
  watch: {
    filterUncheckText(val) {
      this.$refs.tree.filter(val);
    }
  }
};
</script>
