<template>
  <div class="color-bar-picker">
    <Dropdown trigger="click" @on-click="selectItem">
      <div class="bar-select">
        <div class="bar-preview">
          <ColorBar :colors="currentColors"/>
        </div>
      </div>
      <template #list>
        <DropdownMenu>
          <DropdownItem :name="index" v-for="(values, index) in colorOptions" :key="index">
            <div class="bar-item">
              <ColorBar :colors="values"/>
            </div>
          </DropdownItem>
        </DropdownMenu>
      </template>
    </Dropdown>
    <div class="color-edit" v-if="editable">
      <div class="edit-item" v-for="(color, index) in currentColors" :key="index">
        <ThColorPicker alpha transfer v-model="currentColors[index]" @on-change="triggerChange" style="width: calc(100% - 30px);"/>
        <a class="delete-icon" href="javascript:void(0)" title="删除" @click="deleteColor(index)">
          <Icon type="ios-trash" size="20" color="#F3483A"/>
        </a>
      </div>
      <div class="addbtn-box">
        <Button
          type="primary"
          icon="md-add"
          style="width: 100%; color: #ffffff"
          @click="addColor"
          >添加</Button
        >
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import ColorBar from './ColorBar.vue'
import recommendedColors from './recommended'
export default {
  components: {
    ColorBar
  },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    colorOptions: {
      type: Array,
      default: recommendedColors
    },
    editable: {
      type: Boolean,
      default: true
    }
  },
  emits: ['on-change', 'update:modelValue'],
  methods: {
    selectItem(index) {
      this.currentColors = _.cloneDeep(this.colorOptions[index])
      this.triggerChange()
    },
    deleteColor(index) {
      this.currentColors.splice(index, 1)
      this.triggerChange()
    },
    addColor() {
      this.currentColors.push('#ffffff')
      this.triggerChange()
    },
    triggerChange() {
      this.$emit('update:modelValue', this.currentColors)
      this.$emit('on-change', this.currentColors)
    }
  },
  mounted() {
    this.currentColors = _.cloneDeep(this.modelValue)
  },
  data() {
    return {
      currentColors: []
    }
  },
  watch: {
    colors() {
      this.currentColors = _.cloneDeep(this.modelValue)
    }
  }
}
</script>