<template>
  <div class="page-container">
    <div class="content-area" v-loading="isSending">
      <div class="image-generate-container" style="padding: 0 280px;" v-if="!route.query.conversationId">
        <h1 class="title">开始 AI 智能创作之旅</h1>
        <p class="subtitle">在下方输入您想要创作的图片描述，小梦将为您生成独特的服装定制图</p>

        <div class="options-grid">
          <div class="option-card" @click="selectOption('art')">
            <img class="option-icon" src="@/assets/imageGeneraterView/edit.svg" alt="edit" />
            <span>艺术创作</span>
          </div>
          <div class="option-card" @click="selectOption('illustration')">
            <img class="option-icon" src="@/assets/imageGeneraterView/design.svg" alt="design" />
            <span>插画设计</span>
          </div>
          <div class="option-card" @click="selectOption('photo')">
            <img class="option-icon" src="@/assets/imageGeneraterView/picture.svg" alt="picture" />
            <span>照片生成</span>
          </div>
          <div class="option-card" @click="selectOption('creative')">
            <img class="option-icon" src="@/assets/imageGeneraterView/pencil.svg" alt="pencil" />
            <span>创意绘画</span>
          </div>
        </div>

        <div class="example-prompts">
          <p class="example-title">示例提示词：</p>
          <div class="prompt-tags">
            <span class="prompt-tag" @click="handleSuggestionClick('适合礼裙的款式图')">适合礼裙的款式图</span>
            <span class="prompt-tag" @click="handleSuggestionClick('用于童装的猫咪图')">用于童装的猫咪图</span>
            <span class="prompt-tag" @click="handleSuggestionClick('常见的球服设计图')">常见的球服设计图</span>
          </div>
        </div>
      </div>

      <div class="image-generate-container" style="display: initial;" v-else>
        <ImageMessageBubble v-for="(item, index) in imageMessages" :key="index" :imageMessage="item" />
      </div>
    </div>

    <PromptInput @send='handleSuggestionClick' v-model="inp" :isSending v-if="showInp" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted } from 'vue'
import PromptInput from '@/components/imageGenerater/PromptInput.vue'
import { createImage, getImageConversationById } from '@/api/aiImage'
import ImageMessageBubble from '@/components/imageGenerater/ImageMessageBubble.vue'
import { useRoute, useRouter } from 'vue-router'
import useImageConversationStore from '@/stores/imageConversation'
import type { ImageConversationMesg } from '@/types/imageConversation'
import type { ImageMessage } from '@/stores/imageConversation'
const router = useRouter()
const inp = ref('')
const isSending = ref(false)
const imageMessages = ref<ImageMessage[]>([])

const route = useRoute()
const imageConversationStore = useImageConversationStore()
const showInp = computed(() => {
  if (imageConversationStore.isReadyNewConversation || route.query.conversationId) {
    return true
  }
  else {
    return false
  }
})

const loadMesg = async (conversationId: string) => {

  if (route.query.conversationId === '-1') {
    console.time('路由跳转耗费时间')
    await router.replace({ name: 'AiImage', query: { conversationId: conversationId } })
    console.timeEnd('路由跳转耗费时间')
    return
  }
  const res = await getImageConversationById(conversationId)
  imageMessages.value = transformImageMesg(res)
  localStorage.setItem('currentMessages', JSON.stringify(imageMessages.value))
}
const transformImageMesg = (res: ImageConversationMesg[]) => {
  const newImageMessages: Array<ImageMessage> = []

  res.map(outItem => {
    // 保存用户消息
    newImageMessages.push({
      sender: 'user',
      text: outItem.message,
      sentAt: outItem.sentAt
    })

    // 保存图片对话项
    outItem.pictureDialogueItemList.map(innerItem => {
      newImageMessages.push({
        id: innerItem.id,
        sender: 'ai',
        url: innerItem.url,
        sentAt: outItem.sentAt
      })
    })
  })

  // 返回新生成的数组
  return newImageMessages
}
// 初始化时加载历史记录
onMounted(() => {
  const messages = localStorage.getItem('currentMessages')
  if (messages) {
    try {
      const parsed = JSON.parse(messages)
      imageMessages.value = transformImageMesg(parsed)

    } catch (e) {
      console.error('Failed to parse chat history:', e)
    }
  }
})

onUnmounted(() => {
  localStorage.removeItem('currentMessages')
})

/**
 * 监听路由会话ID的变化，获取会话消息
 */
let lastConversationId = null;

watch(() => route.query.conversationId, async (newVal: string) => {
  // 避免重复请求
  if (newVal === lastConversationId) return;
  lastConversationId = newVal ?? null;
  localStorage.removeItem('currentMessages');
  /**
   * 如果会话ID为-1，表示新建会话
   */
  if (newVal === '-1') {
    imageConversationStore.isReadyNewConversation = true;
    imageMessages.value = []
    return;
  }
  // 跳转到首页,展示欢迎内容
  else if (!newVal) {
    imageConversationStore.isReadyNewConversation = false;
    return;
  }
  // 如果会话ID有效，加载已有会话的消息
  else if (newVal) {
    imageConversationStore.isReadyNewConversation = false;
    loadMesg(newVal)

  }
}, { immediate: true });

const selectOption = (type) => {
  console.log('Selected option:', type)
  // TODO: Handle option selection
}



/**
 * 把问题推送到imageMessages列表中
 * @param text 待发送的文本内容
 */
const handleSuggestionClick = async (text: string) => {

  await handleUserMessage(text)
}

// 处理用户消息
const handleUserMessage = async (prompt: string) => {
  isSending.value = true
  inp.value = ''

  try {
    const conversationId = imageConversationStore.isReadyNewConversation ? '' : imageConversationStore.conversationId
    // 发送用户消息到后端
    const res = await createImage({ conversationId, prompt })

    imageConversationStore.conversationId = res.conversationsId
    loadMesg(res.conversationsId)

  } catch (error) {
    console.error('获取AI回复失败:', error)

  } finally {
    isSending.value = false
  }
}



</script>

<style scoped>
.page-container {
  height: calc(100vh - 100px);
  background-color: #fff;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  overflow-y: auto;
}

.content-area {
  flex: 1;
  display: flex;
  justify-content: center;

}

.image-generate-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  padding: 2rem;
}

.title {
  font-size: 2rem;
  margin-bottom: 1rem;
  color: #333;
}

.subtitle {
  font-size: 1rem;
  color: #666;
  text-align: center;
  margin-bottom: 3rem;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  margin-bottom: 3rem;
  width: 100%;
}

.option-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 12px;
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-card:hover {
  background-color: #e8e8e8;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.option-icon {
  width: 32px;
  height: 32px;
  margin-bottom: 0.5rem;
}

.example-prompts {
  text-align: center;
  margin-bottom: 2rem;
}

.example-title {
  margin-bottom: 1rem;
  color: #666;
}

.prompt-tags {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  justify-content: center;
}

.prompt-tag {
  cursor: pointer;
  background-color: #f5f5f5;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.9rem;
  color: #333;
}
</style>