<template>
	<el-dialog v-model="dialogVisible" title="优化提示词" width="80%" :close-on-click-modal="false">
		<div class="flex gap-4 h-full">
			<!-- Left Panel: Settings -->
			<div class="w-1/2 border shadow-sm card bg-base-100 border-base-200">
				<div class="p-6 card-body">
					<!-- Header with Settings Icon -->
					<div class="flex items-center mb-4">
						<div class="p-2 mr-2 rounded-full bg-base-200">
							<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" style="color: var(--el-color-primary)" viewBox="0 0 20 20" fill="currentColor">
								<path
									fill-rule="evenodd"
									d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z"
									clip-rule="evenodd"
								/>
							</svg>
						</div>
						<h2 class="text-lg font-medium card-title text-slate-700">优化设置</h2>
					</div>

					<!-- Template Selection Section -->
					<div class="mb-4">
						<div class="flex gap-2 mb-4">
							<el-tooltip :content="SYSTEM_PROMPTS.default" placement="top" :show-after="500" raw-content>
								<button
									class="flex-1 normal-case btn btn-outline"
									:class="{ 'btn-active btn-primary': selectedTemplate === 'default' }"
									@click="selectedTemplate = 'default'"
								>
									默认模板
								</button>
							</el-tooltip>
							<el-tooltip :content="SYSTEM_PROMPTS.concise" placement="top" :show-after="500" raw-content>
								<button
									class="flex-1 normal-case btn btn-outline"
									:class="{ 'btn-active btn-primary': selectedTemplate === 'concise' }"
									@click="selectedTemplate = 'concise'"
								>
									简洁模板
								</button>
							</el-tooltip>
							<el-tooltip :content="SYSTEM_PROMPTS.detailed" placement="top" :show-after="500" raw-content>
								<button
									class="flex-1 normal-case btn btn-outline"
									:class="{ 'btn-active btn-primary': selectedTemplate === 'detailed' }"
									@click="selectedTemplate = 'detailed'"
								>
									扩展模板
								</button>
							</el-tooltip>
						</div>
					</div>

					<!-- Model Selection and Temperature -->
					<div class="grid grid-cols-2 gap-4 mb-4">
						<div>
							<label class="block mb-1 text-sm font-medium text-slate-700">使用模型</label>
							<div class="w-full dropdown">
								<div tabindex="0" role="button" class="justify-between normal-case btn btn-outline btn-block">
									{{ selectedModel }}
									<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
										<path
											fill-rule="evenodd"
											d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
											clip-rule="evenodd"
										/>
									</svg>
								</div>
								<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-full">
									<li v-for="model in aiModels" :key="model.id">
										<a @click="selectedModel = model.modelName">{{ model.name }}</a>
									</li>
								</ul>
							</div>
						</div>
						<div>
							<label class="block mb-1 text-sm font-medium text-slate-700">温度</label>
							<input
								type="range"
								min="0"
								max="1"
								v-model="temperature"
								step="0.1"
								class="w-full range range-xs range-blue"
								style="
									background-image: linear-gradient(
										to right,
										var(--el-color-primary-light-9),
										var(--el-color-primary),
										var(--el-color-primary-dark-2)
									);
								"
							/>
							<div class="flex justify-between mt-1 text-xs text-slate-500">
								<span>低值=稳定内容</span>
								<span>{{ temperature }}</span>
								<span>高值=创新内容</span>
							</div>
						</div>
					</div>

					<!-- Input Prompt Section -->
					<div>
						<div class="flex items-center mb-2">
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 w-5 h-5"
								style="color: var(--el-color-primary)"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
							</svg>
							<h3 class="text-sm font-medium text-slate-700">原始提示词</h3>
						</div>
						<textarea
							v-model="inputPrompt"
							class="w-full text-sm resize-none textarea textarea-bordered focus:outline-none"
							style="height: calc(35vh - 100px)"
							:style="{
								'border-color': 'var(--el-color-primary)',
								'box-shadow': '0 0 0 2px rgba(var(--el-color-primary-rgb), 0.2)',
							}"
							placeholder="在此输入您的原始提示词..."
						></textarea>
					</div>

					<!-- Optimize Button -->
					<div class="mt-4">
						<button
							class="text-white normal-case btn btn-block bg-primary-light-3 border-primary"
							@click="optimizePrompt"
							:disabled="isOptimizing"
							:class="{ 'hover:bg-opacity-90': !isOptimizing }"
						>
							<span v-if="isOptimizing" class="inline-flex items-center">
								<svg class="mr-2 w-4 h-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor">
									<circle cx="12" cy="12" r="10" stroke-width="4" stroke-opacity=".3" />
									<path d="M12 2C6.48 2 2 6.48 2 12" stroke-width="4" />
								</svg>
								优化中...
							</span>
							<span v-else class="inline-flex items-center">
								<svg xmlns="http://www.w3.org/2000/svg" class="mr-1 w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
									<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
								</svg>
								优化提示词
							</span>
						</button>
					</div>
				</div>
			</div>

			<!-- Right Panel: Results -->
			<div class="w-1/2 border shadow-sm card bg-base-100 border-base-200">
				<div class="p-6 card-body">
					<!-- Header with Results Icon -->
					<div class="flex items-center mb-4">
						<div class="p-2 mr-2 rounded-full bg-base-200">
							<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" style="color: var(--el-color-primary)" viewBox="0 0 20 20" fill="currentColor">
								<path
									fill-rule="evenodd"
									d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
									clip-rule="evenodd"
								/>
							</svg>
						</div>
						<h2 class="text-lg font-medium card-title text-slate-700">优化结果</h2>
					</div>

					<!-- Results Display -->
					<div class="overflow-y-auto p-4 rounded-lg border border-base-300 bg-base-50" style="height: calc(60vh - 80px)">
						<p v-if="!optimizedPrompt" class="text-sm text-slate-400">优化后的提示词将显示在这里...</p>
						<md-renderer v-else :source="optimizedPrompt" />
					</div>

					<!-- Action Buttons -->
					<div class="flex gap-3 justify-end mt-4">
						<button class="normal-case btn btn-outline btn-sm" @click="copyResult">
							<svg xmlns="http://www.w3.org/2000/svg" class="mr-1 w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
								<path d="M8 2a1 1 0 000 2h2a1 1 0 100-2H8z" />
								<path
									d="M3 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v6h-4.586l1.293-1.293a1 1 0 00-1.414-1.414l-3 3a1 1 0 000 1.414l3 3a1 1 0 001.414-1.414L10.414 13H15v3a2 2 0 01-2 2H5a2 2 0 01-2-2V5zM15 11h2a1 1 0 110 2h-2v-2z"
								/>
							</svg>
							复制结果
						</button>
					</div>
				</div>
			</div>
		</div>

		<!-- Dialog Footer -->
		<template #footer>
			<div class="flex justify-center items-center w-full">
				<el-button type="primary" class="px-8" :loading="loading" @click="onSubmit">
					{{ loading ? '保存中...' : '保存' }}
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import MdRenderer from '/@/components/MdRenderer/MdRenderer.vue';
import { optimizeAiPrompt, putObj } from '/@/api/knowledge/aiPrompt';
import { list } from '/@/api/knowledge/aiModel';
import { useMessage } from '/@/hooks/message';
import { Local } from '/@/utils/storage';

interface AiModel {
	id: string;
	modelName: string;
	type: string;
	[key: string]: any;
}

const dialogVisible = ref(false);
const inputPrompt = ref('');
const optimizedPrompt = ref('');
const isOptimizing = ref(false);
const loading = ref(false);
const currentId = ref('');

// Define a type for the keys of SYSTEM_PROMPTS
type TemplateKey = keyof typeof SYSTEM_PROMPTS;

const selectedTemplate = ref<TemplateKey>('default');
const selectedModel = ref('');
const aiModels = ref<AiModel[]>([]);
const temperature = ref(0.2);

const SYSTEM_PROMPTS = {
	/** 通用 - 优化核心意图，明确上下文与目标 */
	default: `作为 Prompt 优化专家，请基于以下「用户原始输入」重写，生成一个高质量、目标明确的 Prompt。核心要求：<br><br>1.  **深度理解与提炼**：精准捕捉用户的核心意图与深层需求，去除模糊或冗余表述。<br>2.  **明确任务目标**：清晰定义 AI 需要完成的具体任务。<br>3.  **补充关键上下文**：添加必要的背景信息、假设或约束条件，确保 AI 准确理解任务环境。<br>4.  **定义期望输出**：明确说明期望的输出格式、风格、口吻或结构。<br>5.  **语言精练、逻辑严谨**：使用准确、无歧义的语言，确保逻辑清晰。<br>6.  **保持原始意图**：不得扭曲或添加与用户原意无关的信息。<br><br>直接输出优化后的 Prompt 内容本身，不要包含任何额外的问候、解释、标题或标记（如 "Prompt:"）。<br><br>Important: Output must start immediately with the rewritten prompt content. Do **NOT** add greetings, explanations, titles, or any extra words before or after the prompt.<br><br>Always reponse in 中文。`,
	/** 极简 - 直击核心，高度浓缩 */
	concise: `请将以下「用户原始输入」压缩为一到两句、信息密度极高的 AI Prompt。要求：<br>1.  **直击本质**：仅保留最核心的任务指令和关键约束。<br>2.  **极致精简**：删除所有非必要的描述、解释、示例和情感色彩。<br>3.  **清晰无歧义**：确保浓缩后的指令依然准确、易于理解。<br><br>只输出最终浓缩后的 Prompt 文本，不附加任何解释。`,
	/** 结构化 - 要素完整，逻辑清晰 */
	detailed: `请基于以下「用户原始输入」，进行深度分析和结构化重构，生成一份包含以下核心要素的详细 Prompt：<br>1.  **核心目标 (Core Objective)**：明确指出本次任务最根本的目的。<br>2.  **角色与背景 (Role & Context)**：设定 AI 的角色（如果需要），并提供完成任务所必需的最小背景信息。<br>3.  **关键指令与步骤 (Key Instructions & Steps)**：按逻辑顺序列出具体的执行要求或思考步骤。<br>4.  **输入信息 (Input Data / Information)**：说明需要处理的输入类型或具体内容（如有）。<br>5.  **输出要求 (Output Requirements)**：详细定义期望输出的具体格式、结构、风格、语气、长度限制和评估标准。<br>6.  **约束与偏好 (Constraints & Preferences)**：明确任务的限制条件、禁止项或用户的特殊偏好。<br><br>确保各要素条理清晰、信息完备且相互关联，能指导 AI 精准高效地完成任务。禁止输出任何额外解释或标注，仅返回最终结构化的 Prompt。<br><br>Important: Output must start immediately with the rewritten prompt content (beginning with "核心目标"). Do **NOT** add greetings, explanations, titles, section numbers (like ①, ②), or any extra words before or after the prompt sections. Use Markdown headers (e.g., ## 核心目标) for structure if appropriate for the target AI, otherwise use clear text labels followed by content.<br><br>Always reponse in 中文。`,
};

const emit = defineEmits(['refresh']);

// 获取AI模型列表
async function fetchAiModels() {
	try {
		const { data } = await list({ modelType: ['Chat'] });
		if (data && Array.isArray(data) && data.length > 0) {
			aiModels.value = data;
			selectedModel.value = data[0].name || '';
		}
	} catch (error) {
		useMessage().error('获取模型列表失败');
	}
}

function openDialog(row: any) {
	inputPrompt.value = row.prompt;
	optimizedPrompt.value = '';
	currentId.value = row.id;
	dialogVisible.value = true;
}

async function optimizePrompt() {
	if (!inputPrompt.value.trim()) {
		useMessage().warning('请先输入原始提示词');
		return;
	}

	isOptimizing.value = true;
	try {
		const storedModel = Local.get(`selectedAiModel:Chat`);
		const modelName = storedModel?.value || undefined;
		const { data } = await optimizeAiPrompt({
			systemPrompt: SYSTEM_PROMPTS[selectedTemplate.value as keyof typeof SYSTEM_PROMPTS],
			prompt: inputPrompt.value,
			modelName,
			temperature: temperature.value,
			template: selectedTemplate.value,
			model: selectedModel.value,
		});
		optimizedPrompt.value = data;
	} catch (error) {
		useMessage().error('优化失败，请重试');
	} finally {
		isOptimizing.value = false;
	}
}

function copyResult() {
	if (!optimizedPrompt.value) {
		useMessage().warning('没有可复制的内容');
		return;
	}

	navigator.clipboard
		.writeText(optimizedPrompt.value)
		.then(() => {
			useMessage().success('已复制到剪贴板');
		})
		.catch(() => {
			useMessage().error('复制失败，请手动复制');
		});
}

async function onSubmit() {
	if (!optimizedPrompt.value) {
		useMessage().warning('请先进行优化');
		return;
	}

	loading.value = true;
	try {
		await putObj({
			id: currentId.value,
			prompt: optimizedPrompt.value,
		});
		useMessage().success('更新成功');
		dialogVisible.value = false;
		emit('refresh');
	} catch (error) {
		useMessage().error('更新失败，请重试');
	} finally {
		loading.value = false;
	}
}

onMounted(() => {
	fetchAiModels();
});

defineExpose({
	openDialog,
});
</script>
