import { ref } from 'vue'

const access_token = ref(null)
const consumerId = ref(null)
const data = ref(null)

// 计数器
let consumeMessageCount = 0

const getAccessToken = async () => {
  try {
    const response = await fetch('/api/oauth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        grant_type: 'client_credentials',
        client_id: '88651e249e734a5290b00345961a7458',
        client_secret: 'fbd457384ba0423cb5d6b86e4c7d3afc'
      })
    })
    if (!response.ok) throw new Error('Network response was not ok')
    const result = await response.json()
    console.log("access_token:>>>>>>>>>", result)
    access_token.value = result.access_token
  } catch (error) {
    console.error('Error fetching access token:', error)
  }
}

const createConsumer = async () => {
  try {
    const token = access_token.value
    if (!token) throw new Error('Access token not found')

    const response = await fetch('/api/api/v1/mq/consumer/group1', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${token}`
      }
    })
    if (!response.ok) throw new Error('Network response was not ok')
    const result = await response.json()
    console.log("createConsumer:>>>>>>>>>", result.data)
    consumerId.value = result.data.consumerId
  } catch (error) {
    console.error('Error creating consumer:', error)
  }
}

const consumeMessage = async () => {
  try {
    const token = access_token.value
    const cid = consumerId.value

    if (!token || !cid) throw new Error('Token or Consumer ID not found')

    const response = await fetch('/api/api/v1/mq/consumer/messages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${token}`
      },
      body: new URLSearchParams({
        autoCommit: 'true',
        consumerId: cid
      })
    })
    if (!response.ok) throw new Error('Network response was not ok')
    const result = await response.json()

    // 解析 content 数据
    const parsedData = result.data.map(item => {
      const content = JSON.parse(item.content.replace(/\\/g, '')) // 去除反斜杠
      return {
        ...item,
        content
      }
    })

    data.value = parsedData
    console.log("consumeMessage:>>>>>>>>>", parsedData)

    consumeMessageCount++
    console.log(`consumeMessage request count: ${consumeMessageCount}`)

    return parsedData
  } catch (error) {
    console.error('Error consuming message:', error)
    return []
  }
}

// 定时器管理
let refreshTokenIntervalId = null
let consumeMessageIntervalId = null

const startAutoRefresh = () => {
  // 1小时刷新一次 getAccessToken 和 createConsumer
  refreshTokenIntervalId = setInterval(async () => {
    await getAccessToken()
    await createConsumer()
  }, 3600000) // 3600000ms = 1小时

  // 每25秒触发一次 consumeMessage
  consumeMessageIntervalId = setInterval(async () => {
    await consumeMessage()
  }, 25000) // 25000ms = 25秒
}

const stopAutoRefresh = () => {
  if (refreshTokenIntervalId) clearInterval(refreshTokenIntervalId)
  if (consumeMessageIntervalId) clearInterval(consumeMessageIntervalId)
}

export {
  access_token,
  consumerId,
  data,
  getAccessToken,
  createConsumer,
  consumeMessage,
  startAutoRefresh,
  stopAutoRefresh
}
