<template>
  <Select v-model:value="backgroundObj.type" style="width: 100%" :options="getOptions" @change="handleChangeColor"/>
  <template v-if="backgroundObj.type === 'color'">
    <div class="color-box">
      <ElColorPicker v-model="backgroundObj.color" color-format="hex" show-alpha size="small"/>
      <ElInput v-model="backgroundObj.color" size="small"></ElInput>
    </div>
  </template>
  <template v-else-if="backgroundObj.type === 'image'">
    <div class="img-preview">
      <div class="img-empty">未选择</div>
      <Image :src="backgroundObj.image" />
      <div class="img-tip">选择素材</div>
    </div>
    <ElRadioGroup v-model="backgroundObj.fillType">
      <ElRadioButton value="cover">填充</ElRadioButton>
      <ElRadioButton value="contain">适应</ElRadioButton>
      <ElRadioButton value="stretch">拉伸</ElRadioButton>
    </ElRadioGroup>
  </template>
</template>

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

interface Prop {
  background: {
    type: "none" | "color" | "image";
    color?: string;
    image?: string;
    fillType?: "cover" | "contain" | "stretch" | "";
  };
  filterOptions?: string[];
}
const props = withDefaults(defineProps<Prop>(), {
  background: () => ({
    type: "none",
    color: "",
    image: "",
    fillType: ""
  })
});

const emit = defineEmits(["update:background"]);

const backgroundObj = ref(props.background);

const options = [
  { label: "无", value: "none" },
  { label: "颜色", value: "color" },
  { label: "图片", value: "image" },
];

const getOptions = computed(() => {
  if(!props.filterOptions) {
    return options;
  }
  return options.filter((item) => !props.filterOptions?.includes(item.value));
});

watch(
  () => backgroundObj.value,
  () => {
    emit("update:background", backgroundObj.value);
  }, {
    deep: true,
    immediate: true
  }
)

const handleChangeColor = (type: any) => {
  if(type === 'color' && !backgroundObj.value.color) {
    backgroundObj.value.color = '#0B074BFF';
  }
};
</script>

<style lang="less" scoped>
.color-box {
  display: flex;
  align-items: center;
  margin: 12px 0;
  margin-bottom: 0;
  :deep(.el-color-picker) {
    margin-right: 8px;
  }
}

.img-preview {
  margin: 12px 0;
  border: solid 1px #eee;
  height: 120px;
  position: relative;
  .img-empty {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #999;
  }
  .img-tip {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba(0, 0, 0, .6);
    color: #fff;
    font-size: 12px;
    opacity: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    &:hover {
      opacity: 1;
    }
  }
}
</style>
