<template>
  <container-item-wrapper :widget="widget">
    <div>
      <div class="tree-form">
        <template v-if="widget.options.filter">
          <el-input
            v-if="!widget.options.treeFilterType"
            :key="0"
            :size="widget.options.size"
            :placeholder="i18nt('designer.setting.enterForQuery')"
            v-model="filterText"
            @change="handleFilterTextChange"
            class="txt"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleClickButton"></el-button>
          </el-input>
          <el-date-picker v-else-if="widget.options.treeFilterType==1" v-model="filterText" type="date" value-format="yyyy-MM-dd" @change="handleFilterTextChange" :placeholder="$t1('请输入日期')"></el-date-picker>
        </template>

      </div>
      <div class="tree-btns"
           v-show="widget.options.selectClearAllNode && widget.options.showCheckBox || widget.options.expandRetractAllNode">
        <el-button
          v-if="widget.options.expandRetractAllNode"
          type="primary"
          round
          plain
          :size="widget.options.size"
          @click="expandAllNodes()"
          class="btn"
        >
          {{ i18nt("designer.setting.expandRetractAllNode") }}
        </el-button>
        <el-button
          v-if="widget.options.selectClearAllNode && widget.options.showCheckBox"
          type="primary"
          round
          plain
          :size="widget.options.size"
          @click="checkAllNodes()"
          class="btn"
        >
          {{ i18nt("designer.setting.selectClearAllNode") }}
        </el-button>
      </div>
      <el-tree
        :data="widget.options.treeData"
        :props="defaultProps"
        ref="tree"
        border
        :lazy="widget.options.lazy"
        node-key="id"
        highlight-current
        :current-node-key="currentKey"
        :show-checkbox="widget.options.showCheckBox"
        :expand-on-click-node="widget.options.expandOnClickNode"
        :default-expand-all="widget.options.defaultExpandAllNode"
        :draggable="widget.options.draggable"
        :check-strictly="widget.options.checkStrictly"
        :filter-node-method="filterNode"
        class="tree-list"
        icon-class="el-icon-arrow-down"
        @node-click="handleTreeNodeClick"
        @node-contextmenu="handleTreeNodeContextmenu"
        @check="handleTreeNodeCheck"
        @check-change="handleCheckChange"
        :load="loadNode"
        v-if="showTree"
      >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                v-if="widget.options.nodeEdit"
                type="primary"
                link
                plain
                :size="widget.options.size"
                @click.stop="append(data)"
                class="button-sty"
                icon="el-icon-plus"
              >
              {{ i18nt("designer.setting.add") }}
            </el-button>
            <el-button
              v-if="widget.options.nodeEdit"
              type="primary"
              link
              plain
              :size="widget.options.size"
              @click.stop="remove(node,data)"
              class="button-sty"
              icon="el-icon-delete"
            >
              {{ i18nt("designer.setting.delete") }}
            </el-button>
            </span>
          </span>
      </el-tree>
    </div>
  </container-item-wrapper>
</template>
<script>
import emitter from '../../../../components/xform/utils/emitter'
import i18n from "../../../../components/xform/utils/i18n"
import refMixin from "../../../../components/xform/form-render/refMixin"
import ContainerItemWrapper from './container-item-wrapper'
import containerItemMixin from "./containerItemMixin";

export default {
  name: "TreeItem",
  componentName: "ContainerItem",
  mixins: [emitter, i18n, refMixin, containerItemMixin],
  components: {
    ContainerItemWrapper
  },
  inject: [
    "refList",
    "sfRefList",
    "globalModel",
    "getFormConfig",
    "getGlobalDsv",
  ],
  data() {
    return {
      isExpanded: !0,
      isChecked: !1,
      currentKey: "",
      filterText: "",
      loadingFlag: !1,
      defaultProps: {
        children: "children",
        label: "label",
        disabled: this.isDisabled,
        isLeaf: 'leaf'
      },
      showTree:true
    };
  },
  computed: {
    formConfig() {
      return this.getFormConfig();
    },
  },
  watch: {
    filterText(o) {
      if(!this.widget.options.disLocalFilter){
          this.$refs.tree.filter(o);
      }
    },
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    subFormRowIndex: {type: Number, default: -1},
    subFormColIndex: {type: Number, default: -1},
    subFormRowId: {type: String, default: ""},
  },
  created() {
    this.initRefList(), this.handleOnCreated();
    if (this.widget.options.lazy) {
      this.widget.options.treeData = [];
    }
  },
  mounted() {
    /*this.widget.options.dsEnabled && this.loadDataFromDS({}),*/
    this.$nextTick(() => {
      this.handleOnMounted();
    });
  },
  beforeDestroy() {
    this.unregisterFromRefList();
  },
  methods: {
    isDisabled() {
      return this.widget.options.disabled;
    },
    append(o) {
      this.$prompt(
        this.i18nt("designer.setting.inputNodeName"),
        this.i18nt("designer.setting.tips"),
        {
          confirmButtonText: this.i18nt(
            "designer.hint.confirm"
          ),
          cancelButtonText: this.i18nt(
            "designer.hint.cancel"
          ),
        }
      )
        .then(({value: e}) => {
          let id = new Date().getTime()
          const n = {id: id, label: e, children: []};
          o.children || (o.children = []), o.children.push(n);
        })
        .catch((e) => {
          console.error(e);
        });
    },
    remove(o, e) {
      this.$confirm(
        this.i18nt("designer.setting.deleteNode"),
        this.i18nt("designer.setting.tips"),
        {
          confirmButtonText: this.i18nt(
            "designer.hint.confirm"
          ),
          cancelButtonText: this.i18nt(
            "designer.hint.cancel"
          ),
          type: "warning",
        }
      )
        .then(() => {
          const n = o.parent,
            l = n.data.children || n.data,
            s = l.findIndex((c) => c.id === e.id);
          l.splice(s, 1),
            this.$root.$message({
              type: "success",
              message: this.i18nt(
                "designer.setting.nodeDeleted"
              ),
            });
        })
        .catch((n) => {
          console.error(n);
        });
    },
    filterNode(o, e) {
      return o ? e.label.indexOf(o) !== -1 : !0;
    },
    handleOnCreated() {
      this.widget.options.onCreated &&
      new Function(this.widget.options.onCreated).call(this);
    },
    handleOnMounted() {
      this.widget.options.onMounted &&
      new Function(this.widget.options.onMounted).call(this);
    },
    handleTreeNodeClick(o, e, n) {
      this.widget.options.onNodeClick &&
      new Function(
        "data",
        "node",
        "el",
        this.widget.options.onNodeClick
      ).call(this, o, e, n);
    },
    handleTreeNodeContextmenu(o, e, n, l) {
      this.widget.options.onNodeContextmenu &&
      new Function(
        "event",
        "data",
        "node",
        "el",
        this.widget.options.onNodeContextmenu
      ).call(this, o, e, n, l);
    },
    handleTreeNodeCheck(o, e) {
      this.widget.options.onNodeCheck &&
      new Function(
        "data",
        "treeState",
        this.widget.options.onNodeCheck
      ).call(this, o, e);
    },
    handleCheckChange(o, e, n) {
      this.widget.options.onCheckChange &&
      new Function(
        "data",
        "checked",
        "indeterminate",
        this.widget.options.onCheckChange
      ).call(this, o, e, n);
    },
    setNodeExpanded(o, e) {
      o.expanded = e;
      for (let n = 0; n < o.childNodes.length; n++)
        (o.childNodes[n].expanded = e),
        o.childNodes[n].childNodes.length > 0 &&
        this.setNodeExpanded(o.childNodes[n], e);
    },
    setNodeChecked(o, e) {
      o.checked = e;
      for (let n = 0; n < o.childNodes.length; n++)
        (o.childNodes[n].checked = e),
        o.childNodes[n].childNodes.length > 0 &&
        this.setNodeChecked(o.childNodes[n], e);
    },
    getNativeTree() {
      return this.$refs.tree;
    },
    setTreeData(o) {
      (this.widget.options.treeData = o),
      o && o.length > 0 && (this.currentKey = o[0].id);
    },
    getTreeData() {
      return this.widget.options.treeData;
    },
    expandAllNodes(o) {
      (this.isExpanded = o || !this.isExpanded),
        this.setNodeExpanded(
          this.$refs.tree.store.root,
          this.isExpanded
        );
    },
    checkAllNodes(o) {
      (this.isChecked = o || !this.isChecked),
        this.setNodeChecked(
          this.$refs.tree.store.root,
          this.isChecked
        );
    },
    setCheckedNodes(o) {
      this.$refs.tree.setCheckedNodes(o);
    },
    getCheckedNodes(o, e) {
      return this.$refs.tree.getCheckedNodes(o, e);
    },
    getCurrentNode() {
      return this.$refs.tree.getCurrentNode();
    },
    setCurrentNode(o) {
      return this.$refs.tree.setCurrentNode(o);
    },
    setCurrentKey(o) {
      return this.$refs.tree.setCurrentKey(o);
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      if (this.widget.options.onLoadNode) {
        let loopDo = () => {
          if (!this.$el) {
            this.$nextTick(() => {
              loopDo();
            });
            return
          }
          new Function(
            "data",
            "node",
            "resolve",
            this.widget.options.onLoadNode
          ).call(this, node.data, node, resolve);
        }
        loopDo();
      }
    },
    handleClickButton(){
      this.handleCustomEvent(this.widget.options.onFilterIconClick,["keyword"],[this.filterText])
    },
    handleFilterTextChange(val){
      this.handleCustomEvent(this.widget.options.onFilterTextChange,["keyword"],[val])
    },
    reflushTree(){
      this.showTree = false;
      this.$nextTick(()=>{
        this.showTree = true;
      })
    }
    /*loadDataFromDS(o = {}, e = "") {
      let n = e || this.widget.options.dsName,
        l = this.widget.options.dataSetName,
        s = getDSByName(this.formConfig, n);
      if (s) {
        let c = this.getGlobalDsv() || {},
          u = new Object({});
        overwriteObj(u, c),
          overwriteObj(u, o),
          (u.widgetName = this.widget.options.name),
          (this.loadingFlag = !0),
          runDataSourceRequest(
            s,
            u,
            this.getFormRef(),
            !1,
            this.$message
          )
            .then(($) => {
              !!l && $.hasOwnProperty(l)
                ? this.setTreeData($[l])
                : this.setTreeData($),
                (this.loadingFlag = !1);
            })
            .catch(($) => {
              this.$message.error($.message),
                (this.loadingFlag = !1);
            });
      }
    },*/
  },
}
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
