<template>
  <!-- Coze AI 聊天助手容器 -->
  <div id="coze-chat-container"></div>

  <!-- 登录提示弹窗 -->
  <div v-if="showLoginModal" class="modal-overlay" @click="hideLoginModal">
    <div class="modal-content login-prompt-modal" @click.stop>
      <div class="modal-icon">
        <svg class="login-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <circle cx="12" cy="8" r="3" stroke="currentColor" stroke-width="2"/>
          <path d="M12 14c-4 0-7 2-7 4v2h14v-2c0-2-3-4-7-4z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
        </svg>
      </div>
      <h3>需要登录</h3>
      <p>使用AI助手功能需要先登录您的账号</p>
      <div class="modal-actions">
        <button class="btn btn-secondary" @click="hideLoginModal">取消</button>
        <button class="btn btn-primary" @click="goToLogin">立即登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import { userStore } from '../store/user'

export default {
  name: 'CozeChat',
  setup() {
    // 响应式数据
    const cozeWebSDK = ref(null)
    const showLoginModal = ref(false)
    const router = useRouter()

    // 加载Coze Chat SDK
    const loadCozeChatSDK = () => {
      // 检查是否已经存在script标签
      const existingScript = document.querySelector('script[src*="coze"]')
      if (existingScript) {
        console.log('Coze SDK已存在，直接初始化')
        if (window.CozeWebSDK) {
          initCozeChatClient()
        }
        return
      }

      // 创建script标签
      const script = document.createElement('script')
      script.src = import.meta.env.VITE_COZE_SDK_URL
      script.async = true
      script.onload = () => {
        console.log('Coze SDK 加载完成')
        initCozeChatClient()
          .then(() => {
            console.log('Coze客户端初始化成功')
          })
          .catch(error => {
            console.error('Failed to initialize Coze chat client:', error)
          })
      }
      script.onerror = (error) => {
        console.error('加载Coze SDK失败:', error)
      }
      document.body.appendChild(script)
    }

    // 初始化Coze聊天客户端
    const initCozeChatClient = async () => {
      if (!window.CozeWebSDK) {
        console.error('Coze SDK not loaded')
        throw new Error('Coze SDK未加载')
      }
      
      try {
        console.log('Initializing Coze chat client...')
        
        // 获取token
        const tokenData = await fetchCozeToken()
        console.log('Token data received:', tokenData)
        
        if (!tokenData || !tokenData.access_token) {
          console.error('Failed to get valid Coze token')
          throw new Error('无法获取有效的Coze token')
        }
        
        console.log('Creating Coze chat client with token...')
        
        // 检测设备类型
        const isMobile = checkDeviceType()
        console.log('设备类型:', isMobile ? '移动设备' : 'PC设备')
        
        // 保存Coze SDK配置
        const config = {
          config: {
            bot_id: import.meta.env.VITE_COZE_BOT_ID,
          },
          componentProps: {
            title: '精彩猪手',
          },
          auth: {
            type: 'token',
            token: tokenData.access_token,
            onRefreshToken: async () => {
              try {
                console.log('Refreshing token...')
                const refreshedData = await fetchCozeToken()
                if (refreshedData && refreshedData.access_token) {
                  console.log('Token refreshed successfully')
                  return refreshedData.access_token
                } else {
                  throw new Error('Failed to refresh token')
                }
              } catch (error) {
                console.error('Error refreshing token:', error)
                return ''
              }
            }
          },
          userInfo: {
            id: userStore.user?.id?.toString() || 'guest',
            url: import.meta.env.VITE_COZE_AVATAR_URL,
            nickname: userStore.user?.username || '游客',
          },
          ui: {
            base: {
              icon: import.meta.env.VITE_COZE_ICON_URL,
              layout: isMobile ? 'mobile' : 'pc',
              zIndex: 1000,
              lang:'zh-CN'
            },
            asstBtn: {
              isNeed: false, // 不展示默认悬浮球
            },
            footer: {
              isShow: false // 隐藏底部版权信息
            }
          }
        }
        
        // 创建聊天客户端实例
        cozeWebSDK.value = new window.CozeWebSDK.WebChatClient(config)
        console.log('Coze chat client initialized successfully')
        return cozeWebSDK.value
        
      } catch (error) {
        console.error('Error initializing Coze chat:', error)
        throw error
      }
    }

    // 从API获取Coze token
    const fetchCozeToken = async () => {
      try {
        // 确保获取最新的用户信息
        let userId = 'guest'
        if (userStore.isLoggedIn && userStore.user?.id) {
          userId = userStore.user.id
          console.log('使用已登录用户ID:', userId)
        } else if (userStore.isLoggedIn) {
          // 如果用户已登录但没有用户信息，尝试获取
          try {
            await userStore.fetchLoginUser()
            userId = userStore.user?.id || 'guest'
            console.log('重新获取用户信息后的ID:', userId)
          } catch (error) {
            console.warn('获取用户信息失败，使用guest模式:', error)
          }
        }
        
        const jwtExpireSeconds = 3600 // 1小时
        const tokenDurationSeconds = 86400 // 24小时
        
        // 使用环境变量获取API基础URL
        const apiBaseUrl = import.meta.env.VITE_API_BASE_URL
        
        const url = `${apiBaseUrl}/jwt/one-step-token?jwtExpireSeconds=${jwtExpireSeconds}&sessionName=${userId}&tokenDurationSeconds=${tokenDurationSeconds}`
        
        console.log('Fetching Coze token, URL:', url)
        
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        })
        
        if (!response.ok) {
          console.error(`API error: ${response.status}`, await response.text())
          throw new Error(`API error: ${response.status}`)
        }
        
        const data = await response.json()
        console.log('Token API response:', data)
        
        if (!data.success || !data.data) {
          throw new Error('API返回错误: ' + (data.message || '未知错误'))
        }
        
        if (data.data.access_token) {
          console.log('Token received successfully:', data.data.access_token.substring(0, 10) + '...')
          return data.data
        } else if (typeof data.data === 'string') {
          console.log('Token string received:', data.data.substring(0, 10) + '...')
          return { access_token: data.data }
        } else {
          console.error('Invalid token format:', data.data)
          throw new Error('Invalid token format')
        }
      } catch (error) {
        console.error('Error fetching Coze token:', error)
        return null
      }
    }

    // 检查是否为移动设备
    const checkDeviceType = () => {
      const isMobile = window.innerWidth <= 768
      console.log('设备类型检测:', isMobile ? '移动设备' : 'PC设备', '屏幕宽度:', window.innerWidth)
      return isMobile
    }

    // 显示AI助手聊天窗口
    const showAIAssistant = async () => {
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        console.log('用户未登录，提示先登录')
        // 显示登录提示
        showLoginPrompt()
        return
      }

      // 如果用户已登录但Coze SDK未初始化，强制重新初始化
      if (!cozeWebSDK.value) {
        console.log('用户已登录但Coze SDK未初始化，强制重新初始化')
        try {
          await forceReinitializeCozeSDK()
          // 重新初始化后直接显示聊天窗口
          if (cozeWebSDK.value) {
            cozeWebSDK.value.showChatBot()
          }
        } catch (error) {
          console.error('强制重新初始化失败:', error)
        }
        return
      }

      // 如果SDK已初始化，直接显示聊天窗口
      if (cozeWebSDK.value) {
        console.log('显示聊天窗口')
        try {
          cozeWebSDK.value.showChatBot()
        } catch (error) {
          console.error('显示聊天窗口失败:', error)
          // 重新初始化并显示
          await forceReinitializeCozeSDK()
          if (cozeWebSDK.value) {
            cozeWebSDK.value.showChatBot()
          }
        }
      }
    }

    // 显示登录提示
    const showLoginPrompt = () => {
      showLoginModal.value = true
    }

    // 隐藏登录提示
    const hideLoginModal = () => {
      showLoginModal.value = false
    }

    // 跳转到登录页
    const goToLogin = () => {
      hideLoginModal()
      router.push('/login')
    }

    // 强制重新初始化Coze SDK（用于用户登录后）
    const forceReinitializeCozeSDK = async () => {
      try {
        console.log('用户登录状态变化，强制重新初始化Coze SDK')
        
        // 清理现有的Coze实例
        cozeWebSDK.value = null
        
        // 移除已有的script标签
        const existingScripts = document.querySelectorAll('script[src*="coze"]')
        existingScripts.forEach(script => {
          try {
            document.body.removeChild(script)
          } catch (e) {
            console.warn('移除script标签失败:', e)
          }
        })
        
        // 清除window上的CozeWebSDK
        if (window.CozeWebSDK) {
          delete window.CozeWebSDK
        }
        
        // 重新加载并初始化SDK
        await loadCozeChatSDK()
        
        console.log('Coze SDK 重新初始化完成')
      } catch (error) {
        console.error('强制重新初始化Coze SDK失败:', error)
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      // 加载Coze Chat SDK
      loadCozeChatSDK()

      // 监听来自其他组件的AI助手调用事件
      window.addEventListener('showAIAssistant', showAIAssistant)
      
      // 监听来自其他组件的Coze SDK重新初始化事件
      window.addEventListener('reinitializeCozeSDK', forceReinitializeCozeSDK)
    })

    // 监听用户登录状态变化，重新初始化Coze SDK
    watch(() => userStore.isLoggedIn, async (newValue, oldValue) => {
      console.log('用户登录状态变化:', { oldValue, newValue })
      
      // 只有从未登录变为已登录时才重新初始化
      if (!oldValue && newValue) {
        console.log('用户刚刚登录，需要重新初始化Coze SDK')
        // 延迟一下确保用户信息已经更新
        setTimeout(async () => {
          await forceReinitializeCozeSDK()
        }, 1000)
      }
      
      // 如果用户退出登录，清理Coze实例
      if (oldValue && !newValue) {
        console.log('用户退出登录，清理Coze SDK')
        cozeWebSDK.value = null
      }
    })

    // 组件卸载时清理
    onBeforeUnmount(() => {
      // 移除事件监听器
      window.removeEventListener('showAIAssistant', showAIAssistant)
      window.removeEventListener('reinitializeCozeSDK', forceReinitializeCozeSDK)
      // 清理Coze SDK实例
      cozeWebSDK.value = null
    })

    return {
      showLoginModal,
      hideLoginModal,
      goToLogin
    }
  }
}
</script>

<style scoped>
/* Coze AI 聊天助手样式 */
#coze-chat-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 登录提示弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(4px);
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 30px;
  max-width: 380px;
  width: 90%;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

.login-prompt-modal {
  border: 2px solid rgba(255, 107, 53, 0.1);
}

.modal-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 20px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  border-radius: 50%;
  box-shadow: 0 8px 24px rgba(255, 107, 53, 0.3);
}

.login-icon {
  width: 32px;
  height: 32px;
  color: white;
}

.modal-content h3 {
  color: #333;
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 15px;
}

.modal-content p {
  color: #666;
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 25px;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  border: none;
  transition: all 0.3s ease;
  min-width: 100px;
}

.btn-primary {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  box-shadow: 0 4px 15px rgba(255, 107, 53, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 53, 0.4);
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-secondary:hover {
  background: #e9ecef;
  border-color: #ccc;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 移动端适配 */
@media (max-width: 480px) {
  .modal-content {
    padding: 25px 20px;
    margin: 0 15px;
  }
  
  .modal-icon {
    width: 56px;
    height: 56px;
    margin-bottom: 15px;
  }
  
  .login-icon {
    width: 28px;
    height: 28px;
  }
  
  .modal-content h3 {
    font-size: 18px;
  }
  
  .modal-content p {
    font-size: 14px;
  }
  
  .modal-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .btn {
    width: 100%;
    padding: 14px 20px;
  }
}
</style>
