<template>
  <div class="agent-chat-view">
    <!-- Header -->
    <header class="chat-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" circle size="small" @click="goBack" />
        <div class="agent-info">
          <span class="agent-name">{{ agentName }}</span>
          <span class="agent-status">在线</span>
        </div>
      </div>
    </header>

    <!-- Chat Content -->
    <div class="chat-content" ref="chatContentRef">
      <!-- Welcome Message -->
      <div v-if="messages.length === 0" class="welcome-section">
        <div class="ai-avatar">
          <span class="avatar-emoji">{{ agentEmoji }}</span>
        </div>
        <h2 class="welcome-title">{{ agentName }}</h2>
        <p class="welcome-text">{{ agentDescription }}</p>
        
        <!-- Quick Actions -->
        <div class="quick-actions">
          <div
            v-for="(action, index) in quickActions"
            :key="index"
            class="action-item"
            @click="handleQuickAction(action)"
          >
            {{ action }}
          </div>
        </div>
      </div>

      <!-- Chat Messages -->
      <div v-else class="messages-container">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message"
          :class="message.role"
        >
          <div class="message-avatar">
            <span v-if="message.role === 'assistant'" class="ai-avatar-small">{{ agentEmoji }}</span>
            <div v-else class="user-avatar-small">👤</div>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
          </div>
        </div>
        
        <!-- Loading indicator -->
        <div v-if="isLoading" class="message assistant">
          <div class="message-avatar">
            <span class="ai-avatar-small">{{ agentEmoji }}</span>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Input Area -->
    <div class="input-area">
      <div class="input-wrapper">
        <textarea
          v-model="inputText"
          :placeholder="inputPlaceholder"
          @keydown.enter.prevent="handleSend"
          rows="1"
        ></textarea>
        <button class="send-btn" @click="handleSend" :disabled="!inputText.trim()">
          <el-icon><Promotion /></el-icon>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Promotion } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const inputText = ref('')
const isLoading = ref(false)
const chatContentRef = ref(null)
const messages = ref([])

const agentId = computed(() => route.query.id || 'default')
const agentName = computed(() => route.query.name || 'AI助手')

const agentConfig = {
  xiaohongshu: {
    emoji: '📕',
    description: '我是小红书文案生成助手，可以帮你创作爆款笔记文案，支持种草、测评、教程等多种风格。',
    placeholder: '描述你想要的文案主题，如：推荐一款平价护肤品...',
    quickActions: ['帮我写一篇美食探店笔记', '生成护肤品种草文案', '写一篇旅行攻略', '创作穿搭分享文案']
  },
  contract: {
    emoji: '📄',
    description: '我是泰豪合同助手，可以帮你审核合同条款、识别风险点、提供修改建议。',
    placeholder: '请粘贴合同内容或描述你的需求...',
    quickActions: ['审核这份合同的风险点', '解读合同关键条款', '生成合同模板', '对比两份合同差异']
  },
  video: {
    emoji: '🎬',
    description: '我是泰豪短视频助手，专注于短视频脚本创作、文案优化和热门话题推荐。',
    placeholder: '告诉我你想创作什么类型的短视频...',
    quickActions: ['写一个产品介绍脚本', '生成热门话题文案', '优化视频标题', '创作口播文案']
  },
  bidding: {
    emoji: '📋',
    description: '我是招标文件助手，可以帮你解读招标文件、生成投标方案、进行合规性检查。',
    placeholder: '请描述你的招标需求或粘贴招标文件内容...',
    quickActions: ['解读招标文件要求', '生成投标技术方案', '检查投标文件合规性', '分析竞争对手情况']
  },
  service: {
    emoji: '⚡',
    description: '我是泰豪小电智能客服，可以帮您解答电力相关问题、查询用电信息、办理业务咨询。',
    placeholder: '请描述您的用电问题或业务需求...',
    quickActions: ['查询本月用电量', '咨询电费账单', '报修故障', '了解优惠政策']
  },
  default: {
    emoji: '🤖',
    description: '我是您的AI智能助手，有什么可以帮助您的？',
    placeholder: '请输入您的问题...',
    quickActions: ['介绍一下你的功能', '帮我写一段文案', '回答一个问题', '帮我分析数据']
  }
}

const currentConfig = computed(() => agentConfig[agentId.value] || agentConfig.default)
const agentEmoji = computed(() => currentConfig.value.emoji)
const agentDescription = computed(() => currentConfig.value.description)
const inputPlaceholder = computed(() => currentConfig.value.placeholder)
const quickActions = computed(() => currentConfig.value.quickActions)

const goBack = () => {
  router.push('/apps')
}

const scrollToBottom = async () => {
  await nextTick()
  if (chatContentRef.value) {
    chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
  }
}

const handleQuickAction = (action) => {
  inputText.value = action
  handleSend()
}

const generateResponse = (input) => {
  const responses = {
    xiaohongshu: `好的，我来帮你生成一篇小红书文案！\n\n📝 **${input}**\n\n---\n\n姐妹们！今天必须给你们安利这个宝藏好物！✨\n\n用了一周真的爱不释手～效果绝绝子！\n\n💫 亮点：\n• 性价比超高\n• 效果立竿见影\n• 回购无限次\n\n🏷️ #好物分享 #真实测评 #平价好物 #必入清单\n\n---\n\n这篇文案你觉得怎么样？需要我调整风格或者添加更多内容吗？`,
    contract: `我已经分析了您的需求，以下是我的建议：\n\n📋 **合同审核要点**\n\n1. **主体资格** - 需确认双方签约主体的合法性\n2. **权利义务** - 条款表述需更加明确\n3. **违约责任** - 建议增加违约金上限条款\n4. **争议解决** - 建议约定明确的管辖法院\n\n⚠️ **风险提示**\n• 付款条件需细化\n• 交付标准需量化\n• 保密条款期限建议延长\n\n需要我针对某个条款详细解读吗？`,
    video: `好的！我来为您创作短视频脚本：\n\n🎬 **${input}**\n\n---\n\n**【开场 0-3秒】**\n钩子：一句话抓住注意力\n\n**【正文 3-50秒】**\n• 痛点引入\n• 解决方案\n• 效果展示\n\n**【结尾 50-60秒】**\n引导互动 + 关注提示\n\n---\n\n🔥 推荐话题：\n#热门挑战 #干货分享 #涨知识\n\n需要我把脚本内容写得更详细吗？`,
    bidding: `收到您的招标需求："${input}"\n\n📋 **招标文件分析**\n\n我已为您解读关键要点：\n\n**1. 资质要求**\n• 企业资质等级要求\n• 业绩证明材料\n• 人员配置要求\n\n**2. 技术要求**\n• 技术方案要点\n• 实施计划安排\n• 质量保证措施\n\n**3. 商务要求**\n• 报价构成说明\n• 付款方式条款\n• 履约保证金\n\n⚠️ **注意事项**\n• 投标截止时间\n• 必须响应的条款\n• 否决性条款\n\n需要我帮您生成投标技术方案吗？`,
    service: `您好！感谢使用泰豪小电智能客服 ⚡\n\n关于您的问题："${input}"\n\n📊 **查询结果**\n\n我已为您查询到相关信息：\n\n**用电账户信息**\n• 户号：3201****8856\n• 用户类型：居民用电\n• 电价：0.52元/度\n\n**本月用电情况**\n• 当前读数：2856度\n• 本月用电：186度\n• 预计电费：96.72元\n\n💡 **温馨提示**\n• 您可以通过微信公众号缴费\n• 峰谷电价可节省约15%电费\n• 如有故障可拨打24小时热线\n\n还有其他问题需要帮助吗？`,
    default: `收到您的问题："${input}"\n\n我来为您详细解答：\n\n这是一个很好的问题！根据我的分析...\n\n如果您还有其他问题，随时可以问我！`
  }
  
  return responses[agentId.value] || responses.default
}

const handleSend = async () => {
  const text = inputText.value.trim()
  if (!text || isLoading.value) return

  messages.value.push({
    id: Date.now().toString(),
    content: text,
    role: 'user'
  })
  inputText.value = ''
  
  await scrollToBottom()
  isLoading.value = true
  
  // Simulate API delay
  setTimeout(async () => {
    messages.value.push({
      id: Date.now().toString() + '_ai',
      content: generateResponse(text),
      role: 'assistant'
    })
    isLoading.value = false
    await scrollToBottom()
  }, 1000)
}
</script>

<style lang="scss" scoped>
.agent-chat-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
}

.chat-header {
  padding: 12px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .agent-info {
      display: flex;
      flex-direction: column;
      
      .agent-name {
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
      }
      
      .agent-status {
        font-size: 12px;
        color: #10b981;
      }
    }
  }
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 40px 80px;
}

.welcome-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  
  .ai-avatar {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    
    .avatar-emoji {
      font-size: 40px;
    }
  }
  
  .welcome-title {
    font-size: 22px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 12px;
  }
  
  .welcome-text {
    color: #6b7280;
    font-size: 14px;
    text-align: center;
    max-width: 500px;
    margin-bottom: 32px;
    line-height: 1.6;
  }
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  max-width: 600px;
  
  .action-item {
    padding: 10px 20px;
    background: #f3f4f6;
    border: 1px solid #e5e7eb;
    border-radius: 20px;
    font-size: 14px;
    color: #374151;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: #7c3aed;
      border-color: #7c3aed;
      color: #fff;
    }
  }
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  
  .message {
    display: flex;
    gap: 12px;
    
    &.user {
      flex-direction: row-reverse;
      
      .message-content .message-text {
        background: #7c3aed;
        color: #fff;
      }
    }
    
    .message-avatar {
      flex-shrink: 0;
      
      .ai-avatar-small {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
      }
      
      .user-avatar-small {
        width: 40px;
        height: 40px;
        background: #e5e7eb;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
      }
    }
    
    .message-content {
      max-width: 70%;
      
      .message-text {
        padding: 14px 18px;
        background: #f3f4f6;
        border-radius: 16px;
        color: #1f2937;
        line-height: 1.7;
        white-space: pre-wrap;
      }
    }
  }
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 16px;
  background: #f3f4f6;
  border-radius: 16px;
  
  span {
    width: 8px;
    height: 8px;
    background: #9ca3af;
    border-radius: 50%;
    animation: typing 1.4s infinite ease-in-out both;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-area {
  padding: 20px 80px 30px;
  background: #fff;
  
  .input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    background: #f9fafb;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 12px 16px;
    
    textarea {
      flex: 1;
      border: none;
      background: transparent;
      resize: none;
      outline: none;
      font-size: 14px;
      color: #1f2937;
      min-height: 24px;
      max-height: 120px;
      
      &::placeholder {
        color: #9ca3af;
      }
    }
    
    .send-btn {
      width: 40px;
      height: 40px;
      background: #7c3aed;
      border: none;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover:not(:disabled) {
        background: #5b21b6;
      }
      
      &:disabled {
        background: #d1d5db;
        cursor: not-allowed;
      }
    }
  }
}
</style>
