<template>
  <WlPopup
    v-model="popUpVisible"
    style="height: 300px"
    :headerVisible="false"
    @close="onClose"
    round
  >
    <DatePicker
      v-bind="$attrs"
      v-model="data"
      :title="title"
      type="date"
      @cancel="onClose"
      @confirm="onConfrim"
    />
  </WlPopup>
</template>

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

<script lang="ts" setup>
import { DatePicker } from "vant";
import { watchEffect, ref } from "vue";
import { getVantDateValue } from "@mobileUI/utils";
import { formatMoment } from "@mobileUI/utils/dayjs";
import WlPopup from "@mobileUI/components/WlPopup/src/index.vue";

type Props = {
  modelValue?: boolean;
  dateValue?: string[] | Date;
  format?: string;
  title?: string;
};
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  dateValue: () => [],
  format: "YYYY-MM-DD",
  title: "",
});

const emit = defineEmits<{
  (e: "onConfrim", val: string);
  (e: "update:modelValue", val: boolean);
  (e: "update:dateValue", val: string[]);
}>();

const popUpVisible = ref(false);

const data = ref([]);

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

const onConfrim = (val) => {
  emit("update:modelValue", false);
  let timestamp = val.selectedOptions.map((ele) => ele.value).join("/");
  timestamp = new Date(timestamp).getTime();
  const time = formatMoment(timestamp, props.format);
  emit("onConfrim", time);
};

watchEffect(() => {
  popUpVisible.value = props.modelValue;
});
watchEffect(() => {
  if (props.dateValue instanceof Date) {
    data.value = getVantDateValue(props.dateValue);
  } else {
    data.value = props.dateValue;
  }
});
watchEffect(() => {
  emit("update:dateValue", data.value as string[]);
});
</script>
