<template>
  <a-date-picker
    :class="[style && Object.keys(style).length > 0 ? 'customStyle' : '']"
    :style="{ width: width }"
    :size="size"
    v-model:value="modelValue"
    :placeholder="placeholder"
    :format="format"
    :valueFormat="format"
    :allowClear="allowClear"
    :disabled="disabled"
    :showTime="format === 'YYYY-MM-DD HH:mm:ss'"
    :picker="picker"
    @change="handleChange"
  />
</template>
<script lang="ts" setup>
  import dayjs from 'dayjs';
  import { ref, watch, computed } from 'vue';
  import { getLocalTime } from '/@/api/system/user';

  const props = defineProps({
    value: [dayjs, String, Object],
    size: String,
    placeholder: String,
    format: String,
    allowClear: Boolean,
    disabled: Boolean,
    isGetCurrent: Boolean,
    style: Object,
    width: String,
  });
  const modelValue = ref<string | null>();
  const emit = defineEmits(['update:value', 'change']);

  const picker = computed(() => {
    let time = 'date';
    switch (props.format) {
      case 'YYYY-MM':
        time = 'month';
        break;
      case 'YYYY':
        time = 'year';
        break;
    }
    return time;
  });
  watch(
    () => props.value,
    async (val) => {
      if (!val && props.isGetCurrent) {
        const date = await getLocalTime();
        modelValue.value = dayjs(date).format(props.format);
        handleChange(modelValue.value);
      } else if (val && typeof val !== 'string') {
        modelValue.value = val?.format(props.format);
      } else {
        modelValue.value = val || '';
      }
    },
    {
      immediate: true,
    },
  );

  const handleChange = (time) => {
    emit('update:value', time);
    emit('change', time);

    modelValue.value = null;
  };
  const color = computed(() => {
    return props.style?.color;
  });
  const backgroundcolor = computed(() => {
    return props.style
      ? props.style['background-color'] || (props.disabled ? '#f5f5f5' : '#fff')
      : '#fff';
  });
  const border = computed(() => {
    return props.style?.border || '1px solid #d9d9d9';
  });
  const fontsize = computed(() => {
    return props.style ? props.style['font-size'] : '14px';
  });
  const fontstyle = computed(() => {
    return props.style ? props.style['font-style'] : 'normal';
  });
  const customwidth = computed(() => {
    return props.style?.width;
  });
  const height = computed(() => {
    return props.style?.height || '32px';
  });
  const textalign = computed(() => {
    return props.style ? props.style['text-align'] : 'left';
  });
</script>
<style scoped lang="less">
  .customStyle {
    width: v-bind(customwidth);
    border: v-bind(border) !important;
    background-color: v-bind(backgroundcolor);
    height: v-bind(height);

    :deep(.ant-picker-input > input) {
      color: v-bind(color);
      font-size: v-bind(fontsize);
      font-style: v-bind(fontstyle);
      text-align: v-bind(textalign);
    }
  }
</style>
