<template>
  <view>
      <z-paging class="cu-chat"  ref="paging" v-model="messageList" use-chat-record-mode safe-area-inset-bottom bottom-bg-color="#f8f8f8"
                @query="queryList" >
      <!-- 底部聊天输入框 -->
      <template #top>
        <cu-custom bgImage="/static/bg.png" :isBack="true">
          <template v-slot:content>
            <text>{{ chatName }}</text>
          </template>
        </cu-custom>
        <scroll-view scroll-x class="bg-white nav" >
          <view class="flex text-center">
            <view class="cu-item flex-sub" :class="index===tabCur?'text-orange cur':''" v-for="(item,index) in options"
                  :key="index" @tap="tabSelect($event,item)" :data-id="index">
              {{ item.label }}
            </view>
          </view>
        </scroll-view>
      </template>
      <view v-for='(item,index) in messageList' :id="`z-paging-${index}`" :key="item.id" class="paging-item">
        <view v-if="item.messageType === MessageType.event" class="text-center" style="transform: scaleY(-1)">
          <MessageEvent :message="item"></MessageEvent>
        </view>
        <template v-else>
          <view v-if='item.fromId ===  currentUser!.id' class='cu-item self' style="transform: scaleY(-1)">
            <view class='main' style='display: block;'>
              <view class='text-gray text-sm padding-bottom-sm'>
                <view class='margin-right inline'>
                  <Time :time='item.timestamp'></Time>
                </view>
                <text>{{ chatUsers.get(item!.fromId)?.name }}</text>
              </view>
              <view class='content shadow'>
                <message-view :item='item'></message-view>
              </view>
            </view>
            <view>
              <image class='cu-avatar radius' :src='chatUsers.get(item.fromId)?.avatar'></image>
            </view>
          </view>
          <view v-if='item.fromId !==  currentUser!.id' class='cu-item' :id="'m-'+index" style="transform: scaleY(-1)">
            <view class='flex flex-direction'>
              <image class='cu-avatar radius' :src='chatUsers.get(item.fromId)?.avatar'></image>
            </view>
            <view class='main' style='display: block;'>
              <view class='text-gray text-sm padding-bottom-sm'>
                <text>{{ chatUsers.get(item!.fromId)?.name }}</text>
                <view class='margin-left inline'>
                  <Time :time='item.timestamp'></Time>
                </view>
              </view>
              <view class='content shadow'>
                <message-view :item='item'></message-view>
              </view>
            </view>
          </view>
        </template>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {onLoad, onPageScroll} from '@dcloudio/uni-app';
import {useUserStore} from "@/store/userStore";
import MessageApi from "@/api/MessageApi";
import MessageView from '@/components/MessageView.vue';
import Time from '@/components/Time.vue';
import type ChatSimple from "@/mode/ChatSimple";
import CuCustom from '@/colorui/components/cu-custom.vue';
import ChatType from "@/utils/ChatType";
import GroupApi from "@/api/GroupApi";
import UserApi from "@/api/UserApi";
import type User from "@/mode/User";
import MessageType from "@/utils/MessageType";
import MessageEvent from "@/components/messages/MessageEvent.vue";
import ZPaging from "@/uni_modules/z-paging/components/z-paging/z-paging.vue";
//聊天对象,
const userStore = useUserStore();

const messageList = ref([]);
const chatId = ref('');
const keyword = ref('');
const messageType = ref('');
const chatName = ref('');
const type = ref('');
const tabCur = ref(0);
const scrollLeft = ref(0);
const paging = ref();
const chatUsers = ref<Map<string, ChatSimple>>(new Map());
const currentUser = userStore.getUser();
const dateRange = ref([])
const options = [
  {value: '', label: '全部'},
  {value: '0', label: '文本'},
  {value: '1', label: '图片'},
  {value: '2', label: '文件'},
  {value: '3', label: '语音'},
  {value: '5', label: '视频'}
]
const tabSelect = (e: TouchEvent, item: any) => {
  tabCur.value = e.currentTarget!.dataset.id;
  messageType.value = item.value;
  uni.redirectTo({
    url: '/pages/chat/history?chatId=' + chatId.value + '&type=' + type.value + '&messageType=' + messageType.value + '&tabCur=' + tabCur.value
  })
}
//获取聊天室id
onLoad((opt) => {
  chatId.value = opt?.chatId;
  type.value = opt?.type;
  if(opt?.tabCur){
    tabCur.value = Number(opt?.tabCur)
  }
  if(opt?.messageType){
    messageType.value = opt?.messageType
  }
  loadUsers()
})

onPageScroll((e) => {
  if (e.scrollTop < 1) {
    paging.value.doChatRecordLoadMore();
  }
})

const loadUsers = () => {
  if (currentUser) {
    chatUsers.value.set(currentUser.id, {avatar: currentUser.avatar, name: currentUser.name});
    if (type.value === ChatType.FRIEND) {
      UserApi.getUser(chatId.value)
          .then((res) => {
            const chatUser = res.data;
            chatName.value = chatUser.name
            chatUsers.value.set(chatUser.id, {avatar: chatUser.avatar, name: chatUser.name});
          })
    } else {
      GroupApi.users(chatId.value)
          .then((res) => {
            res.data.forEach((item: User) => {
              chatUsers.value.set(item.id, {avatar: item.avatar, name: item.name});
            })
            return GroupApi.get(chatId.value)
          })
          .then((res) => {
            chatName.value = res.data.name
          })
    }
  }
}

/**
 * 加载数据
 * @param pageNum
 * @param pageSize
 */
const queryList = (pageNum: number, pageSize: number) => {
  if (currentUser) {
    uni.showLoading()
    MessageApi.search(
        chatId.value,
        currentUser!.id,
        keyword.value,
        type.value,
        messageType.value,
        pageNum,
        dateRange.value ? dateRange.value[0] : '',
        dateRange.value ? dateRange.value[1] : '',
        pageSize
    ).then(
        (res: any) => {
          //数据反转
          const dataList: [] = res.data.records;
          paging.value.complete(dataList)
        }
    )
        .catch(() => {
          paging.value.complete(false);
        })
        .finally(() => {
          uni.hideLoading()
        })
  }
}

</script>
<style scoped>
.inline {
  display: inline-block;
}
.cu-chat {
  background-color: #eeeeee;
}
.cu-chat .cu-item{
  padding: 0 0.625rem;
}
.paging-item{
  padding: 0.5rem 0 ;
}
</style>