<template>
  <el-dropdown
    trigger="click"
    class="color-select custom-select"
    placement="bottom-start"
    @command="select"
  >
    <div class="select-preview">
      <div class="select-preview-main">
        <div
          class="color-item"
          :style="{ backgroundColor: selected }"
          v-if="selected"
        ></div>
      </div>
      <div class="select-preview-icon">
        <i class="el-icon-arrow-down"></i>
      </div>
    </div>
    <el-dropdown-menu slot="dropdown" class="color-menu">
      <el-dropdown-item command="" v-if="showEmpty">无</el-dropdown-item>
      <el-dropdown-item
        v-for="(option, index) in optionList"
        :key="index"
        :command="option"
      >
        <div class="color-item" :style="{ backgroundColor: option }"></div>
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
const PREDEFINE_OPTIONS = ["#000000", "#666666", "#999999", "#ffffff"];

export default {
  name: "color-select",
  props: {
    value: String,
    predefine: Array,
    showEmpty: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
  },
  created() {
    this.optionList =
      this.predefine && this.predefine.length
        ? this.predefine
        : PREDEFINE_OPTIONS;
  },
  methods: {
    select(option) {
      this.selected = option;
      this.$emit("input", this.selected);
      this.$emit("change", this.selected);
    },
  },
};
</script>
