<template>
	<div class="app-container">
		<!-- 搜索区域 -->
		<el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="80px">
			<el-form-item label="模型名称" prop="useCase">
				<el-input v-model="queryParams.useCase" placeholder="请输入名称" clearable style="width: 240px"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery" :loading="loading">查询</el-button>
				<el-button icon="Refresh" @click="resetQuery" :loading="loading">重置</el-button>
			</el-form-item>
		</el-form>

		<!--loading-->
		<div v-if="loading" v-loading="loading" class="loading-page" element-loading-text="正在加载..."
			style="width: 100%; height: calc(100vh - 250px)"></div>
		<div v-else-if="pageList.length && !loading">
			<!-- 表格数据 -->
			<el-table v-loading="loading" :data="pageList">
				<el-table-column label="模型名称" prop="useCase" />
				<el-table-column label="模型类型" prop="modelType" />
				<el-table-column label="模型" prop="modelName" />
				<el-table-column label="API密钥" prop="apiKey" :show-overflow-tooltip="true" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-tooltip content="编辑" placement="top">
							<el-button link type="primary" icon="Edit"
								@click="openDialog('edit', scope.row)">编辑</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页区域 -->
			<pagination :show="total > 0" :total="total" v-model:page="queryParams.pageNum"
				v-model:limit="queryParams.pageSize" @pagination="getList" />
		</div>
		<lz-page-empty v-else-if="!loading" :type="'2'">
			<lz-svg-icon icon-class="empty2" style="font-size: 312px;" />
		</lz-page-empty>


		<!-- 修改对话框 -->
		<el-dialog :title="dialogTitle" v-model="dialogOpen" width="980px" append-to-body :close-on-click-modal="false"
			@close="cancel">
			<el-form :model="dialogForm" :rules="dialogRules" ref="configModelsRef" label-width="80px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="模型名称" prop="useCase">
							<el-input v-model="dialogForm.useCase" disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="模型" prop="modelId">
							<el-select v-model="dialogForm.modelId" placeholder="请选择模型" @change="handleModelChange">
								<el-option v-for="item in modelsOptions" :key="item.id" :label="item.modelName" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="API密钥" prop="apiKey">
							<el-input v-model="dialogForm.apiKey" type="textarea" placeholder="请输入API密钥"
								rows="4"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="提示词" prop="modelPrompt">
							<MdEditorPreview v-model="dialogForm.modelPrompt" />
							<!-- <el-input v-model="dialogForm.modelPrompt" type="textarea" placeholder="请输入内容"
								:rows="12"></el-input> -->
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="configModels">
import { modelList, modelConfigList, modelConfigUpdate } from "@/api/tc/model"
import MdEditorPreview from "@/components/Markdown/MdEditorPreview"
import { ref } from "vue"

const { proxy } = getCurrentInstance()


const pageList = ref([])
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const modelsOptions = ref([])

/** 配置模型表单引用 */
const configModelsRef = ref(null)
const dialogOpen = ref(false)
const dialogTitle = ref('新增')
const dialogForm = ref({
	useCase: '',
	modelId: '',
	modelName: '',
	modelPrompt: '',
	apiKey: '',
})
const dialogRules = ref({
	modelId: [{ required: true, message: '请选择模型', trigger: ['change'] }],
	modelPrompt: [{ required: true, message: '请输入提示词', trigger: ['blur'] }],
	apiKey: [{ required: true, message: '请输入API密钥', trigger: ['blur'] }],
})

const data = reactive({
	form: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		useCase: undefined,
	},
	rules: {},
})

const { queryParams } = toRefs(data)

/** 查询模型列表 */
function getModelList() {
	modelList().then(res => {
		modelsOptions.value = res.rows
	})
}

/** 模型选择 */
function handleModelChange() {
	dialogForm.value.modelName = modelsOptions.value.find(item => item.id === dialogForm.value.modelId)?.modelName || ''
}

/** 提交表单 */
function submitForm() {
	// 验证表单
	configModelsRef.value.validate((valid) => {
		if (valid) {
			const data = { ...dialogForm.value }; // 获取表单数据
			console.log(data);
			const params = {
				id: data.id,
				modelId: data.modelId,
				modelName: data.modelName,
				modelPrompt: data.modelPrompt,
				apiKey: data.apiKey,
			}
			
			// 调用更新接口
			modelConfigUpdate(params).then(response => {
				proxy.$message.success(response.msg);
				getList(); // 更新列表
			}).finally(() => {
				dialogOpen.value = false; // 关闭对话框
				reset()
			});
		} else {
			console.log('表单验证失败');
		}
	});
}

/** 取消按钮 */
function cancel() {
	dialogOpen.value = false
	reset()
}

/** 重置操作表单 */
function reset() {
	dialogForm.value = {
		useCase: '',
		modelId: '',
		modelName: '',
		modelPrompt: '',
		apiKey: '',
	}
	proxy.resetForm("configModelsRef")
}

/** 打开新增/编辑弹窗 */
function openDialog(type = 'add', row = {}) {
	if (type === 'add') {
		dialogTitle.value = '新增'
	} else if (type === 'edit') {
		dialogTitle.value = '编辑'
		dialogForm.value = JSON.parse(JSON.stringify(row))
	}
	dialogOpen.value = true
}
/** 查询列表 */
function getList() {
	loading.value = true
	const data = { ...queryParams.value }
	modelConfigList(data).then(response => {
		const res = response.rows;
		pageList.value = res
		total.value = response.total
	}).finally(() => {
		loading.value = false
	})
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1
	getList()
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm("queryRef")
	handleQuery()
}

onMounted(() => {
	// 模型列表
	getModelList()
	// 列表查询
	getList()
})
</script>