<template>
  <Picker 
    v-bind="props"
    :value="value"
    :columns="columns"
    @selectTextChange="() => {}"
    @update:value="updateValue"
  />
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue';
import type { PickerItem, PickerProps } from './Picker.vue';
import Picker from './Picker.vue';
import { DateUtils } from '@imengyu/imengyu-utils';

export interface TimePickerProps extends Omit<PickerProps, 'columns'|'value'> {
  modelValue?: Date,
  showHours?: boolean,
  showSecond?: boolean,
  showMinute?: boolean,
  minuteText?: string,
  secondText?: string,
  hourText?: string,
}

const emit = defineEmits([ 'update:modelValue', 'selectTextChange' ]);
const props = withDefaults(defineProps<TimePickerProps>(), {
  pickerHeight: 300,
  pickerWidth: 750,
  showHours: true,
  showSecond: true,
  showMinute: true,
  minuteText: '分',
  secondText: '秒',
  hourText: '时',
});

const value = computed(() => {
  const value : number[] = [];
  let date = props.modelValue;
  if (!date)
    date = new Date();
  if (!(date instanceof Date))
    date = typeof date === 'string' ? DateUtils.parseDate(date) : new Date();
  if (props.showHours) 
    value.push(date.getHours());
  if (props.showMinute)
    value.push(date.getMinutes());
  if (props.showSecond)
    value.push(date.getSeconds());
  return value;
})

const columns = computed(() => {
  const cols = [] as PickerItem[][];
  if (props.showHours) {
    const hours = [] as PickerItem[];
    cols.push(hours);
    for (let i = 0; i < 24; i++) {
      hours.push({
        text: i.toString() + props.hourText,
        value: i,
      })
    }
  }
  if (props.showMinute) {
    const minutes = [] as PickerItem[];
    cols.push(minutes);
    for (let i = 0; i < 60; i++) {
      minutes.push({
        text: i.toString() + props.minuteText,
        value: i,
      })
    }
  } 
  if (props.showSecond) {
    const seconds = [] as PickerItem[];
    cols.push(seconds);
    for (let i = 0; i < 60; i++) {
      seconds.push({
        text: i.toString() + props.secondText,
        value: i,
      })
    }
  } 
  return cols;
});

function updateValue(v: number[]) {
  if (props.modelValue || v.length > 0) {
    const date = new Date(props.modelValue ?? new Date());
    if (v.length > 0) {
      if (props.showHours)
        date.setHours(v[0]);
      if (props.showMinute)
        date.setMinutes(v[1]);
      if (props.showSecond)
        date.setSeconds(v[2]);
      emit('update:modelValue', date);
    }
    emit('selectTextChange', DateUtils.formatDate(date, 'HH:mm:ss'));
  } else {
    emit('selectTextChange', '');
  }
}
onMounted(() => updateValue([]));

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>
