<script setup>
import Header from './views/layout/pc/header/index.vue'
import Footer from './views/layout/pc/footer/index.vue'
import {onMounted, ref, watch} from 'vue'
import {visit} from '@/api/index'
import axios from 'axios'

const referrer = ref(document.referrer || '')
const ipUrl = ref('')

const CACHE_KEY = 'ip'
const TIME_KEY = 'ipFetchTime'
const CACHE_MIN = 60 * 60 * 1000 // 1h

async function getUrl() {
  const now = Date.now()
  const cachedIp = sessionStorage.getItem(CACHE_KEY)
  const cachedTime = sessionStorage.getItem(TIME_KEY)

  if (cachedIp && cachedTime && now - Number(cachedTime) < CACHE_MIN) {
    ipUrl.value = cachedIp
    return cachedIp
  }

  try {
    const {data} = await axios.get('https://api64.ipify.org?format=json')
    ipUrl.value = data.ip
    sessionStorage.setItem(CACHE_KEY, data.ip)
    sessionStorage.setItem(TIME_KEY, now.toString())
    postVisit()
  } catch (e) {
    console.error('获取 IP 失败:', e)
  }
}

function postVisit() {
  const params = {
    timestamp: new Date(),
    url: window.location.href,
    referrer: referrer.value,
    real_ip: ipUrl.value,
  }

  visit(params).then((res) => {})
}

onMounted(async () => {
  await getUrl()
})
</script>

<template>
  <div id="app">
    <Header id="header" />
    <router-view id="main" v-slot="{Component, title}">
      <keep-alive include="New">
        <component :is="Component" />
      </keep-alive>
    </router-view>
    <Footer id="footer" />
  </div>
</template>

<style lang="scss" scoped>
#app {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  #header {
    width: 100%;
    height: $header_nav_height;
    position: fixed;
    z-index: 99;
  }
  #main {
    margin-top: $header_nav_height;
    width: 100%;
    flex: 1;
    background-color: $white;
  }
  #footer {
    width: 100%;
    height: 380px;
  }
}
</style>
