<template>
  <a-date-picker
    style="width: 100%"
    :value="currentValue"
    :id="'form_item_' + formatFieldName(field.name)"
    :disabled="readOnly"
    :clearable="field.clearable"
    :disabled-date="(date) => getDisabledDate(date, field)"
    :placeholder="placeholder"
    :format="dateFormat"
    @change="handleChange"
  />
</template>

<script setup>
import { computed } from "vue";
import { useVModel } from "@/iview/utils/useModel";
import dayjs from "dayjs";

const props = defineProps({
  field: {
    type: Object,
    required: true,
  },
  fieldPrefix: {
    type: String,
    default: "",
  },
  modelValue: {
    type: Object,
    required: true,
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  readOnly: {
    type: Boolean,
    default: false,
  },
  rawFormData: {
    type: Object,
  },
});

const emit = defineEmits(["update:modelValue"]);
const vModel = useVModel(props, "modelValue", emit);

const getDisabledDate = (date, field) => {
  if (!date) return false;

  if (field.minDate && dayjs(field.minDate).isValid()) {
    if (date.isBefore(dayjs(field.minDate), "day")) {
      return true;
    }
  }

  if (field.maxDate && dayjs(field.maxDate).isValid()) {
    if (date.isAfter(dayjs(field.maxDate), "day")) {
      return true;
    }
  }

  return false;
};

const formatFieldName = (name) => {
  if (!props.fieldPrefix) {
    return name;
  }
  return props.fieldPrefix + "-" + name;
};

const dateFormat = computed(() => {
  return props.field.dateFormat || "YYYY-MM-DD";
});

const handleChange = (value) => {
  vModel.value[formatFieldName(props.field.name)] = !!value
    ? value.format(dateFormat.value)
    : undefined;
};

const currentValue = computed(() => {
  let value = vModel.value[formatFieldName(props.field.name)];
  if (value === undefined || value === null) {
    return undefined;
  }
  return dayjs(value, dateFormat.value);
});
</script>
