<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>
      <view class="contact-btn" @click.stop="handleContactClick" />
    </movable-view>
  </movable-area>
</template>

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

const POS_KEY = 'kefuPos'

/** 客服在线时间 9:30 ~ 21:30 */
const isInServiceHours = (): boolean => {
  const now = new Date()
  const current = now.getHours() * 60 + now.getMinutes()
  return current >= 9 * 60 + 30 && current <= 21 * 60 + 30
}

/* 实时拖拽位置（非响应式，避免与原生拖拽冲突） */
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 openCustomerService = () => {
  // #ifdef MP-WEIXIN
  wx.openCustomerServiceConversation({
    sessionFrom: '',
    showMessageCard: true,
    sendMessageTitle: 'YesWash洗车客服'
  })
  // #endif
}

const handleContactClick = () => {
  if (isInServiceHours()) {
    openCustomerService()
    return
  }
  uni.showModal({
    title: '客服提示',
    content: '客服在线时间 9:30~21:30，当前留言可能会延迟回复',
    cancelText: '取消',
    confirmText: '继续留言',
    success: (res) => {
      if (res.confirm) {
        openCustomerService()
      }
    }
  })
}
</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>
