<template>
  <Nav :title="detail.name">
    <img
      class="set"
      src="@/assets/images/set.png"
      @click="router.push('./set')"
    />
  </Nav>
  <van-notice-bar
    v-if="showNotice"
    left-icon="volume-o"
    mode="closeable"
    :text="detail.notice"
  />
  <van-tabs v-model:active="active" line-width="0.4rem" @change="changeTab">
    <van-tab title="互动" :name="0">
      <ChatFrame
        :type="1"
        :bsRefresh="active === 0"
        :detail="detail"
        :newMsg="newMsg"
        :stompClient="stompClient"
      />
    </van-tab>
    <van-tab title="老师" :name="1">
      <ChatFrame
        :type="2"
        :bsRefresh="active === 1"
        :detail="detail"
        :newMsg="newMsg"
        :stompClient="stompClient"
      />
    </van-tab>
    <van-tab
      title="私聊"
      :name="2"
      :badge="privateMsgUnreadCount"
      :show-zero-badge="false"
    >
      <ChatFrame
        :type="5"
        :bsRefresh="active === 2"
        :detail="detail"
        :newMsg="privateNewMsg"
        :stompClient="stompClient"
      />
    </van-tab>
    <van-tab title="精选" :name="3">
      <ChatFrame
        :type="4"
        :bsRefresh="active === 3"
        :detail="detail"
        :newMsg="newMsg"
        :stompClient="stompClient"
      />
    </van-tab>
  </van-tabs>
  <div class="input-area">
    <input
      type="text"
      v-model="content"
      maxlength="200"
      :disabled="detail.interactiveStatus === 2"
      :placeholder="
        detail.interactiveStatus === 2
          ? '暂不允许互动'
          : active === 2
          ? '请输入您想私聊的内容'
          : '请输入您想发送的内容'
      "
      @keyup.enter="sendMsg(1, { text })"
    />
    <button
      class="send"
      :disabled="!content || sendTextLoading || detail.interactiveStatus === 2"
      @click="sendMsg(1, { text })"
    >
      发送
    </button>
  </div>
</template>
<script setup>
import { ref } from "vue"
import Nav from "@/components/NavBar.vue"
import ChatFrame from "./components/ChatFrame.vue"
import { useRouter, useRoute } from "vue-router"
import { sendMessage } from "@/api/circle"
import { getCircleDetail, msgUnreadCount } from "@/api/circle"
import useWebSocket from "./hooks/useWebSocket"
import { useStore } from "vuex"

const active = ref(0)
const router = useRouter()
const route = useRoute()
const sendTextLoading = ref(false)
const content = ref("")
const store = useStore()

const showNotice = ref(false) // 是否展示公告栏，同一个公告栏只展示一次
const detail = ref({
  advisor: {},
})
const queryCircleDetail = async () => {
  const ret = await getCircleDetail({ id: route.query.id })
  if (ret && ret.code == 0) {
    detail.value = ret.data
    if (detail.value.authorityId && !detail.value.authResultVo.auth) {
      return router.replace(
        `/circle?id=${route.query.id}&saleUserId=${
          route.query.saleUserId || ""
        }`
      )
    }
    const key = `circleNotice-${detail.value.id}-${store.state.userInfo.userId}`
    const storageCircleNotice = localStorage.getItem(key)
    if (
      detail.value.notice &&
      (!storageCircleNotice || storageCircleNotice !== detail.value.notice)
    ) {
      showNotice.value = true
      localStorage.setItem(key, detail.value.notice)
    } else {
      showNotice.value = false
    }
  }
}

queryCircleDetail()

const privateNewMsg = ref({})
const privateMessage = (msg) => {
  console.log("privateMessage", msg)
  const body = JSON.parse(msg.body)
  const data = body.data
  console.log("data", data)
  // interactiveType	交互类型:1群聊;2私聊;3会话消息
  if ([1].includes(body.type)) {
    privateNewMsg.value = data
    if (active.value !== 2) {
      privateMsgUnreadCount.value++
    }
  }
}

const newMsg = ref({}) // ws最新推送的消息
const chatMessage = (msg) => {
  const body = JSON.parse(msg.body)
  const data = body.data
  console.log("data", data)
  // interactiveType	交互类型:1群聊;2私聊;3会话消息
  if ([1].includes(body.type)) {
    newMsg.value = data
  } else if (body.type === 6) {
    detail.value.interactiveStatus = data
  } else if (body.type === 16) {
    // 隐藏用户昵称
    detail.value.showNickName = data
  } else if (body.type === 19) {
    // 隐藏圈子人数
    detail.value.showMemberCount = data
  }
}
const { stompClient } = useWebSocket({
  id: route.query.id,
  privateMessage,
  chatMessage,
})

const sendMsg = async () => {
  let ret = await sendMessage({
    content: content.value,
    groupId: route.query.id,
    interactiveType: active.value === 2 ? 2 : 1,
  })
  if (ret && ret.code === 0) {
    content.value = ""
  }
}

// 获取私聊未读消息
const privateMsgUnreadCount = ref()
const getMsgUnreadCount = async () => {
  const lastId = localStorage.getItem(
    `privateMsgUnreadCount-${route.query.id}-${store.state.userInfo.userId}`
  )
  if (!lastId) return
  let ret = await msgUnreadCount({
    groupId: route.query.id,
    type: 5,
    lastId,
  })
  if (ret && ret.code === 0) {
    privateMsgUnreadCount.value = ret.data
  }
}
getMsgUnreadCount()

const changeTab = (tabName) => {
  if (tabName === 2) {
    privateMsgUnreadCount.value = 0
  }
}
</script>
<style lang="scss" scoped>
.set {
  width: 50px;
}
::v-deep .van-nav-bar {
  background: #fff;
}
.van-tabs {
  height: calc(100% - 200px);
  ::v-deep .van-tabs__content {
    height: calc(100% - 156px);
    .van-tab__panel {
      height: 100%;
    }
  }
}
.input-area {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20px 20px;
  input {
    height: 64px;
    background: #9aa4b61a;
    border-radius: 32px;
    font-weight: 500;
    font-size: 24px;
    letter-spacing: 0;
    line-height: 24px;
    padding: 0 16px;
    flex: 1;
    color: #666;
    margin: 0 20px;
  }

  input::placeholder,
  input::-webkit-input-placeholder {
    color: #666; /* 设置颜色为灰色 */
  }
  button.send {
    height: 64px;
    padding: 0 20px;
    font-size: 28px;
    border-radius: 32px;
    color: #fff;
    background-image: linear-gradient(270deg, #2e78fa 0%, #45acff 100%);
    &[disabled] {
      opacity: 0.3;
    }
  }
  .share {
    width: 64px;
    height: 64px;
    margin-left: 20px;
    background: url(../../assets/images/share1.png) no-repeat center;
    background-size: contain;
    border-radius: 50%;
  }
  .star {
    width: 64px;
    height: 64px;
    position: relative;
    background: url(../../assets/images/h-like.png) no-repeat center;
    background-size: 52px 52px;
    margin-left: 20px;
    &.active {
      background: url(../../assets/images/h-like1.png) no-repeat center;
      background-size: 52px 52px;
    }
    span {
      position: absolute;
      top: 0;
      right: 0;
      min-width: 20px;
      transform: translateX(18px) translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 4px;
      flex-direction: column;
      border-radius: 13px 13px 13px 4px;
      background: linear-gradient(
        128deg,
        #fff2dc -25.5%,
        #ffd9a7 89.14%,
        #605a52 89.14%
      );
      color: rgb(142, 81, 5);
      font-size: 18px;
      font-style: normal;
      font-weight: 500;
    }
  }
}
.van-notice-bar {
  position: absolute;
  top: 232px;
  left: 0;
  right: 0;
  font-size: 24px;
  line-height: 48px;
  height: 48px;
  z-index: 2;
}
</style>
