<template>
	<view class="bs-autoInput">
		<input type="text" :disabled="disabled" :placeholder="placeholder" v-model="inputValue" @focus='onFocus'
			@input='onChange' />
		<scroll-view :class="['auto-options', {'flex_center': !searchData.length}]" scroll-y v-show="visible">
			<view class="option-item flex_sb" v-for="(item,index) in searchData" :key="index" @click="onSelect(item)">
				<text class="options-label">{{item.label}}</text>
				<text class="options-value">{{item.value}}</text>
			</view>
			<u-empty mode="data" textSize='32' iconSize="160" text="暂无数据" v-if="!searchData.length" />
		</scroll-view>
	</view>
</template>

<script>
	import Request from '@/api/request.js'
	import { getOptionEnum } from '@/api/apiList.js'
	export default {
		name: "bs-autoInput",
		options: { styleIsolation: 'shared' },
		props: {
			placeholder: {
				type: String,
				default: '' //默认提示
			},
			disabled: {
				type: Boolean,
				default: false //是否禁用
			},
			name: {
				type: String,
				default: 'label' //是否禁用
			},
			autoApi: {
				type: String,
				default: '' //数据API
			},
		},
		data() {
			return {
				inputValue: '', //输入值
				showSelect: '', //当前选中的值
				visible: false, //是否显示下拉框
				sourceData: [], //源数据
				searchData: [], // 搜索数据
			};
		},
		methods: {
			onVisible() {
				this.visible = !this.visible
			},

			async onFocus() {
				const api = this.autoApi
				if (api) {
					const res = await Request(api) //详细参数参考Request请求
					const datas = res.data.data.datas
					this.sourceData = datas
					this.searchData = datas
					this.onVisible()
				}
			},

			onChange(e) {
				const value = e.detail.value
				let newData = []
				if (value) {
					newData = this.searchData.filter(item => item.label.includes(value))
				} else {
					newData = this.sourceData
				}
				this.searchData = [...newData]
			},

			onSelect(data) {
				const value = data[this.name]
				this.inputValue = value
				this.$emit('onSearch', value)
				this.onVisible()
			}
		}
	}
</script>

<style lang="scss">
	.bs-autoInput {
		position: relative;

		/deep/.uni-input-input {
			width: 99%;
			border-right: 2rpx solid #797979;
		}

		/deep/.uni-input-placeholder {
			font-size: 28rpx;
			color: rgb(192, 196, 204);
		}

		.auto-options {
			width: 100%;
			max-height: 400rpx;
			min-height: 400rpx;
			padding: 10rpx;
			position: absolute;
			top: 80rpx;
			z-index: 999;
			background-color: #FFFFFF;
			border-radius: 6px;
			border: 2prx solid #ebeef5;
			box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, .1);

			&::after {
				content: '';
				position: absolute;
				top: -20rpx;
				left: 10%;
				width: 0;
				height: 0;
				border: 16rpx solid #FFFFFF;
				border-top-width: 0;
				border-bottom-color: #DFE2E5;
			}


			.option-item {
				padding: 20rpx;
				border-bottom: 1rpx solid #DFE2E5;

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}
</style>
