<template>
	<view class="u-picker-data">
		<up-picker
			:show="visible"
			:columns="optionsInner"
			:keyName="labelKey"
			:defaultIndex="defaultIndex"
			@confirm="confirm"
			@cancel="cancel"
			@close="close">
		</up-picker>
	</view>
</template>

<script>
export default {
	name: 'com-appointment-picker-data',
	data() {
		return {
			visible: false,
			current: '',
			defaultIndex: [],
			options: [],
			valueKey: 'id',
			labelKey: 'name',
			_resolver: null,
			_rejecter: null,
		}
	},
	computed: {
		optionsInner() {
			return [this.options];
		}
	},
	methods: {
		// 异步显示选择器，参数与原 props 一致
		show(params = {}) {
			const { options = [], valueKey = 'id', labelKey = 'name', modelValue } = params;
			this.options = Array.isArray(options) ? options : [];
			this.valueKey = valueKey;
			this.labelKey = labelKey;
			this.current = '';
			this.defaultIndex = [];
			if (modelValue !== undefined && modelValue !== null && this.options.length > 0) {
				this.options.forEach((ele, index) => {
					if (ele[this.valueKey] == modelValue) {
						this.current = ele[this.labelKey]
						this.defaultIndex = [index]
					}
				})
			}
			this.visible = true;
			return new Promise((resolve, reject) => {
				this._resolver = resolve;
				this._rejecter = reject;
			})
		},
		cancel() {
			this.visible = false;
			if (this._resolver) this._resolver(undefined);
			this._resolver = null;
			this._rejecter = null;
		},
		close() {
			this.visible = false;
			if (this._resolver) this._resolver(undefined);
			this._resolver = null;
			this._rejecter = null;
		},
		confirm(e) {
			const { columnIndex, value } = e;
			this.visible = false;
			const selected = value && value[0] ? value[0] : undefined;
			this.defaultIndex = columnIndex;
			this.current = selected ? selected[this.labelKey] : '';
			if (this._resolver) this._resolver(selected);
			this._resolver = null;
			this._rejecter = null;
		}
	}
}
</script>

<style lang="scss" scoped>
/* 空样式占位，可按需补充样式 */
</style>
