<template>
	<div>
		<el-select v-bind="$attrs" ref="selectRef"
			v-model="selectValue"
			:value-key="valueField"
		>
			<template #empty>
				<div :style="{ width: tableWidth + 'px', padding: '2px' }">
					<el-input
						v-model="keyword"
						placeholder="关键词查找"
						@keyup.enter="handleQuery"
					></el-input>
					<div style="height: 2px"></div>
					<scTable
						ref="table"
						:apiObj="apiObj"
						:params="params"
						:query="query"
						:height="tableHeight"
						row-key="id"
						stripe
						@row-click="rowClick"
						:hidePagination="hidePagination"
						paginationLayout="prev, pager, next"
						hideDo
						@dataChange="tdChange"
						@selection-change="
							(selection) => {
								selections = selection;
							}
						"
					>
						<el-table-column
							v-if="multiple"
							type="selection"
							width="40"
							:reserve-selection="true"
						></el-table-column>
						<slot></slot>
					</scTable>
				</div>
			</template>
		</el-select>
	</div>
</template>

<script setup>
import { ref, defineProps, defineEmits, computed } from "vue";

const props = defineProps({
	multiple: { type: Boolean, default: false },
	edit: { type: Boolean, default: true },
	hidePagination: { type: Boolean, default: false },
	tableWidth: { type: Number, default: 600 },
	tableHeight: { type: Number, default: 400 },
	apiObj: { type: Object, default: () => {}, required: true },
	params: { type: Object, default: () => {} },
	label: { type: String, default: "" },
	obj: { type: Object, default: () => {} },
	modelValue: { type: String, default: null },
	labelField: { type: String, default: "name" },
	valueField: { type: String, default: "id" },
});

const emit = defineEmits(["update:modelValue", "update:label", "rowSelect"]);

// 控制 popover 显示与隐藏的状态
const showPopover = ref(false);
const table = ref();
const selectRef = ref();

const selectObj = computed({
	get() {
		return props.obj;
	},
	set(val) {
		emit("update:obj", val);
	},
});

const selectLabel = computed({
	get() {
		return props.label;
	},
	set(val) {
		emit("update:label", val);
	},
});
const selectValue = computed({
	get() {
		return props.modelValue;
	},
	set(val) {
		emit("update:modelValue", val);
	},
});

const keyword = ref("");
const query = ref({ search: "" });

const handleQuery = () => {
	query.value.search = keyword.value;
	table.value.queryData(query.value);
};

const rowClick = (row) => {
	selectObj.value = row;
	selectLabel.value = row[props.labelField];
	selectValue.value = row[props.valueField];
	initOptions();
	showPopover.value = false;
};

const handleClear = () => {
	selectObj.value = {};
	selectLabel.value = "";
	selectValue.value = null;
};

const initOptions = () => {
    console.log(selectRef.value)
}

const tdChange = (res, tableData) => {};
</script>
