<template>
  <WlPopup
    v-model="visible"
    :style="`height: ${contentHeight}`"
    round
    :teleport="teleport"
    position="bottom"
    @close="onClose"
  >
    <Picker
      ref="pickerRef"
      show-toolbar
      :columns="columns"
      v-model="defaultValue"
      @cancel="onClose"
      @confirm="onConfirm"
      @change="onChange"
    />
  </WlPopup>
</template>

<script lang="ts">
export default {
  name: "WlPicker",
};
</script>

<script setup lang="ts">
import { Picker } from "vant";
import type { TPickerColumn } from "../type";
import { ref, watch, watchEffect } from "vue";
import WlPopup from "@mobileUI/components/WlPopup/src/index.vue";

interface Props {
  columns?: TPickerColumn;
  modelValue?: boolean;
  pickerDefaultValue?: any[];
  teleport?: string;
  contentHeight?: string
}
const props = withDefaults(defineProps<Props>(), {
  columns: () => [],
  modelValue: false,
  pickerDefaultValue: () => [],
  teleport: "body",
  contentHeight: "fit-content"
});

const emit = defineEmits<{
  (e: "onConfirm", val: TPickerColumn, indexs: number[], origin);
  (e: "onChange", val: TPickerColumn, indexs: number[], origin);
  (e: "update:modelValue", val: boolean);
  (e: "onClose");
}>();

const visible = ref(false);
const pickerRef = ref<any>();
const defaultValue = ref([])
const onConfirm = (item) => {
  emit("onConfirm", item.selectedValues, item.selectedIndexes, item);
  onClose();
};

const onClose = () => {
  emit("update:modelValue", false);
  emit("onClose");
};

const onChange = (item) => {
  emit("onChange", item.selectedValues, item.selectedIndexes, item);
};

watchEffect(() => {
  visible.value = props.modelValue;
});

watch(
  () => [props.modelValue, props.pickerDefaultValue],
  () => {
    if (props.modelValue) {
      defaultValue.value = props.pickerDefaultValue;
    }
  },
  {
    immediate: true,
  }
);
</script>
