<template>
  <div class="wrap selcetAll">
    <el-tooltip
      v-if="isShow"
      class="item"
      effect="dark"
      :content="labelStr"
      placement="top"
      ref="tooltip"
    >
      <div class="showDev"></div>
    </el-tooltip>

    <div class="select-all">
      <el-select
        multiple
        clearable
        filterable
        collapse-tags
        class="select"
        v-bind="{ ...$attrs, ...$props }"
        v-on:input="(value) => $emit('input', value)"
        @change="onChange"
        ref="select"
      >
        <slot />
      </el-select>
      <el-button @click="selectAll" class="btn" v-bind="{ ...$attrs, ...$props  }">
        全选
      </el-button>
    </div>
  </div>
</template>
<script>
export default {
  name: "select-all",
  data() {
    return {
      isShow: false,
      labelStr: null,
    };
  },
  mounted() {
    this.$nextTick((res) => {
      this.isShow =
        (this.$refs?.select?.disabled || false) && this.labelStr?.length > 0;
    });
  },
  // computed: {
  //   labelStr() {
  //     const { selected } = this.$refs.select;
  //     let labelStr = selected
  //       .map((item) => (item.label ? item.label : item.value))
  //       .join(",");
  //     return labelStr;
  //   },
  // },
  watch: {
    "$attrs.value": {
      immediate: true,
      handler(newVal, oldVal) {
        // 优化页面使用多组件时，tooltip不显示的问题
        this.$nextTick(() => {
          const selected = this.$refs.select?.selected;

          let labelStr = "";
          if (newVal && newVal.length > 0 && selected) {
            labelStr = selected
              .map((item) => (item.label ? item.label : item.value))
              .join(",");
            this.labelStr = labelStr;
            this.isShow =
              (this.$refs?.select?.disabled || false) &&
              this.labelStr?.length > 0;
          } else {
            this.labelStr = "";
            this.isShow =
              (this.$refs?.select?.disabled || false) &&
              this.labelStr?.length > 0;
          }
        });
      },
    },
  },
  methods: {
    selectAll() {
      const { options } = this.$refs.select;
      const values = options
        .filter((item) => !item.disabled && item.value)
        .map((item) => item.value);
      this.$emit("input", values);
      this.$emit("change", values);
    },
    onChange(val) {
      this.$emit("change", val);
    },
  },
};
</script>
<style lang="scss">
.el-tooltip__popper {
  max-width: 300px;
  line-height: 180%;
}
</style>
<style lang="less" scoped>
.wrap {
  position: relative;
}

.select-all {
  display: flex;
  flex-direction: row;
  align-items: center;
  .select {
    flex: 1;
    /deep/ .el-input__inner {
      border-radius: 4px 0 0 4px;
    }
  }
}
.btn {
  width: 50px;
  // padding: 0 10px;
  border-left: none;
  border-radius: 0 4px 4px 0;
  // height: 40px;
}
.item {
  width: 100%;
  position: absolute;
  z-index: 1000;
  // height: 40px;
  .showDev {
    width: 100%;
  }
}
</style>
