<script>
export default {
  name: "index",
};
</script>
<script setup>
import { ref, reactive, toRaw, toRefs, nextTick, computed, watchEffect,onMounted,inject } from "vue";
import { useRouter, useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
import word from "@/assets/images/word2.png";
import chat from "@/assets/images/profile.png";
import cebian from "@/assets/images/cebian.png";
import send from "@/assets/images/send.png";
import downFile from "@/assets/images/down-file.png";
import preFile from "@/assets/images/outline_preview.png";
import forwardFile from "@/assets/images/forward-file.png";
import sendFile from "@/assets/images/send-file.png";
import myfile from '@/api/myfile/myfile'
import { parseTime } from "@/utils/ruoyi";
import store from "@/store";
import {
  msgFriend,
  userTree,
  userInfo,
  msgSend,
  msgRecord,
  delMsg,
  dirTree,
  fileTree,
  spaceInfo,
  fileDownload,
} from "@/api/chat/msg";
import Addperson from "@/components/AddPerson/index.vue"; //添加人员的弹框
import FileTreeChoice from "@/components/FileTreeChoice/index.vue"; //选择文件发送的列表
import forwordTree from "@/components/forwordTree/index.vue"; //选择文件发送的列表
//websocket连接====
import useWebsoctStore from "@/store/modules/websocket";
import { ElMessage } from "element-plus";
import { preview } from "@/api/common/common.js";
import { canPreviewFile, rightMenuRole, setIcon } from "@/utils/index.js";
import ImgPreview from '@/components/ImgPreview/ImgPreview.vue'
const router = useRouter(); //注册路由
const websoctStore = useWebsoctStore();
//====
const { proxy } = getCurrentInstance();
const userIds = useUserStore();
// main元素的初始高度，在onMounted时需要重新计算
let height = ref(document.documentElement.clientHeight - 16 + "px;");
let height2= ref('0px'); //会话列表高度
const messageText = ref(""); //发送的内容
let headerName = ref("");
const total = ref(0);
const sendId = ref(""); //选择发送的文件id
const isForward = ref(false);
const openFile = ref(false); //文件目录
const openForwardFile = ref(false); //转发目录
const showCircel = ref(""); //是否 显示圆点
const chatRecords = reactive({ data: [] });
const loading = ref(false);
const addFileTab = inject("addFileTab");
const wangzhi=import.meta.env.VITE_APP_BASE_API
const copyFileType = ref();
const previewData = ref();
const showPreview = ref(false);
const loadingPreview = ref(false);
const sendCont = reactive({
  //发送聊天内容数据组装
  data: {
    content: "",
    fileList: [],
    toId: 0,
    msgType: "",
  },
});
const searchText = ref(""); //搜
const searchData = ref([]);

//聊天列表数据模拟
const personList = reactive({ data: [] });
let getchatUserState = false //获取会话人员列表状态.获取动作完成前接收到的消息需要临时缓存
let tmpMsgList = ref([]) //临时消息队列。主要存储会话人员还未获取完成前收到的消息
//获取好友列表
const getMsgList = async () => {
  getchatUserState = true
  const resFriend = await msgFriend();
  personList.data = resFriend.rows;
  searchData.value = personList.data;
  if(personList.data.length==0){
    getchatUserState = false
    return
  }
  //圆点======
  sendCont.data.toId =
    personList.data[0]?.toId == userIds.uid
      ? personList.data[0].fromId
      : personList.data[0].toId;
  headerName.value =
    personList.data[0]?.toId == userIds.uid
      ? personList.data[0].fromName
      : personList.data[0].toName;
  // 默认点击第一个对话人
  if (clickPersonId.value ==0 && personList.data.length>0) {
    clickPersonId.value = sendCont.data.toId
  }
  getchatUserState = false
  if(tmpMsgList.value.length>0){
    //处理临时缓存消息：将发送者标记为消息未读提示
    searchData.value.map((user) => {
      let charUserid = user?.toId == userIds.uid  ? user.fromId : user.toId;
      for(let i=0;i<tmpMsgList.value.length;i++){
        let tmpFromID = tmpMsgList.value[i].fromId
        if (tmpFromID == charUserid && sendCont.data.toId!=tmpFromID) {
          user.showCircel = true;
        }
      }
    });
    tmpMsgList.value = []
  }
  if (sendCont.data.toId) {
    //调用聊天记录
    msgRecordEvent(sendCont.data.toId);
  }
};
const noMes = ref(false);
const boottmScroll = () => {
  //发送消息后滚动到最底部显示最新消息
  const chatContainer = document.querySelector(".right-container");
  if(chatContainer==null) return
  // 计算滚动的目标位置
  const targetScrollTop = chatContainer.scrollHeight;
  // 设置滚动位置
  nextTick(() => {
    chatContainer.scrollTop = targetScrollTop;
  });
};
let noReadList = null;
//往前继续读取
let pageNumRead = 1
const readChat =async ()=>{
      pageNumRead++
      const queryParams = {
          pageNum: pageNumRead,
          pageSize: 10,
        };
      const resMsgData = await msgRecord(toIdValue, queryParams);
      if(resMsgData.rows[0].isRead === "N"){
        readChat()
      }
}
//获取用户的聊天记录
const msgRecordEvent = async (toIdValue) => {
  if(clickPersonId.value!=toIdValue) return;
  const queryParams = {
    pageNum: 1,
    pageSize: 10,
  };
  const resMsgData = await msgRecord(toIdValue, queryParams);
  if(resMsgData.rows.length<=0){
    chatRecords.data = []
    return
  }
  if(resMsgData.rows[0].isRead === "N"){
      readChat()
  }
  resMsgData.rows.map((i) => (i.isForward = false));
  chatRecords.data = resMsgData.rows.reverse();
  const PageNum = Math.ceil(chatRecords.data.length / 10) + 1;
  if (PageNum * 10 > resMsgData.total && !noMes.value) {
    loading.value = false;
    noMes.value = false;
  }
  const nowtime = parseTime(new Date().getTime(), "{y}-{m}-{d}");
  chatRecords.data.map((i) => {
    if (nowtime == i.createTime.substr(0, 10))
      i.createTime = i.createTime.substring(11);
  });
  total.value = resMsgData.total;
  boottmScroll();  
  setTimeout(() => {
    noReadList = localStorage.getItem('noreadlist');
    if(noReadList==null || noReadList=='') return;
    noReadList = JSON.parse(noReadList);
    if(noReadList[sendCont.data.toId]!=null) delete noReadList[sendCont.data.toId]
    let i=0
    for(let k in noReadList){
      i++
    }
    if(i==0) window.localStorage.removeItem('noreadlist');
    else window.localStorage.setItem('noreadlist',JSON.stringify(noReadList));
  }, 500); 
};
//点击左侧新建聊天
const open = ref(false);
const userTreeData = reactive({ data: [] });
const clickNewPerson = async () => {
  const res = await userTree();
  userTreeData.data = res;
  toRaw(userTreeData.data);
  open.value = true;
};
// 点击文件预览
const toPreviewFile = async (index,file)=>{
   copyFileType.value = file.fileType;
  loadingPreview.value = true;
  const filePreview = canPreviewFile(file.fileType);
  if (filePreview) {
    loadingPreview.value = false;
    const itemData = {
        name: file.fileName,
        path: `${window.location.origin}/fileEdit?clickRowId=${file.docId}&canEdit=0&canCopy=0&history=0&fileId=0`
    }
    // sessionStorage.setItem('newTab',JSON.stringify(itemData))
    window.parent.$setOpenTab(itemData)
    // addFileTab(file, 0, 0);
  } else {
    const res = await preview(file.docId);
    showPreview.value = true;
    previewData.value = URL.createObjectURL(res);
    loadingPreview.value = false;
  }
}
//关闭图片预览事件
const closeImgPreview = () => {
  // console.log('close');
  showPreview.value = false;
};
const setImg = (type) => {
  return setIcon(type);
};
//点击左侧聊天列表
const clickPersonIndex = ref("");
const clickPersonId = ref(0);
const clickPerson = (index, item) => {
  sendCont.data.toId = item.userId
    ? item.userId
    : item.toId == userIds.uid
    ? item.fromId
    : item.toId;
  headerName.value = item.nickName
    ? item.nickName
    : item.toId == userIds.uid
    ? item.fromName
    : item.toName;
  noMes.value = false;
  clickPersonIndex.value = index;
  clickPersonId.value = sendCont.data.toId;
  //点击某个人就不显示红点
  searchData.value.map((i) => {
    if (i.fromId == item.fromId) {
      i.showCircel = false;
    }
  });
  const chatContainer = document.querySelector(".right-container");
  // 计算滚动的目标位置
  const targetScrollTop = chatContainer.scrollHeight;
  // 设置滚动位置
  chatContainer.scrollTop = targetScrollTop;
  msgRecordEvent(sendCont.data.toId); 
};
//删除聊天
const delClick = (toId) => {
  proxy.$modal
    .confirm("删除后，将清空与该人员的所有会话记录，确定吗？")
    .then(function () {
      return delMsg(toId);
    })
    .then(() => {
      chatRecords.data    = []
      headerName.value    = ''
      clickPersonId.value = 0
      sendCont.data.toId  = 0
      getMsgList();
      proxy.$modal.msgSuccess("删除成功");
    });
};

//树选中的人传过来的选中人的信息，push进入列表中
// val 新的会话人员信息对象
// isnew：false或null：自己添加的 true：其他人员发起的新消息会话
const changeMsg = async (val,isnew) => {
  const resInfo = await userInfo(val.id);
  resInfo.fromId = val.id
  resInfo.content = val.content
  resInfo.file = val.file
  // resInfo.toAvatar = resInfo.fromAvatar = resInfo.avatar
  if (searchData.value.length > 0) {
    //判断是否有相同的聊天人
    const filerData = searchData.value.filter(
      (vPerson) =>
        (vPerson.toId && vPerson.toId == resInfo.userId) ||
        (vPerson.fromId && vPerson.fromId == resInfo.userId)
    );
    if (filerData.length > 0) {
      // 存在就算了，无需提示
      //return ElMessage({ message: "该聊天已存在", type: "error" });
    } else {
      if(isnew!=null){        
        resInfo.showCircel = true        
      }
      searchData.value.unshift(resInfo);
      chatRecords.data = []
    }
  } else {
    //为空数组的时候无需判断
    searchData.value.unshift(resInfo);
  }
  if(isnew==null){
    // 自己添加的会话人员，默认选中进行对话
    sendCont.data.toId = resInfo.userId;
    headerName.value = resInfo.nickName;
    clickPersonId.value = resInfo.userId
    clickPerson(0,searchData.value[0]);
  }else if(searchData.value.length==1){
    sendCont.data.toId = resInfo.userId;
    headerName.value = resInfo.nickName;
    clickPersonId.value = val.id
    clickPerson(0,searchData.value[0]);
  }
};

//发送聊天
const inputRef = ref(null);
const msgSendClick = (event) => {
  if (event.ctrlKey && event.keyCode == 13) {
    //CTRL+enter键换行
    const textarea = event.target;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = messageText.value;
    messageText.value = text.slice(0, start) + "\n" + text.slice(end);
    nextTick(() => {
      textarea.selectionStart = start + 1;
      textarea.selectionEnd = start + 1;
    });
    event.preventDefault();
  } else if (event.shiftKey && event.keyCode == 13) {
    event.preventDefault();
  }
};
const msgSendClick2 = (event,icon) => {
  if(sendCont.data.toId==null||sendCont.data.toId==0){
    return ElMessage({ message: "请添加或者选择会话人员", type: "error" });
  }
  if ((!event.shiftKey && event.keyCode == 13 && !event.ctrlKey)||icon) {
  event.preventDefault();
  noMes.value = false;
    if (messageText.value.trim() == "") {
      return ElMessage({ message: "不能发送空白消息", type: "error" });
    }
    const message = {
      content: messageText.value,
      msgType: "2",
      fileList: [],
      toId: sendCont.data.toId,
    };
    websoctStore.sendMessage(message).then((res) => {
      if(res.code==200){
        //发送成功
        messageText.value = "";
        msgRecordEvent(sendCont.data.toId)
      }
    }).catch((err) => {
      //发送失败了
    })
  }
}
//发送文件确认按钮
const fileChangeMsg = async (val) => {
  if(sendCont.data.toId==null||sendCont.data.toId==0){
    return ElMessage({ message: "请添加或者选择会话人员", type: "error" });
    return
  }
  const message = {
    content: val.id,
    msgType: "1",
    fileList: [],
    toId: sendCont.data.toId,
  };
  sendId.value = val.id;
  websoctStore.sendMessage(message).then((res) => {
      if(res.code==200){
        //发送成功
        messageText.value = "";
        msgRecordEvent(sendCont.data.toId)
      }
  }).catch((err) => {
      //发送失败了
  })
};
//点击发送文件图标
const fileUserTreeData = reactive({ data: {} });
const sendFileClick = async () => {
  const resDir = await fileTree(3);
  fileUserTreeData.data = resDir;
  toRaw(fileUserTreeData.data);
  openFile.value = true;
};
//获取用户聊天记录
const handleNewMessage = async () => {
  //console.log("======当前状态:",localStorage.getItem("inChat"),'    sendCont.data.toId:',sendCont.data.toId)
  if('1'==localStorage.getItem("inChat")){
    const hasNewMessage = localStorage.getItem('noreadlist');
    if(hasNewMessage==null || hasNewMessage=='') return;
    msgRecordEvent(sendCont.data.toId); //获取用户的聊天记录
  }
};
//接收到的新消息
watchEffect(async() => {
  let newMessages = {}
  newMessages = websoctStore.messOne  
  // if(router.currentRoute.value.path!='/index' || newMessages.fromId==null) return;
  if( newMessages.fromId==null) return;
  //此处判断messOne是否已发生更改，如果还未发生更改则清除该消息
  if(websoctStore.messOne.fromId==newMessages.fromId){    
    noMes.value = false;
    websoctStore.messOne={}
  }
  // console.log("clickPersonId:",clickPersonId.value)
  if(getchatUserState){
    //会话列表还处理完成，临时缓存消息
    tmpMsgList.value.push(newMessages)
    // console.log("===============会话列表还处理完成，临时缓存消息：",tmpMsgList.value)
    return
  }
  if(websoctStore.noReadList!=null) {
    // 是否正在对话的人员
    if(clickPersonId.value!=newMessages.fromId){
      let isExist=false // 当前消息发送人员是否已在对话人员列表中
      for(let i=0;i<searchData.value.length;i++){
        let chatUserID = searchData.value[i].fromId
        if(chatUserID==userIds.uid) chatUserID = searchData.value[i].toId
        if(chatUserID==newMessages.fromId){
          isExist = true
          searchData.value[i].showCircel = true
          searchData.value[i].content = newMessages.content
          searchData.value[i].file = newMessages.file
        }
      }
      if(!isExist){
        // 接收到其他人员发来的第一次会话消息，需要将该人员添加到会话人员列表
        changeMsg({"id":newMessages.fromId,"content":newMessages.content,"file":newMessages.file},true)
      }
      return;
    }
    msgRecordEvent(newMessages.fromId);   
    // getYuan()    
    // getMsgList();
  }
});
// 滚动翻页========
const mainContainer = ref(null);
const handleScroll = (event) => {
  // 在滚动到顶部时，加载上一页的聊天记录
  const mainContainer2 = document.querySelector(".right-container");
  if (
    event.deltaY < 0 &&
    mainContainer2.scrollTop <= 1 &&
    !noMes.value &&
    !loading.value
  ) {
    loading.value = true;
    loadPreviousPage();
  }
};
const loadPreviousPage = async () => {
  const currentPageNum = Math.ceil(chatRecords.data.length / 10) + 1;
  const queryParams = {
    pageNum: currentPageNum,
    pageSize: 10,
  };
  const resMsgData = await msgRecord(sendCont.data.toId, queryParams);
  const previousPageData = resMsgData.rows.reverse();
  chatRecords.data = [...previousPageData, ...chatRecords.data];
  const nowtime2 = parseTime(new Date().getTime(), "{y}-{m}-{d}");
  chatRecords.data.map((i) => {
    if (nowtime2 == i.createTime.substr(0, 10))
      i.createTime = i.createTime.substring(11);
  });
  noMes.value = false;
  if (currentPageNum * 10 > resMsgData.total && !noMes.value) {
    loading.value = false;
    noMes.value = true;
    return;
  }
  //获取数据后滚动到获得新消息的最后一条，而不是第一条=========
  await nextTick();
  const mainContainer = document.querySelector(".right-container");
  const newMessages = document.querySelectorAll(".message-container");
  // console.log('mainContainer',mainContainer);
  const firstNewMessage = newMessages[previousPageData.length];
  // const firstNewMessageTop = mainContainer.offsetHeight + 100;
  const firstNewMessageTop = mainContainer.offsetHeight-10;
  mainContainer.scrollTop = firstNewMessageTop;
  chatRecords.data;
  //===========
  // 将加载的上一页聊天记录插入到 chatRecords.data 的前面
  loading.value = false;
  // }, 50);
};
const transferFiles = (forwardVal, msgIds, indexs) => {
  chatRecords.data.map((i, index) => {
    if (i.msgId == msgIds && i.msgType == "1" && indexs == index) {
      i.isForward = true;
    } else {
      i.isForward = false;
    }
  });
};
// 点击转存
const forwardTreeData = reactive({ data: {} });
const spaceId = ref("");
const docId = ref("");
const forwardClick = async (indexs, docIds) => {
  docId.value = docIds ? docIds.toString() : "";
  const resDir = await dirTree(3);
  forwardTreeData.data = resDir;
  toRaw(forwardTreeData.data);
  //获取最上层树的id
  const topSpaceid = await spaceInfo(3);
  spaceId.value = topSpaceid.data.spaceId.toString();
  openForwardFile.value = true;
};
const forwardChangeMsg = async (val) => {};
//点击下载
const downClick = async (file) => {
  // location.href = `${import.meta.env.VITE_APP_BASE_API}/api/download/${fileId}`;
downLoadfile(file)
};
//搜索的点击事件
const SearchChat = () => {
  if (searchText.value) {
    searchData.value.map((user) => {
      let charUserName = user?.toId == userIds.uid  ? user.fromName : user.toName;
      if(charUserName==null) charUserName = user.nickName
      if(charUserName.indexOf(searchText.value.replace(/ /gi,''))>-1) user['display'] = 1
      else user['display'] = 0
    });
  } else {
    searchData.value.map((user) => {
      user['display'] = 1
    });
  }
};
//转聊天记录的/n为实际样式
const formatText = (text) => {
  const formattedText = text.replace(/\n/g, "<br>");
  return formattedText;
};
  // 文件下载
  const downLoadfile = (file)=>{
      myfile.fileDown(file.docId).then(res=>{
            var reader = new FileReader();
          reader.onloadend = function(event){
          //event 就是你要的返回内容
          //因为返回的报错格式是字符串，手动转换成对象，转换成功表示请求失败
          //转换失败就意味着你拿到的result是文件流，那么直接手动下载就好
          try{
              let data = JSON.parse(event.target.result)
          }catch(err){
              const link = document.createElement('a');  // 创建a标签
              let blob = new Blob([res]);     
              link.style.display = 'none';
              link.href = URL.createObjectURL(blob);   // 创建下载的链接
              link.setAttribute('download',file.fileName);  // 给下载后的文件命名
              document.body.appendChild(link);
              link.click();  // 点击下载
              document.body.removeChild(link);  //  完成移除元素
              window.URL.revokeObjectURL(link.href);  // 释放blob对象
          }
          };
          reader.readAsText(res);
      })
  };
const headError=(ind,item)=>{
  // console.log("头像加载失败:",ind)
  // item.fromAvatar=item.toAvatar=item.avatar=null;
};
// 滚动翻页========
onMounted(() => {
  // height.value = document.documentElement.clientHeight - document.getElementsByClassName("tab_box")[0].offsetHeight-8-document.getElementsByClassName("nav")[0].offsetHeight -26 + "px";
  height2.value = height.value.replace('px','') - 48 + 'px';
  getMsgList();
  websoctStore.connect();
  setInterval(handleNewMessage, 1000); // 每秒钟检查是否有新消息
});
</script>

<template>
  <div class="main" :style="'height:' + height">
    <!-- 左侧用户列表 -->
    <div class="left-main">
      <div class="left-top search">
        <el-input
          v-model="searchText"
          maxlength="32"
          class="w-50 m-2"
          size="small"
          clearable
          placeholder="搜索聊天"
          suffix-icon="Search"
          @change="SearchChat"
        />
        <!-- 添加聊天人员 -->
        <el-icon
          size="24"
          color="#505870"
          class="shouzhi"
          @click="clickNewPerson"
          style="margin-right: 8px"
          ><Plus
        /></el-icon>
        <!-- 新建聊天弹框 -->
        <Addperson
          :open="open"
          @close="open = false"
          :userTreeData="userTreeData.data"
          @changeMsg="changeMsg"
        ></Addperson>
      </div>
      <!-- 列表 -->
      <div :style="'overflow-y: auto;height: '+height2">
        <div
          :class="
            (item.display!=null && item.display==0) 
            ? ''
            :(
            clickPersonIndex == index
              ? 'activ-left-container left-container shouzhi'
              : 'left-container shouzhi'
            )
          "
          v-for="(item, index) in searchData"
          :key="index"
          @click="clickPerson(index, item)"
        >
        <template v-if="item.display==null || item.display==1">
          <img :src="cebian" class="cebian" v-if="clickPersonIndex == index" />
          <button
            class="del-chat"
            v-if="clickPersonIndex == index && item.fromId!=-1"
            @click="delClick(item.userId!=null? item.userId : (item.toId == userIds.uid?item.fromId:item.toId))"
          >
            删除会话
          </button>
          <div>
            
            <img
              :src="wangzhi + item.fromAvatar"
              class="head-sculpture"
              :onerror="headError(index,item)"
              v-if="item.toId == userIds.uid && item.fromAvatar"
            />
            <img :src="wangzhi + item.avatar" :onerror="headError(index,item)" alt="" class="head-sculpture" v-else-if="item.avatar"/>
            <img
              :src="wangzhi + item.toAvatar"
              class="head-sculpture"
              :onerror="headError(index,item)"
              v-else-if="item.toId != userIds.uid && item.toAvatar"
            />
            <span
              style="
                background-color: #7a89ba;
                display: inline-block;
                color: #fff;
                font-weight: 600;
                text-align: center;
                line-height: 40px;
              "
              class="head-sculpture"
              v-else
              >{{ item.nickName!=null? item.nickName.slice(0, 1):item.toId == userIds.uid? item.fromName.slice(0, 1): item.toName.slice(0, 1) }}</span>
          </div>
          <div class="spill">
            <span class="person-name">{{
              item.nickName
                ? item.nickName
                : item.toId == userIds.uid
                ? item.fromName
                : item.toName
            }}</span
            ><span class="person-cont spill">
              {{ item.file?.fileName ? item.file?.fileName : item.content }}</span
            >
          </div>
          <span
            class="yuandian"
            v-if="item.showCircel && $route.path == '/index' && clickPersonId!==item.fromId"
          ></span>
        </template>
        </div>
      </div>
    </div>
    <!-- 右侧聊天 -->
    <div class="right-main">
      <div
        class="common-layout"
        style="display: flex; flex-direction: column; height: 100vh"
      >
        <el-container>
          <el-header height="64px" class="right-header flex-buju">{{
            headerName
          }}</el-header>
          <!-- 聊天 -->
          <el-main
            class="right-container"
            @wheel="handleScroll"
            ref="mainContainer"
          >
            <div v-loading="loading"></div>
            <!-- <div v-if="noMes" style="color:#9fa1a5 ;">无更多聊天记录</div> -->
            <div
              class="message-container"
              v-for="(record, index) in chatRecords.data"
              :class="{
                'message-left': useUserStore().uid == record.toId,
                'message-right': useUserStore().uid !== record.toId,
              }"
              :key="index"
            >
              <div>
                <div
                  v-if="useUserStore().uid !== record.toId"
                  style="display: flex"
                >
                  <div
                    :class="
                      record.msgType == '1'
                        ? 'file-msg right-back'
                        : 'time-text right-back'
                    "
                  >
                    <img
                      :src="word"
                      v-if="record.msgType == '1'"
                      class="head-sculpture"
                    />
                    <div
                      :class="
                        record.msgType == '2' ? 'clip-path' : 'clip-path-right'
                      "
                    >
                      <div
                        style="
                          color: #c1cce3;
                          font-size: 12px;
                          margin-bottom: 4px;
                        "
                      >
                        {{ record.createTime.slice(0, -3) }}
                      </div>
                      <span v-if="record.msgType == '1'">{{
                        record.file?.fileName
                      }}</span>
                      <!-- <span v-else-if="record.msgType == '2'">{{
                    record.content
                  }}</span> -->
                      <span
                        v-else-if="record.msgType == '2'"
                        v-html="formatText(record.content)"
                      ></span>
                    </div>
                  </div>
                  <div>
                    <!-- 右侧聊天头像 -->
                    <img
                      :src="wangzhi + record.fromAvatar"
                      class="head-sculpture"    
                      :onerror="headError(index,record)"                  
                      v-if="
                        useUserStore().uid != record.toId && record.fromAvatar
                      "
                    />
                    <img
                      :src="wangzhi + record.toAvatar"
                      class="head-sculpture"
                      :onerror="headError(index,record)"
                      v-else-if="
                        useUserStore().uid == record.toId && record.toAvatar
                      "
                    />
                    <span
                      style="
                        background-color: #7a89ba;
                        display: inline-block;
                        color: #fff;
                        font-weight: 600;
                        text-align: center;
                        line-height: 40px;
                      "
                      class="head-sculpture"
                      v-else
                      >{{ record.fromName!=null ? record.fromName.slice(0, 1) :'系' }}</span
                    >
                  </div>
                </div>
                <!-- 头像 -->
                <!-- <img :src="chat" class="head-sculpture" /> -->
              </div>
              <div style="display: flex; align-items: center">
                <div
                  v-if="useUserStore().uid == record.toId"
                  style="display: flex"
                >
                  <div>
                    <!-- 左侧侧聊天头像 -->
                    <img
                      :src="wangzhi + record.fromAvatar"
                      class="head-sculpture"
                      :onerror="headError(index,record)"
                      v-if="
                        useUserStore().uid == record.toId && record.fromAvatar
                      "
                    />
                    <img
                      :src="wangzhi + record.toAvatar"
                      class="head-sculpture"
                      :onerror="headError(index,record)"
                      v-else-if="
                        useUserStore().uid != record.toId && record.toAvatar
                      "
                    />
                    <span
                      style="
                        background-color: #7a89ba;
                        display: inline-block;
                        color: #fff;
                        font-weight: 600;
                        text-align: center;
                        line-height: 40px;
                      "
                      class="head-sculpture"
                      v-else
                      >{{ record.fromName!=null? record.fromName.slice(0, 1):'系' }}</span
                    >
                  </div>
                  <div
                    :class="
                      record.msgType == '1' ? 'file-msg left-back' : 'left-back'
                    "
                    @click="transferFiles(record.msgType, record.msgId, index)"
                  >
                    <img
                      v-if="record.msgType == '1'"
                      :src="setImg(record.file.fileType)"
                      class="head-sculpture"
                    />
                    <div
                      :class="
                        record.msgType == '2' ? 'clip-path' : 'clip-path-left'
                      "
                    >
                      <div
                        style="
                          color: #7a89ba;
                          font-size: 12px;
                          margin-bottom: 4px;
                        "
                      >
                        {{ record.createTime.slice(0, -3) }}
                      </div>
                      <span v-if="record.msgType == '1'">{{
                        record.file?.fileName
                      }}</span>
                      <span
                        v-else-if="record.msgType == '2'"
                        v-html="formatText(record.content)"
                      ></span>
                    </div>
                  </div>
                </div>
                 <img
                  :src="preFile"
                  class="zhuanfa downf shouzhi"
                  alt="预览"
                  v-if="record.isForward"
                  @click="toPreviewFile(index, record.file)"
                />
                <img
                  :src="forwardFile"
                  class="zhuanfa forwd shouzhi"
                  alt="转存"
                  v-if="record.isForward && record.file.unloading"
                  @click="forwardClick(index, record.file?.docId)"
                />
                <img
                  :src="downFile"
                  class="zhuanfa downf shouzhi"
                  alt="下载"
                  v-if="record.isForward && record.file.unloading"
                  @click="downClick(record.file)"
                />
              </div>
            </div>
          </el-main>
          <!-- 底部 -->
          <el-footer height="112px" class="right-footer" v-if="sendCont.data.toId>0">
            <!-- 发送文件 -->
            <img
              :src="sendFile"
              class="send-info-file shouzhi"
              @click="sendFileClick"
            />
            <FileTreeChoice
              :openFile="openFile"
              @close="openFile = false"
              :fileUserTreeData="fileUserTreeData.data"
              @fileChangeMsg="fileChangeMsg"
            ></FileTreeChoice>
            <el-input
              v-model="messageText"
              class="w-50 m-2"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5 }"
              clearable
              ref="inputRef"
              size="small"
              placeholder="请输入聊天内容"
              maxlength="800"
              @keyup.ctrl.enter="msgSendClick($event)"
              @keyup.shift.enter="msgSendClick($event)"
              @keydown.enter="msgSendClick2($event)"
            />
            <!-- 发送按钮 -->
            <img :src="send" class="send-info" @click="msgSendClick2($event,true)" />
          </el-footer>
        </el-container>
      </div>
    </div>
  </div>
  <!-- 发送消息按钮选择的文件 -->
  <forwordTree
    :openForwardFile="openForwardFile"
    :docId="docId"
    :spaceId="spaceId"
    @close="openForwardFile = false"
    :forwardTreeData="forwardTreeData.data"
    @forwardChangeMsg="forwardChangeMsg"
  ></forwordTree>
    <ImgPreview
    :previewData="previewData"
    :copyFileType="copyFileType"
    :showPreview="showPreview"
    @closeImgPreview="closeImgPreview"
  ></ImgPreview>
  <div
    v-loading.fullscreen="loadingPreview"
    v-if="loadingPreview"
    class="lodingBox"
  ></div>
</template>

<style lang="scss" scoped>
@import "@/assets/styles/my-common.scss";
.left-container {
  position: relative;
}
.yuandian {
  width: 8px;
  height: 8px;
  position: absolute;
  right: 8px;
  top: 6px;
  background: #fa5151;
  border-radius: 4px;
}
:deep(.el-textarea__inner) {
  resize: none;
}
</style>