<template>
	<view>
		<view class="form-row">
			<text class="form-row__label form-row__label--req">有效期类型</text>
			<picker :range="validLabels" :value="validIndex" @change="onValidType">
				<view class="form-row__picker">
					<text>{{ validLabels[validIndex] || '请选择' }}</text>
				</view>
			</picker>
		</view>
		<view v-if="validType === VALID_RANGE" class="form-row">
			<text class="form-row__label form-row__label--req">开始日期</text>
			<picker mode="date" :value="start" @change="onStart">
				<view class="form-row__picker">
					<text :class="{ 'form-row__placeholder': !start }">{{ start || '请选择' }}</text>
				</view>
			</picker>
		</view>
		<view v-if="validType === VALID_RANGE" class="form-row">
			<text class="form-row__label form-row__label--req">结束日期</text>
			<picker mode="date" :value="end" @change="onEnd">
				<view class="form-row__picker">
					<text :class="{ 'form-row__placeholder': !end }">{{ end || '请选择' }}</text>
				</view>
			</picker>
		</view>
	</view>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { VALID_TYPE_OPTIONS, VALID_RANGE } from '@/utils/entryConstants'

const props = defineProps({
	validType: { type: String, default: '1' },
	start: { type: String, default: '' },
	end: { type: String, default: '' }
})

const emit = defineEmits(['update:validType', 'update:start', 'update:end'])

const validLabels = VALID_TYPE_OPTIONS.map((o) => o.label)
const validIndex = ref(0)

watch(
  () => props.validType,
  (v) => {
    const idx = VALID_TYPE_OPTIONS.findIndex((o) => o.value === v)
    validIndex.value = idx >= 0 ? idx : 0
  },
  { immediate: true }
)

function onValidType(e) {
  const idx = Number(e.detail.value)
  validIndex.value = idx
  emit('update:validType', VALID_TYPE_OPTIONS[idx].value)
}

function onStart(e) {
  emit('update:start', e.detail.value)
}

function onEnd(e) {
  emit('update:end', e.detail.value)
}
</script>

<style lang="scss" scoped>
@import '@/styles/mine.scss';
</style>
