<template>
  <div class="vtk-date-range-picker">
    <v-menu
      v-model="menu"
      :close-on-content-click="false"
      transition="scale-transition"
      offset-y
      min-width="auto"
      eager
    >
      <template #activator="{ props: activatorProps }">
        <v-text-field
          v-bind="{ ...activatorProps, ...textFieldProps }"
          v-model="displayValue"
          :placeholder="placeholder"
          :disabled="disabled"
          readonly
          clearable
          density="compact"
          variant="outlined"
          @click:clear="clearValue"
        >
          <template #prepend-inner>
            <v-icon size="small">mdi-calendar</v-icon>
          </template>
        </v-text-field>
      </template>
      
      <v-card style="width: 650px;">
        <v-card-text class="pa-0">
          <div class="date-picker-container">
            <v-date-picker
              v-model="startDateRange"
              hide-header
              :min="minDate"
              :max="maxDate"
              :show-current="showCurrent"
              @update:model-value="onStartDateChange"
              class="date-picker-item"
            />
            <v-date-picker
              v-model="endDateRange"
              hide-header
              :min="minDate"
              :max="maxDate"
              :show-current="showCurrent"
              @update:model-value="onEndDateChange"
              class="date-picker-item"
            />
          </div>
        </v-card-text>
        
        <v-divider></v-divider>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn text @click="cancel">取消</v-btn>
          <v-btn color="primary" variant="tonal" @click="confirm">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-menu>
  </div>
</template>

<script setup>
import { ref, computed, watch, useAttrs } from 'vue';

// 定义组件名称
defineOptions({
  name: "VtkDatePicker",
  inheritAttrs: false,
});

// 定义props
const props = defineProps({
  // v-model绑定值
  modelValue: {
    type: [Array, String],
    default: () => []
  },
  // 占位符
  placeholder: {
    type: String,
    default: '请选择日期范围'
  },
  // 禁用状态
  disabled: {
    type: Boolean,
    default: false
  },
  // 最小日期
  min: {
    type: String,
    default: undefined
  },
  // 最大日期
  max: {
    type: String,
    default: undefined
  },
  // 是否显示当前日期
  showCurrent: {
    type: [Boolean, String],
    default: true
  },
  // 显示格式
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  // 分隔符
  separator: {
    type: String,
    default: ' 至 '
  }
});

// 定义emit事件
const emit = defineEmits(['update:modelValue', 'change']);

// 获取透传属性
const attrs = useAttrs();

// 菜单显示控制
const menu = ref(false);

// 日期范围值
const dateRange = ref([]);

// 为了横向排列，需要分别管理开始和结束日期选择器的值
const startDateRange = ref(null);
const endDateRange = ref(null);


// 显示值
const displayValue = computed(() => {
  if (!dateRange.value || dateRange.value.length === 0) {
    return '';
  }
  
  if (dateRange.value.length === 1) {
    return formatDate(dateRange.value[0]);
  }
  
  return `${formatDate(dateRange.value[0])}${props.separator}${formatDate(dateRange.value[1])}`;
});

// 文本框属性
const textFieldProps = computed(() => {
  // 排除我们自己使用的属性
  const { 
    modelValue, 
    placeholder, 
    disabled, 
    min, 
    max, 
    showCurrent, 
    format,
    separator,
    ...rest 
  } = attrs;
  
  return rest;
});

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  
  // 如果是字符串直接返回
  if (typeof date === 'string') {
    return date;
  }
  
  // 如果是 Date 对象
  if (date instanceof Date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  return date;
};

// 最小日期
const minDate = computed(() => props.min);

// 最大日期
const maxDate = computed(() => props.max);

// 监听外部modelValue变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (Array.isArray(newValue) && newValue.length > 0) {
      dateRange.value = [...newValue];
      // 同步到单独的日期选择器
      if (newValue[0]) startDateRange.value = newValue[0];
      if (newValue[1]) endDateRange.value = newValue[1];
    } else if (typeof newValue === 'string' && newValue) {
      // 处理字符串形式的日期范围，如 "2023-01-01 至 2023-01-31"
      const dates = newValue.split(props.separator);
      if (dates.length === 2) {
        dateRange.value = [dates[0].trim(), dates[1].trim()];
        startDateRange.value = dates[0].trim();
        endDateRange.value = dates[1].trim();
      } else {
        dateRange.value = [];
        startDateRange.value = null;
        endDateRange.value = null;
      }
    } else {
      dateRange.value = [];
      startDateRange.value = null;
      endDateRange.value = null;
    }
  },
  { immediate: true }
);


// 开始日期变化处理
const onStartDateChange = (value) => {
  // 更新日期范围的第一个值
  if (value) {
    dateRange.value = [value, dateRange.value[1] || null];
  } else {
    // 如果开始日期被清除，清除整个范围或只清除开始日期
    if (dateRange.value.length > 0) {
      dateRange.value = [null, dateRange.value[1] || null];
    }
  }
};

// 结束日期变化处理
const onEndDateChange = (value) => {
  // 更新日期范围的第二个值
  if (value) {
    dateRange.value = [dateRange.value[0] || null, value];
  } else {
    // 如果结束日期被清除，只清除结束日期
    if (dateRange.value.length > 1) {
      dateRange.value = [dateRange.value[0] || null, null];
    }
  }
};

// 清除值
const clearValue = () => {
  dateRange.value = [];
  startDateRange.value = null;
  endDateRange.value = null;
  emit('update:modelValue', []);
  emit('change', []);
  menu.value = false;
};

// 取消
const cancel = () => {
  // 恢复到原始值
  if (Array.isArray(props.modelValue)) {
    dateRange.value = [...props.modelValue];
    if (props.modelValue[0]) startDateRange.value = props.modelValue[0];
    if (props.modelValue[1]) endDateRange.value = props.modelValue[1];
  } else {
    dateRange.value = [];
    startDateRange.value = null;
    endDateRange.value = null;
  }
  menu.value = false;
};

// 确认
const confirm = () => {
  // 确保日期按顺序排列
  let sortedRange = [...dateRange.value].filter(date => date !== null);
  if (sortedRange.length === 2) {
    const date1 = new Date(sortedRange[0]);
    const date2 = new Date(sortedRange[1]);
    if (date1 > date2) {
      sortedRange = [sortedRange[1], sortedRange[0]];
    }
  } else if (sortedRange.length === 1) {
    // 如果只有一个日期，复制为范围
    sortedRange = [sortedRange[0], sortedRange[0]];
  }
  
  emit('update:modelValue', sortedRange);
  emit('change', sortedRange);
  menu.value = false;
};
</script>

<style scoped>
.vtk-date-range-picker {
  width: 100%;
}

.date-picker-container {
  display: flex;
  flex-direction: row;
  gap: 0;
}

.date-picker-item {
  flex: 1;
  max-width: 50%;
}

.date-picker-item:first-child {
  border-right: 1px solid rgba(0, 0, 0, 0.12);
}

:deep(.v-picker) {
  border-radius: 0;
}

:deep(.v-date-picker-month__day--adjacent) {
  opacity: 0.5;
}

:deep(.v-date-picker-title) {
  display: none;
}
</style>