<script setup lang="ts">
import { ref } from 'vue'
import FgTabbar from '@/tabbar/index.vue'
import { isPageTabbar } from './tabbar/store'
import { currRoute } from './utils'

const isCurrentPageTabbar = ref(true)
onShow(() => {
  const { path } = currRoute()
  // “蜡笔小开心”提到本地是 '/pages/index/index'，线上是 '/' 导致线上 tabbar 不见了
  // 所以这里需要判断一下，如果是 '/' 就当做首页，也要显示 tabbar
  if (path === '/') {
    isCurrentPageTabbar.value = true
  } else {
    isCurrentPageTabbar.value = isPageTabbar(path)
  }
})

const helloKuRoot = ref('Hello AppKuVue')

const exposeRef = ref('this is form app.Ku.vue')

const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)
const aiIconLeft = ref(20)
const aiIconTop = ref(110)

const handleAIClick = () => {
  console.log('点击了')
  uni.navigateTo({
    url: '/pages/warning/list'
  })
}

const handleTouchStart = (e: any) => {
  isDragging.value = true
  startX.value = e.touches[0].clientX
  startY.value = e.touches[0].clientY
}

const handleTouchMove = (e: any) => {
  if (!isDragging.value) return
  const dx = e.touches[0].clientX - startX.value
  const dy = e.touches[0].clientY - startY.value
  const newLeft = aiIconLeft.value + dx * 2
  const newTop = aiIconTop.value - dy * 2
  
  // 限制在屏幕范围内
  const screenWidth = uni.getSystemInfoSync().windowWidth
  const screenHeight = uni.getSystemInfoSync().windowHeight
  
  const minLeft = 0
  const maxLeft = screenWidth * 2 - 120 // 120是AI图标的宽度
  const minTop = 0
  const maxTop = screenHeight * 2 - 120 // 120是AI图标的高度
  
  aiIconLeft.value = Math.max(minLeft, Math.min(maxLeft, newLeft))
  aiIconTop.value = Math.max(minTop, Math.min(maxTop, newTop))
  
  startX.value = e.touches[0].clientX
  startY.value = e.touches[0].clientY
}

// 结束拖动
const handleTouchEnd = () => {
  isDragging.value = false
}

defineExpose({
  exposeRef,
})
</script>

<template>
  <view>
    <!-- 这个先隐藏了，知道这样用就行 -->
    <view class="hidden text-center">
      {{ helloKuRoot }}，这里可以配置全局的东西
    </view>
    <KuRootView />
    <FgTabbar v-if="isCurrentPageTabbar" />
    <view 
      class="ai-icon" 
      @click="handleAIClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      :style="{
        left: aiIconLeft + 'rpx',
        bottom: aiIconTop + 'rpx'
      }"
    >
      <image src="/src/assets/AIimgs.gif" mode="aspectFit" />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.ai-icon {
  position: fixed;
  z-index: 9999;
  width: 120rpx;
  height: 120rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.ai-icon image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
