<template>
	<div>
		<el-form :inline="true" :model="query" class="mb12" @submit.prevent>
			<el-form-item label="客户编号">
				<el-input v-model="query.custNo" placeholder="输入客户编号" clearable style="width: 180px" />
			</el-form-item>
			<el-form-item label="客户名称">
				<el-input v-model="query.sortName" placeholder="输入客户名称" clearable style="width: 180px" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="doSearch">查询</el-button>
				<el-button @click="reset">重置</el-button>
			</el-form-item>
		</el-form>

		<el-table
			:data="rows"
			v-loading="loading"
			border
			stripe
			style="width: 100%"
			height="420"
			@row-dblclick="onDblClick"
			@sort-change="onSortChange"
		>
			<el-table-column prop="cust" label="客户编号" width="200" sortable="custom" />
			<el-table-column prop="sortName" label="客户名称" min-width="220" show-overflow-tooltip sortable="custom" />
		</el-table>

		<div class="pager">
			<el-pagination
				v-model:current-page="query.page"
				v-model:page-size="query.pageSize"
				:total="total"
				:page-sizes="[10, 20, 50]"
				layout="total, sizes, prev, pager, next"
				@current-change="loadList"
				@size-change="loadList"
			/>
		</div>
	</div>
</template>

<script setup lang="ts" name="aidopBusinessSelectCustomer">
import { onMounted, reactive, ref } from 'vue';
import { fetchCustomerPage, type CustomerRow } from '../api/universalSelector';

const emit = defineEmits<{ (e: 'picked', v: CustomerRow): void }>();

const query = reactive({
	custNo: '',
	sortName: '',
	page: 1,
	pageSize: 10,
	sortField: '',
	sortOrder: '',
});

const loading = ref(false);
const rows = ref<CustomerRow[]>([]);
const total = ref(0);

async function loadList() {
	loading.value = true;
	try {
		const data = await fetchCustomerPage({
			custNo: query.custNo || undefined,
			sortName: query.sortName || undefined,
			page: query.page,
			pageSize: query.pageSize,
			sortField: query.sortField || undefined,
			sortOrder: query.sortOrder || undefined,
		});
		rows.value = data.list || [];
		total.value = data.total || 0;
	} finally {
		loading.value = false;
	}
}

function doSearch() {
	query.page = 1;
	loadList();
}

function reset() {
	query.custNo = '';
	query.sortName = '';
	query.page = 1;
	query.sortField = '';
	query.sortOrder = '';
	loadList();
}

function onSortChange({ prop, order }: { prop: string; order: string | null }) {
	query.sortField = prop || '';
	query.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '';
	loadList();
}

function onDblClick(row: CustomerRow) {
	emit('picked', row);
}

onMounted(loadList);
</script>

<style scoped lang="scss">
.mb12 {
	margin-bottom: 12px;
}
.pager {
	margin-top: 10px;
	display: flex;
	justify-content: flex-end;
}
</style>
