<script setup lang="ts">
import { Field as vanField, Picker as vanPicker, Popup as vanPopup } from 'vant'
import { computed, ref, watch } from 'vue'

interface Props {
  modelValue?: string | number | Date
  label?: string
  placeholder?: string
  title?: string
  format?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  label: '选择时间',
  placeholder: '请选择时间',
  title: '选择完整时间',
  format: 'YYYY-MM-DD HH:mm:ss',
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
  'confirm': [value: string]
}>()

const showPicker = ref(false)
const columns = ref<any[]>([])
const selectedValues = ref<string[]>([])

const displayValue = computed(() => {
  if (props.modelValue) {
    const date = new Date(props.modelValue)
    return formatDate(date, props.format)
  }
  return ''
})

watch(() => showPicker.value, (val) => {
  if (val) {
    columns.value = []
    selectedValues.value = []
    getColumns()
  }
}, { immediate: true })

function formatDate(date: Date, format: string): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', String(year))
    .replace('YY', String(year).slice(-2))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

function getColumns() {
  const strtime = props.modelValue ? String(props.modelValue) : ''

  let dateValues: Date
  if (strtime) {
    const date = new Date(strtime.replace(/-/g, '/'))
    dateValues = date
  }
  else {
    dateValues = new Date()
  }

  const Y = dateValues.getFullYear()
  const M = dateValues.getMonth()
  const D = dateValues.getDate()
  const h = dateValues.getHours()
  const m = dateValues.getMinutes()
  const s = dateValues.getSeconds()

  // 生成年份列 (前后10年)
  const year: any[] = []
  const currentYear = new Date().getFullYear()
  for (let i = currentYear - 10; i < currentYear + 10; i++) {
    year.push({ text: i.toString(), value: i.toString() })
  }

  // 生成月份列 (01-12)
  const month: any[] = []
  for (let i = 1; i <= 12; i++) {
    const monthStr = i.toString().padStart(2, '0')
    month.push({ text: monthStr, value: monthStr })
  }

  // 生成日期列 (01-31，根据当前年月动态计算)
  const daysInMonth = getCountDays(Y, M + 1)
  const day: any[] = []
  for (let i = 1; i <= daysInMonth; i++) {
    const dayStr = i.toString().padStart(2, '0')
    day.push({ text: dayStr, value: dayStr })
  }

  // 生成小时列 (00-23)
  const hour: any[] = []
  for (let i = 0; i < 24; i++) {
    const hourStr = i.toString().padStart(2, '0')
    hour.push({ text: hourStr, value: hourStr })
  }

  // 生成分钟列 (00-59)
  const minute: any[] = []
  for (let i = 0; i < 60; i++) {
    const minuteStr = i.toString().padStart(2, '0')
    minute.push({ text: minuteStr, value: minuteStr })
  }

  // 生成秒钟列 (00-59)
  const second: any[] = []
  for (let i = 0; i < 60; i++) {
    const secondStr = i.toString().padStart(2, '0')
    second.push({ text: secondStr, value: secondStr })
  }

  columns.value = [year, month, day, hour, minute, second]

  // 设置默认选中值
  const _M = (M + 1).toString().padStart(2, '0')
  const _D = D.toString().padStart(2, '0')
  const _h = h.toString().padStart(2, '0')
  const _m = m.toString().padStart(2, '0')
  const _s = s.toString().padStart(2, '0')

  selectedValues.value = [Y.toString(), _M, _D, _h, _m, _s]
}

function getCountDays(year: number, month: number): number {
  const day = new Date(year, month, 0)
  return day.getDate()
}

function onChange() {
  // 当年月发生变化时，重新计算日期列
  if (selectedValues.value.length >= 2) {
    const year = Number.parseInt(selectedValues.value[0])
    const month = Number.parseInt(selectedValues.value[1])
    const currentDay = Number.parseInt(selectedValues.value[2])

    const daysInMonth = getCountDays(year, month)

    // 重新生成日期列
    const dayColumn: any[] = []
    for (let i = 1; i <= daysInMonth; i++) {
      const dayStr = i.toString().padStart(2, '0')
      dayColumn.push({ text: dayStr, value: dayStr })
    }

    // 如果当前选中的日期超过了新月份的最大天数，调整为最大天数
    if (currentDay > daysInMonth) {
      selectedValues.value[2] = daysInMonth.toString().padStart(2, '0')
    }

    // 更新列
    columns.value[2] = dayColumn
  }
}

function onCancel() {
  showPicker.value = false
}

function onConfirm() {
  const endval = `${selectedValues.value[0]}-${selectedValues.value[1]}-${selectedValues.value[2]} ${selectedValues.value[3]}:${selectedValues.value[4]}:${selectedValues.value[5]}`

  emit('update:modelValue', endval)
  emit('confirm', endval)
  showPicker.value = false
}
</script>

<template>
  <div>
    <van-field
      v-model="displayValue"
      :label="label"
      :placeholder="placeholder"
      readonly
      is-link
      @click="showPicker = true"
    />

    <van-popup v-model:show="showPicker" position="bottom" round @close="onCancel">
      <van-picker
        v-model="selectedValues"
        :title="title"
        :columns="columns"
        @change="onChange"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<style scoped>
/* 可以根据需要添加自定义样式 */
</style>
