<template>
  <a-select
    v-model:value="selected"
    :placeholder="placeholder"
    :options="optionList"
    :multiple="false"
    :allow-clear="allowClear"
    :disabled="disabled"
    @change="onChange"
  >
  </a-select>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import useDictOption from "@/hooks/dictOption";

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

const props = withDefaults(
  defineProps<{
    value: boolean | null;
    type?: "BOOLEAN_TYPE" | "BOOLEAN_ENABLE_TYPE";
    placeholder?: string;
    allowClear?: boolean;
    disabled?: boolean;
  }>(),
  {
    placeholder: "请选择",
    type: "BOOLEAN_TYPE",
    allowClear: true,
  }
);
const emit = defineEmits(["update:value", "change"]);

const { optionList } = useDictOption(props.type);

const selected = ref<number | undefined | string>();

const onChange = () => {
  const val =
    selected.value === undefined ? null : Boolean(Number(selected.value));
  emit("update:value", val);
  emit("change", val);
};

watch(
  () => props.value,
  (val) => {
    selected.value = val === null ? undefined : val ? "1" : "0";
  },
  {
    immediate: true,
  }
);
</script>
