<template>
  <el-drawer
    :visible.sync="drawerVisible"
    size="50%"
    title="聊天"
    :before-close="handleClose"
  >
    <div class="chat-container">
      <!-- 联系人列表 -->
      <div class="contact-list">
        <el-scrollbar>
          <div
            v-for="contact in contacts"
            :key="contact.contactId"
            class="contact-item"
            @click="selectContact(contact)"
          >
            <el-avatar :src="contact.user.avatar"/>
            <span>{{ contact.user.nickName }}</span>
          </div>
        </el-scrollbar>
      </div>

      <!-- 聊天内容区域 -->
      <div class="chat-box">
        <el-scrollbar style="height:80%" id="message_content_end">
          <div class="messages" ref="messageBox" >
            <div v-for="message in chatHistory" :key="message.id" class="message">
              <span>{{ contactUser.nickName }}: </span>
              <span>{{ message.content }}</span>
            </div>
          </div>
        </el-scrollbar>

        <!-- 消息输入框 -->
        <div style="bottom:0;height:20%">
          <el-input
            v-model="newMessage"
            placeholder="输入消息..."
            suffix-icon="el-icon-chat-dot-round"
            @keyup.enter="sendMessage"
          />
          <el-button @click="sendMessage" icon="el-icon-paperclip">发送</el-button>
        </div>

      </div>
    </div>
  </el-drawer>
</template>

<script>
import {getContact, listContact} from "../../../api/system/contact";
import {parseTime} from "../../../utils/ruoyi";
import {addMessage} from "../../../api/system/message";

export default {
  name: 'ChatComponent',
  props:{
    drawerVisible:Boolean,

  },
  data() {
    return {

      contacts: [], // 联系人列表
      selectedContact: null, // 当前选中的联系人
      chatHistory: [], // 当前聊天记录
      newMessage: '', // 输入框中的消息
      socket: null, // WebSocket实例
      contactQueryParams: {
        pageSize: 10,
        pageNum: 1
      },
      contactUser:{}
    };
  },
  methods: {
    // 打开聊天窗口
    openChat() {
      console.log("窗口打开")
      this.drawerVisible = true;
    },

    // 关闭聊天窗口
    handleClose() {
      this.drawerVisible = false;
    },


    // 选择联系人
    selectContact(contact) {
      this.selectedContact = contact;
      this.chatHistory = []; // 清空当前聊天记录
      console.log(contact);
      this.loadMessage(contact.id);
    },

    getContactList() {
      this.contactListLoading = true;
      this.contactQueryParams.userId = this.userId;
      listContact(this.contactQueryParams).then(response => {
        if (response.code === 200) {
          this.contacts = response.rows;
          this.contactListTotal = response.total;
          const contactUserId = this.$route.query.userId;
          if (contactUserId) {
            this.contactUserId = contactUserId;
            let contact = response.rows.find(row => row.contactUserId === contactUserId);
            this.loadMessage(contact.id);
          }
        }
        this.contactListLoading = false;
      })
    },
    contactLoadMore() {
      // this.contactQueryParams.pageSize = 5;
      // this.contactQueryParams.pageNum++;
      this.getContactList();
    },
    loadMessage(concatId) {
      this.msgListLoading = true;
      getContact(concatId).then(response => {
        if (response.code === 200) {
          console.log(response.data)
          this.currentContact = response.data;
          this.contactUser = response.data.user;
          this.chatHistory = response.data.messages;
        }
        this.msgListLoading = false;
        this.fleshScroll();
      })
    },
    insertEmoji(emoji) {
      this.inputVal += emoji.data;
    },
    sendMessage() {
      const message = {
        contactId: this.currentContact.id,
        userId: this.userId,
        content: this.inputVal,
        roomId: this.currentContact.roomId
      }
      this.msgList.push({
        ...message,
        id: this.msgList.length + 1,
        createTime: parseTime(new Date())
      })
      this.fleshLastMsg();
      addMessage(message)
      const msg = {
        sendUserId: this.userId,
        sendUserName: this.$store.state.user.name,
        userId: this.currentContact.contactUserId === this.userId ? this.currentContact.user.userId : this.currentContact.contactUserId,
        type: "chat",
        detail: this.inputVal
      }
      this.$webSocket.sendWebsocket(JSON.stringify(msg));
      this.inputVal = '';
      this.fleshScroll();
    },
    subscribeMessage(res) {
      if (res) {
        const {sendUserId, sendUserName, userId, type, detail} = res.detail.data;

        const message = {
          id: 1,
          contactId: this.currentContact.id,
          userId: sendUserId,
          content: detail,
          roomId: this.currentContact.roomId,
          createTime: parseTime(new Date()),
          user: this.contactUser
        }
        this.msgList.push(message);
        this.fleshLastMsg();
        this.fleshScroll();


      }
    },
    fleshLastMsg() {
      const index = this.contactList.findIndex(e => e.id === this.currentContact.id);
      this.contactList[index].endMsg = this.msgList[this.msgList.length - 1].content;
    },
    fleshScroll() {
      this.$nextTick(() => {
        document.getElementById("message_content_end").scrollIntoView();
      })
    }
  },
  created() {
    this.userId = this.$store.state.user.id;
    this.subscribeMessage();
    this.getContactList();
  },

  mounted() {
    window.addEventListener("onmessageWS", this.subscribeMessage);

  }
  ,
}
;
</script>

<style scoped>
.chat-container {
  display: flex;

  height: 100%;
}

.contact-list {
  width:40%;
  background: #f4f4f4;
  padding: 10px;
  border-right: 1px solid #ddd;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
}

.contact-item:hover {
  background: #e0e0e0;
}

.chat-box {
  display: flex;
  width: 55%;
  height: 100%;
  flex-direction: column;
  padding: 10px;
}

.messages {

  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
}

.el-input {
  margin-top: 10px;
}
</style>
