<template>
  <a-modal v-model:open="visible" :width="340" centered @ok="onOk">
    <template #title> 颜色选择 </template>

    <ColorPicker
      :color="selectColor"
      alpha-channel="hide"
      default-format="hex"
      @color-change="updateColor"
    />
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { message } from "ant-design-vue";
import { ColorPicker, ColorChangeDetail } from "vue-accessible-color-picker";

import useModal from "@/hooks/useModal";

defineOptions({
  name: "ColorPickerDialog",
});

/* modal */
const { visible, open, close } = useModal();
defineExpose({ open, close });

const props = defineProps<{
  color: string;
}>();
const emit = defineEmits(["confirm"]);

const selectColor = ref("");
function updateColor(eventData: ColorChangeDetail) {
  selectColor.value = eventData.cssColor;
}

function onOk() {
  if (!selectColor.value) {
    message.error("请选择颜色");
    return;
  }
  emit("confirm", selectColor.value);
  close();
}

// init
watch(
  () => visible.value,
  (val) => {
    if (val) {
      selectColor.value = props.color;
    }
  },
  {
    immediate: true,
  }
);
</script>

<style>
@import url("vue-accessible-color-picker/styles");
</style>
