<template>
	<el-dialog v-model="visible" title="选择模型" width="1000px" :close-on-click-modal="false" @close="handleClose">
		<div class="model-selector-header">
			<div class="search-bar">
				<el-input v-model="searchParams.keyword" placeholder="搜索模型名称" clearable @clear="handleSearch">
					<template #prefix><el-icon><Search /></el-icon></template>
				</el-input>
				<el-button type="primary" @click="handleSearch">搜索</el-button>
			</div>
			<el-button type="success" @click="handleAddModel">+ 新建模型</el-button>
		</div>

		<div class="model-list" v-loading="loading">
			<el-empty v-if="!loading && modelList.length === 0" description="暂无模型数据" :image-size="100" />
			<div v-else class="model-grid">
				<div
					v-for="model in modelList"
					:key="model.id"
					class="model-card"
					:class="{ selected: selectedModel?.id === model.id }"
					@click="handleSelectModel(model)"
				>
					<div class="model-card-header">
						<div class="model-type">{{ getModelTypeName(model.modelsType) }}</div>
						<el-icon v-if="selectedModel?.id === model.id" class="check-icon" color="#67c23a"><CircleCheck /></el-icon>
					</div>
					<div class="model-card-body">
						<h3 class="model-name">{{ model.modelName }}</h3>
						<p class="model-url">{{ model.baseUrl }}</p>
						<div class="model-status">
							<el-tag :type="model.enabled === 1 ? 'success' : 'info'" size="small">
								{{ model.enabled === 1 ? '已启用' : '已禁用' }}
							</el-tag>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div v-if="pagination.total > 0" class="pagination-wrap">
			<el-pagination
				v-model:current-page="pagination.pageNum"
				v-model:page-size="pagination.pageSize"
				:total="pagination.total"
				:page-sizes="[10, 20, 50]"
				layout="total, prev, pager, next"
				small
				@current-change="handlePageChange"
			/>
		</div>

		<template #footer>
			<el-button @click="handleClose">取消</el-button>
			<el-button type="primary" @click="handleConfirm" :disabled="!selectedModel">确定</el-button>
		</template>

		<!-- 新建模型弹窗 -->
		<EditModule ref="editModuleRef" @refresh="handleRefresh" />
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { Search, CircleCheck } from '@element-plus/icons-vue';
import { getModelModuleList } from '/@/api/digitalHuman/modelConfig/modelModule';
import EditModule from '/@/views/digitalHuman/modelConfig/modelModule/component/editModule.vue';

interface ModelItem {
	id: string;
	modelName: string;
	modelsType: number;
	baseUrl: string;
	route: string;
	httpMethod: string;
	enabled: number;
	[key: string]: any;
}

interface Props {
	modelValue: boolean;
	defaultModel?: ModelItem | null;
}

interface Emits {
	(e: 'update:modelValue', value: boolean): void;
	(e: 'confirm', model: ModelItem): void;
}

const props = withDefaults(defineProps<Props>(), {
	modelValue: false,
	defaultModel: null,
});

const emit = defineEmits<Emits>();

const visible = ref(false);
const searchParams = reactive({ keyword: '' });
const pagination = reactive({ pageNum: 1, pageSize: 10, total: 0 });
const modelList = ref<ModelItem[]>([]);
const loading = ref(false);
const selectedModel = ref<ModelItem | null>(null);
const editModuleRef = ref();

watch(
	() => props.modelValue,
	(val) => {
		visible.value = val;
		if (val) {
			selectedModel.value = props.defaultModel || null;
			fetchModelList();
		}
	}
);

watch(visible, (val) => {
	if (!val) {
		emit('update:modelValue', false);
	}
});

const getModelTypeName = (type: number) => {
	const typeMap: Record<number, string> = {
		1: '图片模型',
		2: '语音模型',
		3: '推理模型',
	};
	return typeMap[type] || '未知类型';
};

const fetchModelList = async () => {
	loading.value = true;
	try {
		const params = {
			pageNum: pagination.pageNum,
			pageSize: pagination.pageSize,
			keyword: searchParams.keyword || undefined,
		};
		const res = await getModelModuleList(params, { errorMode: 'message' });
		modelList.value = res.data?.list || [];
		pagination.total = res.data?.total || 0;
	} catch (error) {
		modelList.value = [];
		pagination.total = 0;
	} finally {
		loading.value = false;
	}
};

const handleSearch = () => {
	pagination.pageNum = 1;
	fetchModelList();
};

const handlePageChange = () => {
	fetchModelList();
};

const handleSelectModel = (model: ModelItem) => {
	selectedModel.value = model;
};

const handleAddModel = () => {
	editModuleRef.value?.openDialog('add');
};

const handleRefresh = () => {
	fetchModelList();
};

const handleConfirm = () => {
	if (selectedModel.value) {
		emit('confirm', selectedModel.value);
		handleClose();
	}
};

const handleClose = () => {
	visible.value = false;
	selectedModel.value = null;
};
</script>

<style scoped lang="scss">
.model-selector-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
	gap: 12px;
}

.search-bar {
	display: flex;
	gap: 12px;
	flex: 1;
}

.model-list {
	min-height: 300px;
	max-height: 400px;
	overflow-y: auto;
}

.model-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
	gap: 16px;
}

.model-card {
	background: #f8fafc;
	border-radius: 8px;
	padding: 16px;
	cursor: pointer;
	transition: all 0.3s ease;
	border: 2px solid transparent;
}

.model-card:hover {
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	transform: translateY(-2px);
}

.model-card.selected {
	border-color: #67c23a;
	background: #f0f9ff;
}

.model-card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12px;
}

.model-type {
	display: inline-block;
	padding: 2px 8px;
	background: #eff6ff;
	color: #3b82f6;
	border-radius: 4px;
	font-size: 12px;
	font-weight: 600;
}

.check-icon {
	font-size: 20px;
}

.model-card-body {
	flex: 1;
}

.model-name {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
	margin: 0 0 8px 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.model-url {
	font-size: 13px;
	color: #64748b;
	line-height: 1.5;
	margin: 0 0 8px 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.model-status {
	display: flex;
	align-items: center;
	gap: 8px;
}

.pagination-wrap {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
</style>
