<template>
  <el-select
    :title="multiple ? optionData.name : ''"
    ref="select"
    :value="value"
    placeholder="请选择"
    clearable
    :disabled="disabled"
    :filterable="filterable"
    :filter-method="filterMethod"
    style="width: 100%"
    @clear="clear"
    @visible-change="visibleChange"
  >
    <el-option
      ref="option"
      class="tree-select__option"
      :value="optionData.id"
      :label="optionData.name"
    >
      <el-tree
        ref="tree"
        class="tree-select__tree"
        :class="`tree-select__tree--${multiple ? 'checked' : 'radio'}`"
        :node-key="nodeKey"
        :data="data"
        :props="props"
        :default-expanded-keys="[value]"
        :show-checkbox="multiple"
        :highlight-current="!multiple"
        :expand-on-click-node="multiple"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
        :load="loadNode"
        :lazy="lazy"
      ></el-tree>
    </el-option>
  </el-select>
</template>

<script>
import { getItemList, getAreaList, getCity } from "@/api/goodsManagement/goods";
export default {
  name: "TreeSelect",
  props: {
    // v-model绑定
    value: {
      type: [String, Number],
      default: "",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    // 树形的数据
    data: {
      type: Array,
      default: function () {
        return [];
      },
    },
    // 每个树节点用来作为唯一标识的属性
    nodeKey: {
      type: [String, Number],
      default: "id",
    },
    filterable: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // tree的props配置
    props: {
      type: Object,
      default: function () {
        return {
          label: "label",
          children: "children",
        };
      },
    },
    lazy: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      optionData: {
        id: "",
        name: "",
      },
      filterFlag: false,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (!this.isEmpty(this.data)) {
          this.init(val);
        }
      },
      immediate: true,
    },
    data: function (val) {
      if (!this.isEmpty(val)) {
        this.init(this.value);
      }
    },
  },
  created() {},
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: "region" }]);
      }
      if (node.level > 1) return resolve([]);

      console.log(node, node.data.hasOwnProperty(this.props.children));
      if (node.data.hasOwnProperty(this.props.children)) {
        let data = node.data[this.props.children].map((item) => {
          return {
            ...item,
            projectName: item.accountName,
            projectId: item.accountId,
          };
        });
        resolve(data);
      } else {
        getCity({ province: node.data.id }).then((res) => {
          const data = res.map((item) => {
            return {
              id: item,
              name: item,
            };
          });
          resolve(data);
        });
      }
    },
    // 是否为空
    isEmpty(val) {
      for (let key in val) {
        return false;
      }
      return true;
    },
    handleNodeClick(data, node, leaf) {
      // console.log(data, node, leaf);
      if (this.multiple) {
        return;
      }
      if (node.level == 1) {
        this.$emit("input", data[this.nodeKey]);
      } else {
        var pinData = node.parent.data.name + "-" + data[this.nodeKey];
        this.$emit("input", pinData);
      }

      this.$refs.select.visible = false;
    },
    handleCheckChange(data, node, leaf) {
      console.log(data, node, leaf);
      // const nodes = this.$refs.tree.getCheckedNodes();
      // const value = nodes.map((item) => item[this.nodeKey]).join(",");
      // this.$emit("input", value);

      this.$nextTick(() => {
        const nodes = this.$refs.tree.getCheckedNodes();
        // this.getSimpleCheckedNodes(this.$refs.tree.store);
        console.log(nodes);
        const value = nodes.map((item) => item[this.nodeKey]).join(",");
        console.log(value);
        this.$emit("input", value);
      });
    },
    getSimpleCheckedNodes(store) {
      console.log(store);
      // 定义数组
      const checkedNodes = [];
      // 判断是否为全选，若为全选状态返回被全选的节点，不为全选状态正常返回被选中的节点
      const traverse = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data);
          }
          if (child.indeterminate) {
            traverse(child);
          }
        });
      };
      traverse(store);
      return checkedNodes;
    },

    init(val) {
      console.log(val);
      // 多选
      if (this.multiple) {
        const label = this.props.label || "name";
        const arr = val.toString().split(",");
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr);
          const nodes = this.getSimpleCheckedNodes(this.$refs.tree.store);
          const nodesTwo = this.$refs.tree.getCheckedNodes();
          // this.$refs.tree.getCheckedNodes();
          console.log(nodes, nodesTwo);
          this.optionData.id = val;
          this.optionData.name = nodes.map((item) => item[label]).join();
        });
      }
      // 单选
      else {
        val = val === "" ? null : val;
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(val);
          if (val === null) {
            return;
          }
          const label = this.props.label || "name";
          var node;
          if (val.indexOf("-") > -1) {
            node = this.$refs.tree.getNode(val.split("-")[1]);
          } else {
            node = this.$refs.tree.getNode(val);
          }

          this.optionData.id = val;
          this.optionData[label] = val;
        });
      }
    },
    visibleChange(e) {
      if (e) {
        const tree = this.$refs.tree;
        this.filterFlag && tree.filter("");
        this.filterFlag = false;
        let selectDom = null;
        if (this.multiple) {
          selectDom = tree.$el.querySelector(".el-tree-node.is-checked");
        } else {
          selectDom = tree.$el.querySelector(".is-current");
        }
        setTimeout(() => {
          this.$refs.select.scrollToOption({ $el: selectDom });
        }, 0);
      }
    },
    clear() {
      this.$emit("input", "");
    },
    filterMethod(val) {
      this.filterFlag = true;
      this.$refs.tree.filter(val);
    },
    filterNode(value, data) {
      if (!value) return true;
      const label = this.props.label || "name";
      return data[label].indexOf(value) !== -1;
    },
  },
};
</script>

<style lang="scss">
.tree-select__option {
  &.el-select-dropdown__item {
    height: auto;
    line-height: 1;
    padding: 0;
    background-color: #fff;
  }
}

// .tree-select__tree {
//   &.tree-select__tree--radio {
//     .el-tree-node.is-current > .el-tree-node__content {
//       color: #1890ff;
//       font-weight: 700;
//     }
//   }
// }
</style>
