<!-- text -->
<template>
  <Field
    v-model="fieldValue"
    :label="item.label"
    v-bind="item"
    readonly
    :right-icon="fieldValue && item.clearable ? 'clear' : ''"
    @click-input="showCalendar = true"
    @click-right-icon="onReset"
  >
    <template #extra>
      <WlDateTimePicker
        v-bind="item.dateConfig"
        :defalutTime="currentDate"
        v-model:show="showCalendar"
        @onConfirm="onConfirmSelect"
        :type="DATE_TIME_TYPE[item.property_format] || 'date'"
      />
    </template>
  </Field>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import dayjs from "dayjs";
import WlDateTimePicker from "@mobileUI/components/WlDateTimePicker/src/index.vue";
import { Field } from "vant";

const formatDate = (stamp: any, type: any): string => {
  if (!stamp) return "";
  return dayjs(+stamp).format(type);
};
/* 日期格式映射不同日期选择器组件 */
const DATE_TIME_TYPE: any = {
  YYYY: "year", // 年月选择器
  "YYYY/MM": "year month", // 年月选择器
  "YYYY/MM/DD": "year month day", // 年月日选择器
  "YYYY/MM/DD HH": "year month day hour", // 年月日 时选择器
  "YYYY/MM/DD HH:mm": "year month day hour minute", // 年月日 时:分选择器
  "YYYY/MM/DD HH:mm:ss": "year month day hour minute", // 年月日 时:分:秒 使用 年月日 时:分选择器
};
interface Props {
  value: string | number;
  item: any;
}

const props = withDefaults(defineProps<Props>(), {
  value: "",
  item: () => { },
});

const emit = defineEmits<{
  (e: "update:value", val: string): void;
}>();

const fieldValue = ref("");
const currentDate = ref<any>(new Date());
const showCalendar = ref(false);
const onConfirmSelect = (item: any) => {
  currentDate.value = item.time;
  fieldValue.value = formatDate(
    new Date(item.time).getTime(),
    props.item.property_format || "YYYY-MM-DD"
  );
  emit("update:value", new Date(item.time).getTime() + '');
  showCalendar.value = false;
};
watch(
  () => props.value,
  (val) => {
    if (val) {
      currentDate.value = new Date(val);
      fieldValue.value = formatDate(val, props.item.property_format || "YYYY/MM/DD");
    }
  },
  {
    immediate: true,
  }
);
const onReset = () => {
  currentDate.value = "";
  fieldValue.value = "";
  emit("update:value", "");
};
</script>

<style scoped lang="scss">
.content {
  color: #c1c1c1;
}
</style>
<style lang="scss">
.year {
  .van-picker-column {
    &:nth-child(n + 2) {
      display: none;
    }
  }
}
</style>
