<template>
  <ElRadioGroup v-model="colorType" size="small" style="width: 100%" v-if="gradient">
    <ElRadioButton value="pure">单色</ElRadioButton>
    <ElRadioButton value="gradient">渐变色</ElRadioButton>
  </ElRadioGroup>
  <template v-if="colorType === 'pure'">
    <div class="color-box" :style="{marginTop: gradient ? '12px' : '0'}">
      <ElColorPicker v-model="color" color-format="hex" show-alpha size="small"/>
      <ElInput v-model="color" size="small"></ElInput>
    </div>
  </template>
  <template v-else-if="colorType === 'gradient'">
    <div class="gradient-box" :style="{ background: color }">
      <ElColorPicker v-model="gradientColor[0]" color-format="hex" show-alpha size="small"/>
      <ElColorPicker v-model="gradientColor[1]" color-format="hex" show-alpha size="small"/>
    </div>
  </template>
</template>

<script setup lang="ts">
import { ElRadioGroup, ElRadioButton, ElColorPicker, ElInput, } from 'element-plus';
import { defineEmits, defineProps, ref, watch, withDefaults } from 'vue';

const emit = defineEmits(["update:value"]);
const props = withDefaults(defineProps<{
  value: string;
  // 展示渐变色
  gradient?: boolean;
}>(), { gradient: true});
const colorType = ref(props.value?.length <= 9 || !props.value ? 'pure' : 'gradient');
const color = ref(props.value);
// 'linear-gradient(90deg,#9CEC5BFF,#0764F0FF)'
const gradientColor = ref(props.value?.length >= 9 ? props.value.slice(22).replace(')', '').split(',') : ['#4ba9ff', '#fff']);

watch(
  () => [colorType.value, color.value, gradientColor.value],
  () => {
    if (colorType.value === 'pure') {
      color.value = color.value.length > 9 ? '#FFFFFFFF' : color.value;
    } else {
      color.value = `linear-gradient(90deg, ${gradientColor.value.join(',')})`
    }
    emit('update:value', color.value);
  },
  {
    deep: true
  }
);

watch(
  () => props.gradient,
  (val) => {
    if(!val) {
      colorType.value = 'pure';
      color.value = color.value.length > 9 ? '#FFFFFFFF' : color.value;
    }
  }
)
</script>

<style lang="less" scoped>
.color-box {
  display: flex;
  align-items: center;
  :deep(.el-color-picker) {
    margin-right: 8px;
  }
}
.gradient-box {
  padding: 2px;
  margin-top: 12px;
  border: solid 1px #eee;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>