<template>
  <el-dialog
    width="35%"
    ref="treePicker"
    v-dialogDrag
    class="tree-picker"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    append-to-body
  >
    <zte-tree
      ref="zteTree"
      height="300px"
      node-key="id"
      parentId="pid"
      label-prop="name"
      v-loading="loading"
      :data="data"
      :selected="selected"
      :clickExpand="clickExpand"
      :expandAll="expandAll"
      :clickCheck="clickCheck"
      :level="level"
      :show-checkbox="showCheckbox"
    ></zte-tree>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">{{ $t('关闭') }}</el-button>
      <Throttle :time="1000" events="click">
        <el-button size="mini" type="primary" @click.native="handleSubmit">{{ $t('确认') }}</el-button>
      </Throttle>
    </span>
  </el-dialog>
</template>

<script>
import zteTree from './zte-tree';

export default {
  name: 'treePicker',
  components: { zteTree },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    service: {
      type: String,
      default: 'base',
    },
    treeKey: String,
    title: String,
    params: Object,
    selected: String,
    leafOnly: {
      type: Boolean,
      default: false,
    },
    clickExpand: {
      type: Boolean,
      default: true,
    },
    expandAll: {
      type: Boolean,
      default: true,
    },
    clickCheck: {
      type: Boolean,
      default: true,
    },
    showCheckbox: {
      type: Boolean,
      default: true,
    },
    halfChecked: {
      type: Boolean,
      default: false,
    },
    level: Number,
    requestUrl:String,
  },
  data() {
    return {
      data: [],
      loading: true,
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading = true;
      const params = Object.assign({ lovKey: this.treeKey }, this.params);
      this.$http.post(this.requestUrl||`/${this.service}/lov/findTree`, params).then(
        (res) => {
          res = res.data;
          if (res.code === 0) {
            this.data = res.tree;
          }
          this.loading = false;
        },
      ).catch(() => { this.loading = false; });
    },
    handleSubmit() {
      if(this.showCheckbox) {
      const checked = this.$refs.zteTree.getCheckedNodes(this.leafOnly);
      const halfChecked = this.halfChecked && this.$refs.zteTree.getHalfCheckedNodes();
      this.$emit('selectChange', checked, halfChecked);
      } else {
        const noeObj = this.$refs.zteTree.getCurrentNode();
        this.$emit('selectChange', [noeObj]);
      }
      this.$emit('update:dialogVisible', false);
    },
    handleClose() {
      this.$emit('update:dialogVisible', false);
    },
    closeDialog() {
      this.$emit('update:dialogVisible', false);
    },
  },
};
</script>
