<template>
  <div>
    <el-select
      class="CmsSelectTable"
      @change="parentChange"
      @visible-change="visibleChange"
      :placeholder="placeholder"
      :value="value"
      :filterable="true"
      :automatic-dropdown="true"
      :clearable="clearable"
      :filter-method="filterMethod"
      @clear="clearHandle"
    >
      <el-option :value="objs[valueKey]" :label="valueTitle">
        <el-tree
          id="tree-option"
          ref="selectTree"
          :accordion="accordion"
          :data="options"
          :props="props"
          :highlight-current="true"
          :current-node-key="objs[valueKey]"
          @node-click="handleNodeClick"
          :default-checked-keys="defaultExpandedKey"
          :render-after-expand="false"
          :filter-node-method="filterNode"
          :node-key="props.value"
          icon-class="el-icon-caret-right"
          :default-expanded-keys="defaultExpandedKey"
          empty-text="暂无数据"
        >
        </el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import "./_CmsSelectTable.less";

export default {
  props: {
    /* 配置项 */
    props: {
      type: Object,
      default: () => {
        return {
          value: "id", // ID字段名
          label: "name", // 显示名称
          children: "children", // 子级字段名
        };
      },
    },
    valueKey: {
      type: String,
      required: true,
      default: () => {
        return undefined;
      },
    },
    valueName: {
      type: String,
      required: true,
      default: () => {
        return undefined;
      },
    },
    /* 选项列表数据(树形结构的对象数组) */
    dataSource: {
      type: [ Array, String, Function ],
      default: () => {
        return [];
      },
    },
    /* 初始值 */
    value: {
      type: [ Number, String ],
      default: () => {
        return null;
      },
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    /* 自动收起 */
    accordion: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    formModel: {
      type: Object,
      default: () => {
        return {};
      },
    },
    matchKey: {
      type: Object,
      default: () => {
        return {};
      },
    },
    placeholder: {
      type: String,
      default: () => {
        return undefined;
      },
    },
  },
  data() {
    return {
      loading: false,
      valueId: this.formModel[this.valueKey], // 初始值
      valueTitle: "",
      options: [],
      searchValue: undefined,
      defaultExpandedKey: [],
    };
  },
  computed: {
    objs: {
      get() {
        return this.formModel;
      },
      set(val) {
        this.$emit("update:formModel", val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      $(this.$el)
        .find("div.el-select-dropdown")
        .css({
          width: $(this.$el).width() + "px",
        });
    });
    this.initDataSource();
  },
  methods: {
    /**初始化数据源信息*/
    initDataSource() {
      if (typeof this.dataSource === "function") {
        let loading = this.$cmsLoading.open({
          text: this.$t("common.message.loadingMsg"),
        });
        this.dataSource({})
          .then((res) => {
            loading.close();
            let cloneData = JSON.parse(JSON.stringify(res.data));
            // 对源数据深度克隆
            this.options = cloneData.filter((father) => {
              // 循环所有项，并添加children属性
              let branchArr = cloneData.filter((child) => father.id === child.parentId); // 返回每一项的子级数组
              branchArr.length > 0 ? (father.children = branchArr) : ""; // 给父级添加一个children属性，并赋值
              return father.parentId === 0 || father.parentId === undefined; // 返回第一层
            });
            this.$nextTick(() => {
              this.initHandle();
            });
          })
          .catch(() => {
            loading.close();
          });
      } else {
        this.options = this.dataSource;
        let cloneData = JSON.parse(JSON.stringify(this.options));
        // 对源数据深度克隆
        this.options = cloneData.filter((father) => {
          // 循环所有项，并添加children属性
          let branchArr = cloneData.filter((child) => father.id === child.parentId); // 返回每一项的子级数组
          branchArr.length > 0 ? (father.children = branchArr) : ""; // 给父级添加一个children属性，并赋值
          return father.parentId === 0 || father.parentId === undefined; // 返回第一层
        });
        this.initHandle();
      }
    },
    visibleChange(val) {
    },
    /**定义切换事件*/
    parentChange() {
      this.$emit("change", this.formModel[this.valueKey]);
    },
    // 初始化值
    initHandle() {
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll(
          ".el-scrollbar .el-select-dropdown__wrap"
        )[0];
        let scrollBar = document.querySelectorAll(".el-scrollbar .el-scrollbar__bar");
        scrollWrap.style.cssText = "margin: 0px; max-height: none; overflow: hidden;";
        scrollBar.forEach((ele) => (ele.style.width = 0 + "px"));
      });
    },
    // 切换选项
    handleNodeClick(node) {
      for (let key in this.matchKey) {
        this.formModel[key] = node[this.matchKey[key]];
      }
      this.valueTitle = node[this.props.label];
      this.$emit("getValue", this.valueId);
      this.defaultExpandedKey = [];
    },
    // 清除选中
    clearHandle() {
      this.valueTitle = "";
      for (let key in this.matchKey) {
        this.formModel[key] = undefined;
      }
      this.defaultExpandedKey = [];
      this.clearSelected();
      this.$emit("getValue", null);
    },
    /* 清空选中样式 */
    clearSelected() {
      let allNode = document.querySelectorAll("#tree-option .el-tree-node");
      allNode.forEach((element) => element.classList.remove("is-current"));
    },

    filterNode(a) {
      console.log("===========", a);
    },
    filterMethod(val) {
      // this.$refs.selectTree.filter(val);
    },
  },
};
</script>

<style scoped lang="scss">
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}

.el-select-dropdown__item.selected {
  font-weight: normal;
}

ul li > > > .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}

.el-tree-node__label {
  font-weight: normal;
}

.el-tree > > > .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}

.el-tree > > > .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
</style>
