<script setup lang="ts">
import { computed } from 'vue'
import { NTimePicker } from 'naive-ui'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

// Label布局：上下结构(vertical) 或 左右结构(horizontal)
const labelLayout = computed(() => props.df.label_layout || 'vertical')

// Convert "HH:mm:ss" string to timestamp for NTimePicker
function timeStringToTimestamp(timeStr: string): number | null {
  if (!timeStr || typeof timeStr !== 'string') return null
  const parts = timeStr.split(':')
  if (parts.length < 2) return null
  const hours = parseInt(parts[0], 10)
  const minutes = parseInt(parts[1], 10)
  const seconds = parts.length > 2 ? parseInt(parts[2], 10) : 0
  if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) return null
  const date = new Date()
  date.setHours(hours, minutes, seconds, 0)
  return date.getTime()
}

// Convert timestamp to "HH:mm:ss" string for backend storage
function timestampToTimeString(timestamp: number | null): string {
  if (timestamp === null || timestamp === undefined) return ''
  const date = new Date(timestamp)
  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 `${hours}:${minutes}:${seconds}`
}

const timeValue = computed({
  get() {
    const val = props.record[props.df.fieldname]
    if (!val) return null
    if (typeof val === 'number') return val
    return timeStringToTimestamp(val)
  },
  set(newVal: number | null) {
    props.record[props.df.fieldname] = timestampToTimeString(newVal)
  }
})
</script>

<template>
  <div :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <n-time-picker 
      v-model:value="timeValue" 
      placeholder=""
      :disabled="!canEdit"
    />
  </div>
</template>

<style scoped>
.field-wrapper :deep(.n-time-picker) {
  flex: 1;
}
</style>


