<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import WebApp from '@twa-dev/sdk'
import { updateOnlineTime } from '@/service/index/foo'
import i18n from '@/locale'

// 记录开始时间
const startTime = ref<number>(0)
// 累计在线时长(秒)
const totalOnlineTime = ref<number>(0)
// 是否正在计时
const isTracking = ref<boolean>(false)

// 开始计时
const startTracking = () => {
  if (!isTracking.value) {
    startTime.value = Date.now()
    isTracking.value = true
    console.log('开始计时:', new Date(startTime.value).toLocaleString())
  }
}

// 停止计时并计算时长
const stopTracking = async () => {
  if (isTracking.value) {
    const endTime = Date.now()
    const duration = Math.floor((endTime - startTime.value) / 1000) // 转换为秒
    totalOnlineTime.value += duration
    isTracking.value = false

    console.log('本次在线时长:', duration, '秒')
    console.log('总计在线时长:', totalOnlineTime.value, '秒')

    // 添加上报逻辑
    await updateOnlineTime(totalOnlineTime.value)
  }
}

onLaunch(() => {
  uni.hideTabBar()
  console.log('App Launch,111')
  console.info('🚀 ~ file:App method: line:42 -----', WebApp.platform)
})

onShow(() => {
  const lang = uni.getStorageSync('lang')
  if (lang) {
    uni.setLocale(lang)
    i18n.global.locale = lang
  }
  console.log('App Show')
  startTracking()
})

onHide(() => {
  console.log('App Hide')
  stopTracking()
})

onMounted(() => {
  WebApp.ready()
  WebApp.setHeaderColor('#ffffff')
  startTracking()

  // 只保留最基本的关闭监听
  WebApp.onEvent('viewportChanged', () => {
    if (!WebApp.isExpanded) {
      stopTracking()
    }
  })
})

onUnmounted(() => {
  stopTracking()
})
</script>

<style lang="scss">
/* stylelint-disable selector-type-no-unknown */
button::after {
  border: none;
}

swiper,
scroll-view {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

image {
  width: 100%;
  height: 100%;
  vertical-align: middle;
}

// 单行省略，优先使用 unocss: text-ellipsis
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 两行省略
.ellipsis-2 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

// 三行省略
.ellipsis-3 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

// 全局修改
#nprogress .bar {
  height: 20rpx;
  background: #8ae54a !important; /* 进度条颜色 */
}
</style>
