<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <z-paging
    ref="pagingRef"
    v-model="msgList"
    :paging-style="{'top': '0',background: '#F2F3F7'}"
    :empty-view-text="prodEmptyTips"
    :empty-view-img="EmptyTipsUrl"
    :empty-view-img-style="{width:'460rpx',height:'460rpx'}"
    class="page-platform-message"
    @query="onLoadMsgList"
  >
    <view class="Mall4j platform-message notice-message my-message">
      <!-- #ifdef H5 -->
      <!-- <view class="top-title">
      <view class="my-message">我的消息</view>
    </view> -->
      <!-- #endif -->
      <template v-if="isAuthorities">
        <!-- 客服消息 -->
        <view class="service-message">
          <view
            v-for="(item, index) in msgList"
            :key="index"
            class="item unread"
            @tap="toChat(item)"
          >
            <view class="logo">
              <img-show
                :src="item.pic"
                :def-img-inx="2"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ item.nickName }}
              </view>
              <view class="des">
                {{ getMessageText(item.lastMessage) }}
              </view>
            </view>
            <view class="time-box">
              <view class="time">
                {{ item.timestampString||'time' }}
              </view>
              <view
                v-if="item.unread"
                class="unread-box"
              >
                <view class="number">
                  {{ item.unread }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <empty-tips
        v-else
        :tips-list="[$t('niMeiYouFangWenQuanXian')]"
      />
    </view>
  </z-paging>
</template>

<script setup>
import EmptyTipsUrl from '@/static/images/empty-tips.png'
import util from '@/utils/util'
import { Convert } from '@/utils/convert'
import { ConversationWrap } from '@/utils/ConversationWrap'
import { WKSDK, ConversationAction } from 'wukongimjssdk'
const isLoaded = ref(false) // 列表是否加载完毕
const msgList = ref([])
const prodEmptyTips = ref($t('ninHuanMeiYouXiaoXiJiLu'))
let shopInfo = ''
const isAuthorities = ref(false)
const userStore = useUserStore()

const shopId = computed(() => {
  return userStore.shopId
})

/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  getShopInfo()
})

onShow(() => {
  isAuthorities.value = util.isAuthorities('message:message:view')
  if (shopInfo) {
    pagingRef.value?.reload()
  }
  uni.setNavigationBarTitle({
    title: $t('xiaoXiHeZi')
  })
  util.transTabbar()
})
WKSDK.shared().config.provider.syncConversationsCallback = async () => {
  const data = await http.request({
    url: '/shop/wuKongIm/conversation/sync/page',
    method: 'get',
    data: params
  }).then(({ data }) => {
    const resultConversations = []
    const conversationList = data.records
    if (conversationList) {
      conversationList.forEach((v) => {
        const conversation = Convert.toConversation(v)
        conversation.lastMessage.content.text = JSON.parse(conversation.lastMessage?.content.text)
        resultConversations.push(conversation)
      })
    }
    return resultConversations
  })
  return data
}
onUnload(() => {
  WKSDK.shared().conversationManager.removeConversationListener(conversationListener) // 移除最近会话列表监听
})

/**
 * 根据tabType类型 获取消息数据
 */
const pagingRef = ref(null)
let params = {}
const onLoadMsgList = async (current, size) => {
  const url = '/shop/wuKongIm/conversation/sync/page'
  isLoaded.value = false
  const reqData = {
    current,
    size,
    version: 0
  }
  params = {
    url,
    method: 'GET',
    data: reqData
  }
  const remoteConversations = await WKSDK.shared().conversationManager.sync() // 同步最近会话列表
  const conversationWraps = sortConversations(remoteConversations.map(conversation => new ConversationWrap(conversation)))
  pagingRef.value.complete(conversationWraps)
}
// 判断是否为JSON格式
const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}

/**
 * 获取店铺信息
 */
const getShopInfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET',
    data: {
      shopId: shopId.value
    }
  }
  http.request(params).then(({ data: res }) => {
    shopInfo = res
    if (shopInfo) {
      WKSDK.shared().conversationManager.addConversationListener(conversationListener) // 监听最近会话列表的变化
    }
  })
}

// 去客服聊天
const toChat = (item) => {
  uni.navigateTo({
    url: '/pages/chat/chat?userId=' + item.userId + '&userName=' + item.nickName + '&isDestroy=' + item.isDestroy
  })
}

// 排序最近会话列表
const sortConversations = (conversations) => {
  let newConversations = conversations
  if (!newConversations) {
    newConversations = msgList.value
  }
  if (!newConversations || newConversations.length <= 0) {
    return []
  }
  const sortAfter = newConversations.sort((a, b) => {
    let aScore = a.timestamp
    let bScore = b.timestamp
    if (a.extra?.top === 1) {
      aScore += 1000000000000
    }
    if (b.extra?.top === 1) {
      bScore += 1000000000000
    }
    return bScore - aScore
  })
  return sortAfter
}
const conversationListener = async (conversation, action) => {
  if (action === ConversationAction.add) {
    const { data } = await http.request({ url: '/shop/wuKongIm/listChannelSubcribers?channelId=' + conversation.channel.channelID, method: 'GET' })
    // eslint-disable-next-line require-atomic-updates
    conversation.nickName = data.subscribers[data.subscribers.length - 1].nickName
    // eslint-disable-next-line require-atomic-updates
    conversation.userId = data.subscribers[data.subscribers.length - 1].userId
    // eslint-disable-next-line require-atomic-updates
    conversation.pic = data.subscribers[data.subscribers.length - 1].pic
    // 将新对话转换为 ConversationWrap 对象
    const newConversationWrap = new ConversationWrap(conversation)
    // 检查是否存在具有相同 userId 的对话
    const conversationExists = msgList.value.some(conversationWrap => conversationWrap.conversation.userId === newConversationWrap.conversation.userId)
    if (!conversationExists) {
      msgList.value = [new ConversationWrap(conversation), ...(msgList.value || [])]
    } else {
      msgList.value[0].conversation = new ConversationWrap(msgList.value[0].conversation)
    }
  } else if (action === ConversationAction.update) {
    const index = msgList.value?.findIndex(item => item.channel.channelID === conversation.channel.channelID && item.channel.channelType === conversation.channel.channelType)
    if (index !== undefined && index >= 0) {
      msgList.value[index] = new ConversationWrap(conversation)
      msgList.value = sortConversations()
    }
  }
}
const getMessageText = (message) => {
  if (isJSON(message.content.text)) {
    message.content.text = JSON.parse(message.content.text)
  }
  if (message.content.text?.msgType === 1 || message.content.text?.msgType === -1 || message.content.text?.type === -5) {
    return message.content?.text.msg
  } else if (message.content.text?.msgType === 4) {
    return $t('shangPinLianJie')
  } else if (!message.content.text?.msgType) {
    return message.content.text?.content || ''
  } else {
    return $t('tuPian')
  }
}

</script>

<style lang="scss" scoped>
@import "./message-box.scss";
</style>
