<template>
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑智能体' : '新增智能体'"
        width="520px"
        :close-on-click-modal="false"
        @close="handleClose"
    >
        <el-form :model="formData" label-width="100px" label-position="top">
            <el-form-item label="智能体图片">
                <FileUpload
                    mode="cover"
                    v-model:coverImg="formData.imageUrl"
                    accept="image/*"
                    :maxSize="5 * 1024 * 1024"
                    class="agent-cover-upload"
                />
            </el-form-item>
            
            <el-form-item label="智能体名称" required>
                <el-input v-model="formData.name" placeholder="请输入智能体名称" />
            </el-form-item>
            
            <el-form-item label="智能体介绍" required>
                <el-input
                    v-model="formData.description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入智能体功能介绍"
                />
            </el-form-item>
            
            <el-form-item label="API链接">
                <el-input v-model="formData.apiUrl" placeholder="请输入API接口地址" />
            </el-form-item>
            
            <el-form-item label="Dify API Key">
                <el-input
                    v-model="formData.difyApiKey"
                    placeholder="请输入Dify智能体API Key"
                    type="password"
                    show-password
                />
            </el-form-item>
            
            <el-form-item label="引导词">
                <el-input
                    v-model="formData.welcomeMessage"
                    type="textarea"
                    :rows="2"
                    placeholder="例如：今天需要我帮你做点什么吗？"
                />
            </el-form-item>
            
            <el-form-item label="提示卡片（最多3个）">
                <div class="suggestions-input">
                    <div
                        v-for="(card, index) in (formData.suggestionCards || [])"
                        :key="index"
                        class="suggestion-card-item"
                    >
                        <!-- 图标上传区域 - 使用 FileUpload cover 模式 -->
                        <FileUpload
                            mode="cover"
                            v-model:coverImg="formData.suggestionCards![index].icon"
                            accept="image/*"
                            :maxSize="2 * 1024 * 1024"
                            class="card-icon-upload"
                        />
                        
                        <!-- 提示词文本输入 -->
                        <el-input
                            v-model="formData.suggestionCards![index].text"
                            :placeholder="`提示词 ${index + 1}`"
                            class="card-text-input"
                        />
                        
                        <!-- 删除按钮 -->
                        <el-button
                            v-if="(formData.suggestionCards?.length || 0) > 1"
                            :icon="Delete"
                            @click="removeSuggestion(index)"
                            class="delete-btn"
                        />
                    </div>
                    
                    <el-button
                        v-if="(formData.suggestionCards?.length || 0) < 3"
                        type="primary"
                        text
                        :icon="Plus"
                        @click="addSuggestion"
                    >
                        添加提示词
                    </el-button>
                </div>
            </el-form-item>
            
            <el-form-item label="分类" required>
                <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
                    <el-option label="内容创作" value="content" />
                    <el-option label="办公助手" value="office" />
                    <el-option label="业务助手" value="business" />
                    <el-option label="城市生命线" value="lifeline" />
                </el-select>
            </el-form-item>
        </el-form>
        
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { Plus, Trash2 as Delete } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'
import FileUpload from 'shared/components/file/FileUpload'

interface SuggestionCard {
    text: string
    icon?: string
}

interface Agent {
    id?: string
    name: string
    description: string
    icon?: string
    imageUrl?: string
    color?: string
    category: string
    usage?: number
    apiUrl?: string
    difyApiKey?: string
    welcomeMessage?: string
    suggestions?: string[]
    suggestionCards?: SuggestionCard[]
}

interface Props {
    modelValue: boolean
    agent?: Agent | null
}

interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'save', data: Partial<Agent>): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.agent)

const formData = ref<Partial<Agent>>({
    name: '',
    description: '',
    category: '',
    imageUrl: '',
    apiUrl: '',
    difyApiKey: '',
    welcomeMessage: '',
    suggestionCards: [{ text: '', icon: '' }]
})

// 监听 agent 变化，填充表单
watch(() => props.agent, (newAgent) => {
    if (newAgent) {
        formData.value = {
            name: newAgent.name,
            description: newAgent.description,
            category: newAgent.category,
            imageUrl: newAgent.imageUrl || '',
            apiUrl: newAgent.apiUrl || '',
            difyApiKey: newAgent.difyApiKey || '',
            welcomeMessage: newAgent.welcomeMessage || '',
            suggestionCards: newAgent.suggestionCards && newAgent.suggestionCards.length > 0 
                ? [...newAgent.suggestionCards] 
                : [{ text: '', icon: '' }]
        }
    } else {
        // 重置表单
        formData.value = {
            name: '',
            description: '',
            category: '',
            imageUrl: '',
            apiUrl: '',
            difyApiKey: '',
            welcomeMessage: '',
            suggestionCards: [{ text: '', icon: '' }]
        }
    }
}, { immediate: true })

const addSuggestion = () => {
    if (formData.value.suggestionCards && formData.value.suggestionCards.length < 3) {
        formData.value.suggestionCards.push({ text: '', icon: '' })
    }
}

const removeSuggestion = (index: number) => {
    if (formData.value.suggestionCards) {
        formData.value.suggestionCards.splice(index, 1)
    }
}

const handleClose = () => {
    dialogVisible.value = false
}

const handleSave = () => {
    // 验证
    if (!formData.value.name?.trim()) {
        ElMessage.warning('请输入智能体名称')
        return
    }
    if (!formData.value.description?.trim()) {
        ElMessage.warning('请输入智能体介绍')
        return
    }
    if (!formData.value.category) {
        ElMessage.warning('请选择分类')
        return
    }
    
    // 过滤空的提示词卡片
    const suggestionCards = formData.value.suggestionCards?.filter(s => s.text.trim()) || []
    
    // 生成随机颜色（如果没有上传图片）
    const colors = ['#0055AA', '#10b981', '#f59e0b', '#3b82f6', '#ef4444', '#6366f1', '#14b8a6']
    const randomColor = colors[Math.floor(Math.random() * colors.length)]
    
    emit('save', {
        ...formData.value,
        color: formData.value.imageUrl ? undefined : randomColor,
        suggestionCards
    })
}
</script>

<style lang="scss" scoped>
@import url('./AgentEdit.scss');
</style>
