<template>
  <div class="rule-box">
    <div class="rule-input">
      <span v-if="hasColor">{{ props.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="changeValue" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, computed } from 'vue';
  import Icon from '/@/components/Icon/index';
  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;
  });

  onMounted(() => {
    if (!props.value) {
      data.value = data.defaultValue;
    } else {
      data.value = props.value;
    }
  });
  function changeValue(e) {
    data.value = e.target.value;
    emits('update:value', e.target.value);
    emits('change', e.target.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>
