<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view class="chat_content" @touchmove.stop.prevent>
  <!-- <view class="chat_content"> -->
	  <cu-custom :isBack='true' >
	     <template v-slot:content>
	       <text v-if='chat' class="text-jiachu">{{ chat.name }}</text>
	       <text v-if='chat && chat.type === ChatType.GROUP' class="text-jiachu">（{{ count }}人）</text>
	     </template>
	     <template v-slot:right>
	       <text class='cuIcon cuIcon-more' @tap='chatInfo'></text>
	     </template>
	   </cu-custom>
    <scroll-view :scroll-y='true' class='cu-chat' :style="'height: calc(100vh - '+customBar+'px - 3.125rem)'"
                 @scroll='handleScroll' scroll-with-animation="true"
                 :scroll-into-view='last' id='messageBox'>
      <checkbox-group @change="checkboxChange">
      <template  v-for='(item) in messageList' :key="item.id">
        <load-map-user :userId="item.fromId" />
        <view v-if="item.messageType === MessageType.event" class="text-center">
          <MessageEvent :message="item"></MessageEvent>
        </view>
        <view v-else :id="`m-${item.id}`" >
          <view v-if='item.mine' class='cu-item self'>
            <view class='main' style='display: block;'>
              <view class='text-gray padding-bottom-sm' style="font-size: 15px;padding-bottom: 10px;">
                <view class='margin-right inline' style="margin-right: 15px;">
                  <Time :time='item.timestamp'></Time>
                </view>
                <text style='color: black;'>{{ userMap.get(item.fromId)?.name }}</text>
              </view>
              <view class='content shadow break-word contentR'>
                <message-view :item='item'></message-view>
              </view>
              <quote-message :message="item" v-if="item.extend?.quoteMessage"/>
              <view
                  v-if="chat && chat.type === ChatType.FRIEND && item.fromId === user?.id"
                  class="read-tips" :class='!chat.lastReadTime || item.timestamp > chat.lastReadTime?"":"read"'
              >
                {{ !chat?.lastReadTime || item.timestamp > chat?.lastReadTime ? '未读' : '已读' }}
              </view>
            </view>
            <view>
              <vim-avatar :size="'small'" :img="userMap.get(item.fromId)?.avatar" :name="userMap.get(item.fromId)?.name" />
            </view>
            <view v-if="showMultipleCheck" class="padding-left">
              <checkbox :value="item" style="transform:scale(0.7)"/>
            </view>
          </view>
          <view v-if='!item.mine' class='cu-item' :id="`m-${item.id}`" >
            <view v-if="showMultipleCheck" class="padding-right">
              <checkbox :value="item" style="transform:scale(0.7)"/>
            </view>
            <view class='flex flex-direction'>
              <vim-avatar :size="'small'" :img="userMap.get(item.fromId)?.avatar" :name="userMap.get(item.fromId)?.name" />
            </view>
            <view class='main' style='display: block;'>
              <view class='text-gray padding-bottom-sm' style="font-size: 15px;padding-bottom: 10px;">
                <text style='color: black;'>{{ userMap.get(item.fromId)?.name }}</text>
                <view class='margin-left inline' style="margin-left: 15px;">
                  <Time :time='item.timestamp'></Time>
                </view>
              </view>
              <view class='content shadow break-word contentL'>
                <message-view :item='item'></message-view>
              </view>
              <quote-message :message="item" v-if="item.extend?.quoteMessage"/>
            </view>
          </view>
        </view>
      </template>
      <view v-if='messageList' :id="'m-last'"></view>
      </checkbox-group>
	  <view style="height: 60upx;"></view>
    </scroll-view>
    
    <view class='cu-bar foot input' v-if="isValidatedUser" :style="chatStore.quoteMessage?'min-height:5rem;'+'bottom:'+KeyboardHeight+'px;':''+'bottom:'+KeyboardHeight+'px;'">
      <!-- #ifdef APP-PLUS -->
      <view class='action' @tap='changeSendType'>
        <text class='text-grey'
              :class="{'cuIcon-sound':sendType === 'keyboard','cuIcon-keyboard':sendType === 'voice'}"></text>
      </view>
      <!-- #endif -->
      <view class="flex-sub" v-if="sendType === 'keyboard'" >
		  <textarea class="textinput" auto-height="true"
					:always-embed='false' 
					:adjust-position='false'
					cursor-spacing='30'
					confirm-hold='true'
					confirm-type='send'
					:focus='false'
					maxlength='300'
					v-model='messageContent'
					@confirm='mineSendBT' 
					@input='handleShowAt'
		  ></textarea>
        <!-- <input  type="text" :always-embed='false' :adjust-position='false' cursor-spacing='30' confirm-hold='true'
            v-model='messageContent' confirm-type='send' class='solid-bottom' :focus='false' maxlength='300' @confirm='mineSendBT' @input='handleShowAt'/> -->
        <handle-quote-message v-if="chatStore.quoteMessage" :message="chatStore.quoteMessage"/>
      </view>
      <view v-if="sendType === 'keyboard'" class='action'>
        <text class='cuIcon-add text-grey' @tap='showFace=true'></text>
      </view>
      <!-- <button v-if="sendType === 'keyboard' && isValidatedUser" class='cu-btn bg-green shadow' @tap='mineSend'>发送</button> -->
      <voice v-if="sendType === 'voice'" @uploadCallback='uploadCallback'></voice>
    </view>
    <view class='cu-bar foot input' v-if="!isValidatedUser">
      <view class="text-center" style="flex: 1">已退群</view>
    </view>

    <view class='cu-modal bottom-modal' :class="showFace?'show':''" @tap='showFace=false'>
      <view class='cu-dialog'>
        <Faces @click='showFace = true' class='faces-box' @insertFace='insertFace'></Faces>
        <vim-upload v-if="chat" :chat-type="chat.type" :chat-id="chat.id" ></vim-upload>
      </view>
    </view>

    <view class='cu-modal bottom-modal' :class="showAt?'show':''" @tap.stop='handleHideAt'>
      <view class='cu-dialog'>
        <view>
          <!-- <input type="text" v-model="keyword" placeholder="请输入过滤条件" style="height: 80upx"/> -->
        </view>
        <view class='cu-list menu menu-margin at-box'>
          <view v-if='isMaster' class='cu-item' @tap="handleAtUser('所有人')">
            <view class='content'>
              <text class='text-grey'>所有人</text>
            </view>
          </view>
          <view class='cu-item' v-for='(user, index) in  keywordFilter([...userMap.values()],keyword)' :key='index'
                @tap="handleAtUser(user.name)">
            <view class='content'>
              <text class='text-grey'>{{ user.name }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <multiple-forward v-if="showMultipleCheck"></multiple-forward>
  </view>
</template>

<script setup lang='ts'>
import Auth from "@/api/Auth";
import {useChatStore} from '@/store/chatStore'
import {useUserStore} from '@/store/userStore'
import {computed, getCurrentInstance, ref} from 'vue'
import Time from '@/components/Time.vue'
import MessageView from '@/components/MessageView.vue'
import Voice from '@/components/Voice.vue'
import Faces from '@/components/Faces.vue'
import VimUpload from '@/components/VimUpload.vue'
import type Message from '@/mode/Message'
import MessageType from '@/utils/MessageType'
import {onBackPress, onHide, onLoad, onShow, onUnload} from '@dcloudio/uni-app'
import CuCustom from '@/colorui/components/cu-custom.vue'
import ChatType from '@/utils/ChatType'
import type ChatSimple from '@/mode/ChatSimple'
import type Extend from '@/mode/Extend'
import {useWsStore} from '@/store/WsStore'
import {match} from "pinyin-pro";
import {imageLoad, last} from "@/hooks/useMessageImageLoad";
import {count, isValidatedUser, isMaster, loadUserOrGroup, users} from "@/hooks/useChatInit";
import {storeToRefs} from "pinia";
import QuoteMessage from "@/components/QuoteMessage.vue";
import HandleQuoteMessage from "@/components/HandleQuoteMessage.vue";
import MessageEvent from "@/components/messages/MessageEvent.vue";
import MessageApi from "@/api/MessageApi";
import VimAvatar from "@/components/VimAvatar.vue";
import {useMessageStore} from "@/store/messageStore";
import MultipleForward from "@/components/MultipleForward.vue";
import LoadMapUser from "@/components/LoadMapUser.vue";

//@ts-ignore
const {proxy} = getCurrentInstance()
const chatStore = useChatStore()
const userStore = useUserStore()
const wsStore = useWsStore()
//当前聊天室id
const id = ref()
const sendType = ref('keyboard')
const customBar = ref(proxy.customBar)
//是否展示多选
const {showMultipleCheck} = storeToRefs(useMessageStore())
//是否展示表情
const showFace = ref(false)
//弹出键盘高度
const KeyboardHeight = ref(10)

const gundwez = ref('')
const fontValue=ref(Auth.getfontSize());
//是否展示@
const showAt = ref(false)

//是否展示@
const showJp = ref(false)

//输入框的内容
const messageContent = ref('')
//过滤关键词
const keyword = ref('')
//当前聊天
const chat = computed(() => {
  if (chatStore.openChatId) {
    return chatStore.getChat(chatStore.openChatId)
  } else {
    return undefined
  }
})

//聊天对象,
const {userMap} = storeToRefs(userStore)
//消息列表
const messageList = computed(() => {
  return chatStore.getChatMessage(id.value) ?? []
})

//当前用户
const user = userStore.getUser()

onBackPress(() => {
  chatStore.setOpenChatId('')
})
onUnload(() => {
  chatStore.setOpenChatId('')
})

onHide(() => {
  chatStore.setOpenChatId('')
})

const changeSendType = () => {
  sendType.value === 'keyboard' ? sendType.value = 'voice' : sendType.value = 'keyboard'
}
//多选
const checkboxChange= (e:any) => {
  useMessageStore().setCheckList(e.detail.value)
  
}
//获取聊天室id
onLoad((opt) => {
	uni.onKeyboardHeightChange(onKeyboardHeightChange);
	//console.log(user);
  id.value = opt?.id
  //console.log(id);
  chatStore.setOpenChatId(id.value)
  if (chat.value && ChatType.FRIEND === chat.value.type && user) {
    //获取读取消息的时间,这里要颠倒下，是查询对方的读取时间，不是自己的
    //所以聊天室chatId是自己,fromId是对方
    MessageApi.getReadTime(user.id, chat.value.id).then((res) => {
		//console.log(res);
      if (res.data) {
        chatStore.setCurrentChatLastReadTime(parseInt(res.data))
      }
    })
  }
})

const keywordFilter = (items: ChatSimple[], keyword: string): ChatSimple[] => {
  return items.filter((item) => {
    return !!(keyword.trim() === '' || match(item.name, keyword))
  })
}

const handleScroll = () => {
  last.value = '';
}

onShow(() => {
  chatStore.setOpenChatId(id.value)
  if(chat.value){
    if (user) {
      loadUserOrGroup(chat.value, user)
    }
    //延迟1秒发生已读回执消息
    setTimeout(function () {
      readMessage()
    }, 1000)
    //重写 callback 方法，收到的消息后滚动到最下面
    wsStore.callBack(() => {
      if (chat.value && chatStore.openChatId === chat.value.id) {
        imageLoad(messageList.value)
      }
	  //console.log('1111111');
    })
  }
})


const onKeyboardHeightChange = (res:any) => {
	  const { height, duration } = res;
	  //console.log(res);
	  gundwez.value = last.value;
	  last.value='';
	  // 键盘弹起
	  if (height > 0) {
		//console.log('键盘弹起');
		KeyboardHeight.value=height;
		customBar.value = proxy.customBar+height;
	  }// 键盘收回
	  else {
		//console.log('键盘收回');
		KeyboardHeight.value=10;
		customBar.value = proxy.customBar;
	  }
	  setTimeout(() => {
	    last.value = 'm-last';
	  }, 350)
	 //console.log(last);
}

/**
 * 展示聊天室信息
 */
const chatInfo = () => {
 if(chat.value){
   if (ChatType.GROUP === chat.value.type) {
     uni.navigateTo({
       url: '/pages/group/group?id=' + chat.value.id
     })
   } else {
     uni.navigateTo({
       url: '/pages/pub/user?id=' + chat.value.id
     })
   }
 }
}



const uploadCallback = (extend: Extend, messageType: string) => {
	console.log(user,chat.value)
  if (user && chat.value) {
	  //console.log('uploadCallback');
    let msg: Message = {
      messageType: messageType,
      chatId: chat.value.id,
      fromId: user.id,
      content: '',
      type: chat.value.type,
      extend: extend
    }
    wsStore.sendMessage(msg)
  }
}

const getAtUserIds = (str: string): Array<string> => {
  if (users.value) {
    const regex = /@\[([^\]]+)\]/g
    let match
    const usernames = new Array<string>()
    while ((match = regex.exec(str)) !== null) {
      usernames.push(match[1])
    }
    const ids = users.value
        .filter((user) => {
          return usernames.indexOf(user.name) > -1
        })
        .map((user) => {
          return user.id
        })
    return Array.from(new Set(ids))
  } else {
    return []
  }
}



const mineSend = (): void => {
  if (messageContent.value && messageContent.value.trim() !== '' && user && chat.value) {
    let msg: Message = {
      messageType: MessageType.text,
      chatId: chat.value.id,
      fromId: user.id,
      content: messageContent.value,
      type: chat.value.type
    }
    msg.extend = {
      atAll: isMaster.value && msg.content.includes('@[所有人]'),
      atUserIds: getAtUserIds(msg.content)
    }
    if (chatStore.quoteMessage) {
      msg.extend = {
        quoteMessage: chatStore.quoteMessage,
      }
    }
    wsStore.sendMessage(msg)
    messageContent.value = ''
    chatStore.setQuoteMessage(undefined);
  }
}

const mineSendBT = (e) =>{
	console.log('mineSendBT',chat.value);
	if (messageContent.value && messageContent.value.trim() !== '' && user && chat.value) {
	  let msg: Message = {
	    messageType: MessageType.text,
	    chatId: chat.value.id,
	    fromId: user.id,
	    content: messageContent.value,
	    type: chat.value.type
	  }
	  msg.extend = {
	    atAll: isMaster.value && msg.content.includes('@[所有人]'),
	    atUserIds: getAtUserIds(msg.content)
	  }
	  if (chatStore.quoteMessage) {
	    msg.extend = {
	      quoteMessage: chatStore.quoteMessage,
	    }
	  }
	  console.log('mineSend',msg);
	  wsStore.sendMessage(msg)
	  messageContent.value = ''
	  chatStore.setQuoteMessage(undefined);
	}
}

//添加表情
const insertFace = (item: string) => {
  messageContent.value = `${messageContent.value}face${item}`
  showFace.value = false
}

const handleAtUser = (username: string) => {
  messageContent.value = `${messageContent.value}[${username}]`
  showAt.value = false
}
const inputfocus = (e) =>{
	//console.log('inputfocus',e.detail.height);
	showkeybar.value=e.detail.height;
}

/**
 * 显示@
 */
const handleShowAt = () => {
  if (chat.value && chat.value.type === ChatType.GROUP && messageContent.value.endsWith('@')) {
    showAt.value = true
	sendType.value = '';
  }
}
/**
 * 隐藏@
 * @param e TouchEvent
 */
const handleHideAt = (e: TouchEvent) => {
  e.stopPropagation()
  showAt.value = false
  sendType.value = 'keyboard';
}
/**
 * 用户点击消息列表某个聊天场景
 */
const readMessage = () => {
  if (user && chat.value) {
    let read = {
      chatId: chat.value.id,
      userId: user.id,
      timestamp: new Date().getTime(),
      type: chat.value.type
    }
    wsStore.sendRead(read)
  }
}

</script>

<style scoped>

.chat_content {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	overflow: hidden;
}

.cu-chat {
  display: block;
  background-color: #FFF;
  border: solid #eee;;
  border-width: 1px 0px 0rpx 0px;
}

.faces-box {
  height: auto;
}

.inline {
  display: inline-block;
}

.at-box {
  height: 50vh;
  bottom: 0;
  overflow-y: scroll
}

.break-word {
  word-wrap: break-word;
  word-break: break-all;
}


.read-tips {
  font-size: 20upx;
  line-height: 48upx;
}
.read {
  color: #5fb878;
}

.textinput{
	margin-top: 10rpx;
	margin-bottom: 10rpx;
	padding-top: 10rpx;
	padding-bottom: 10rpx;
	width: 100%;
	border-radius: 6rpx;
	border: 1rpx solid darkgray;
	font-size: 32upx;
}

</style>
