<template>
  <div class="pull-down-menu-in-editor" v-clickoutside="onClickOutside">
    <button class="menu-cover" @click="isExpand = !isExpand">
      {{ placeholder ? placeholder : current.label }}
      <i
        class="iconfont icon-material_preview_upload_collect"
        :class="{ flip: isExpand }"
      ></i>
    </button>
    <div class="menu" v-show="isExpand">
      <button
        v-for="(item, index) of valueList"
        :key="index"
        @click="onSelect(item)"
      >
        {{ item.label }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    valueList: {
      type: Array,
      default: function () {
        return [];
      },
    },
    placeholder: {
      type: String,
      default: "",
    },
    value: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      isExpand: false,
      current: {
        id: "",
        label: "",
      },
    };
  },
  watch: {
    valueList: {
      handler(val) {
        if (val && val.length > 0) {
          if (!this.current.id) {
            this.current = this.valueList[0];
          }
        }
      },
      immediate: true,
    },
    value: {
      handler(val) {
        const changeValue = this.valueList.find((i) => i.id === val);
        if (changeValue) {
          this.current = changeValue;
        }
      },
      immediate: true,
    },
  },

  methods: {
    onClickOutside() {
      if (this.isExpand) {
        this.isExpand = false;
      }
    },
    onSelect(item) {
      console.log(item, "ads");
      this.isExpand = false;
      this.$emit("input", item.id);
    },
  },
};
</script>

<style lang="less" scoped>
button {
  background: #252526;
  border: 1px solid #404040;
  height: 36px;
  color: #fff;
  width: 100%;
}
.pull-down-menu-in-editor {
  width: 140px;
  position: relative;
  min-width: 160px;
  > button.menu-cover {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    cursor: pointer;
    > .icon-material_preview_upload_collect {
      font-size: 11px;
      color: rgba(255, 255, 255, 0.6);
      border-radius: 2px;
      &.flip {
        transform: translateY(-2px) rotate(180deg);
      }
    }
  }
  > .menu {
    position: absolute;
    width: 100%;
    > button {
      display: block;
      border-top: none;
      cursor: pointer;
      text-align: left;
      padding: 0 16px;
    }
  }
}
</style>
