<template>
  <div class="rule-box">
    <div class="rule-input">
      <span v-if="hasColor">{{ data.value }}</span>
      <Icon
        icon="ant-design:close-circle-outlined"
        color="#bfbfbf"
        v-if="hasColor"
        @click="close"
      />
    </div>
    <div class="rule-color" style="background-color: transparent">
      <input type="color" :value="data.value" @change="debounceValue" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, reactive, computed } from 'vue';
  import Icon from '/@/components/Icon/index';
  import { debounce } from 'lodash-es';
  const props = withDefaults(
    defineProps<{
      value: string;
    }>(),
    {
      value: '',
    },
  );
  const data = reactive({ defaultValue: '#ffffff', value: '' });
  const emits = defineEmits(['update:value', 'change']);
  function close() {
    data.value = data.defaultValue;
    emits('update:value', '');
    emits('change', '');
  }
  const hasColor = computed(() => {
    return props.value ? true : false;
  });
  const debounceValue = debounce(changeValue, 1000, {
    leading: true, // 延长开始后调用
    trailing: false, // 延长结束前调用
  });
  onMounted(() => {
    if (!props.value) {
      data.value = data.defaultValue;
    } else {
      data.value = props.value;
    }
  });
  onUnmounted(() => {
    debounceValue.cancel();
  });
  function changeValue(e) {
    data.value = e.target.value;
    emits('update:value', e.target.value);
    emits('change', data.value);
  }
</script>

<style lang="less" scoped>
  .rule-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 30px;
  }

  .rule-input {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 30px;
    padding: 0 4px;
    padding-left: 10px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
  }

  input[type='color'] {
    width: 32px;
    height: 32px;
    background: #f8f8f8;
    border-radius: 4px;
    border: 1px solid #ddd;
    margin-left: 10px;
    padding: 1px 3px;
  }

  input[type='color']::-webkit-color-swatch {
    // border: 0;
    border-color: #bfbfbf;
  }
</style>
