<template>
  <movable-area v-if="serviceVisible && show" class="movable-area" :style="{ zIndex: props.zIndex }">
    <movable-view class="movable-view" :style="sizeStyle" :x="x" :y="y" direction="all" @change="onChange">
      <image class="service-icon" :style="sizeStyle" src="/static/home/service.png" mode="aspectFill"
        @click="toServicePage()" />
    </movable-view>
  </movable-area>
</template>
<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import useUser from "@/hooks/useUser";
import { sm4Encrypt } from '@/utils/api'
import { set, get } from '@/utils/cache'
import { toast } from "@/utils/widget";

const props = defineProps({
  zIndex: { type: Number, default: 3 },
  elderMode: { type: Boolean, default: false },
})
const serviceVisible = false
const size = computed(() => {
  if (props.elderMode) {
    return { width: 62, height: 81 }
  }
  return { width: 56, height: 72 }
})
const sizeStyle = computed(() => {
  return { width: size.value.width + 'px', height: size.value.height + 'px' }
})

const appId = process.env.APP_ID;
// const kefuUrl = `https://ykf.zytzymz.com/api/mobileweb/?channel_id=623429&channel_key=623429gnn6&wechatapp_id=698628&key=140761ecgs`
const kefuUrl = `https://ykf.zytzymz.com/s/140761ecgs`;

const x = ref(0);
const y = ref(0);
const timer = ref(null)
const show = ref(false);
const { userInfo, logined, login } = useUser();

function onChange(e) {
  if (timer.value) clearTimeout(timer.value)
  timer.value = setTimeout((a, b) => {
    x.value = a;
    y.value = b;
  }, 300, e.detail.x, e.detail.y)
}

async function toServicePage() {
  if (!logined.value) {
    await login();
  }
  if (!logined.value) return;
  const res = await sm4Encrypt({ textGroup: [`${appId}${userInfo.value.userId}`] });
  const [remark] = res && Array.isArray(res.textGroup) ? res.textGroup : [];
  if (!remark) {
    toast('获取加密参数失败，请稍后再试');
    return;
  }

  const params = {
    appid: appId,
    openid: userInfo.value.userId,
    remark
  }
  const searchParams = Object.keys(params).map(key => `${key}=${params[key]}`).join('&');
  const url = `${kefuUrl}?${searchParams}`;
  uni.navigateTo({
    url: `/pages/webview/webview?url=${encodeURIComponent(url)}&title=在线客服`
  })
}

onMounted(() => {
  const position = get('online-service-position')
  if (position) {
    x.value = position.x;
    y.value = position.y;
  } else {
    const device = uni.getSystemInfoSync();
    x.value = device.windowWidth - 30 - size.value.width;
    y.value = Math.floor(device.windowHeight / 2) + 100;
  }
  show.value = true;
})

watch([x, y], ([newX, newY]) => {
  set('online-service-position', { x: newX, y: newY })
})
</script>
<style lang="scss" scoped>
.movable-area {
  pointer-events: none;
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
}

.movable-view {
  position: relative;
  pointer-events: all;
  z-index: 10;
}
</style>
