<template>
  <movable-area class="movable-area">
    <movable-view
      class="movable-view"
      direction="all"
      :x="snapPos.x"
      :y="snapPos.y"
      :animation="true"
      @change="onDrag"
      @touchend="onTouchEnd"
    >
      <view class="cs-button">
        <uv-icon name="kefu-ermai" color="#FFFFFF" size="24"></uv-icon>
      </view>
      <button class="contact-btn" open-type="contact" @contact="handleContact" send-message-title="YesWash洗车客服" />
    </movable-view>
  </movable-area>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const POS_KEY = 'kefuPos'

/* 实时拖拽位置（非响应式，避免与原生拖拽冲突） */
let dragX = 600
let dragY = 800

/* 初始位置从缓存读取 */
try {
  const last = uni.getStorageSync(POS_KEY)
  if (last) {
    dragX = last.x
    dragY = last.y
  }
} catch {}

const snapPos = ref({ x: dragX, y: dragY })
let windowInfo: any = null

function getWindowInfo() {
  if (!windowInfo) {
    windowInfo = uni.getWindowInfo()
  }
  return windowInfo
}

function onDrag(e: any) {
  dragX = e.detail.x
  dragY = e.detail.y
}

function onTouchEnd() {
  const { windowWidth, windowHeight } = getWindowInfo()
  const btnPx = windowWidth * 104 / 750
  const maxX = windowWidth - btnPx

  const snapX = dragX < maxX / 2 ? 0 : maxX
  const snapY = Math.max(0, Math.min(dragY, windowHeight - btnPx))

  snapPos.value = { x: snapX, y: snapY }
  uni.setStorageSync(POS_KEY, { x: snapX, y: snapY })
}

const handleContact = () => {}
</script>

<style scoped lang="scss">
.movable-area {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 999999;
}

.movable-view {
  width: 104rpx;
  height: 104rpx;
  pointer-events: auto;
  position: relative;
}

.cs-button {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background: #C6171E;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(198, 23, 30, 0.28);
  position: absolute;
  left: 0;
  top: 0;
  transition: transform 0.15s ease;

  &:active {
    transform: scale(0.92);
  }
}

.contact-btn {
  position: absolute;
  left: 0;
  top: 0;
  width: 104rpx;
  height: 104rpx;
  opacity: 0;
  z-index: 2;
  padding: 0;
  margin: 0;
}
</style>
