<template>
	<view class="picker-select">
		<view class="dflex acenter" @click="show = true">
			<text
				class="tips-txt"
				:class="value ? 'value-txt' : 'place-txt'"
			>
				{{ showValue }}
			</text>
			<view
				style="margin-left: 3px"
				v-if="value || value === 0"
				@click.stop="clear"
			>
				<u-icon
					color="#c0c4cc"
					size="18"
					class="arrow-r"
					name="close-circle-fill"
				></u-icon>
			</view>
			<u-icon
				v-else
				color="#c0c4cc"
				size="14"
				class="arrow-r"
				name="arrow-right"
			></u-icon>
		</view>
		<u-datetime-picker
			closeOnClickOverlay
			:show="show"
			:value="value || +new Date()"
			@close="show = false"
			@cancel="show = false"
			@confirm="handleConfirm"
			:mode="mode"
			:formatter="formatter"
		></u-datetime-picker>
	</view>
</template>

<script>
export default {
	name: 'timeSelect',
	model: {
		event: 'change',
		prop: 'value',
	},
	props: {
		mode: String,
		placeholder: {
			default: '请选择',
			type: String,
		},
		value: {
			type: [Number, String, Date],
		},
		columns: {
			default: () => [],
			type: Array,
		},
	},

	data() {
		return {
			show: false,
		};
	},

	computed: {
		showValue() {
			const { value, placeholder } = this;
			return value || value === 0 ? value : placeholder;
		},
	},

	methods: {
		clear() {
			this.$emit('change');
		},
		formatter(type, value) {
			const allTypes = {
				year: '年',
				month: '月',
				day: '日',
				hour: '时',
				minute: '分',
			};

			return `${value}${allTypes[type]}`;
		},
		handleConfirm(e) {
			console.log(e);
			const value = e.value;
			if (this.mode === 'time') {
				this.$emit('change', value);
				this.show = false;
				return;
			}

			const date = uni.$u.timeFormat(value, 'yyyy-mm-dd');
			this.$emit('change', date);
			this.show = false;
		},
	},
};
</script>

<style scoped lang="scss">
.picker-select {
	.arrow-r {
		margin-top: 5rpx;
	}
	.place-txt {
		font-size: 14px;
		color: #c0c4cc;
	}
	.value-txt {
		font-size: 14px;
		color: #333;
	}
}
</style>
