<template>
  <div class="mainBox">
    <!--大厅 start------------------------------------------------------------>
    <div class="layerBox">

      
      <el-container style="height: 100vh;">
        <el-aside width="300px" style="background: #f2f2f2;">
          <el-menu>
            <div class="conversation-list">会话记录（100）</div>
            <el-menu-item 
              v-for="conversation in conversations" 
              :key="conversation.session_id"
              @click="selectConversation(conversation)"
              :class="{ 'is-active': activeConversation && activeConversation.session_id === conversation.session_id }">
              <div v-if="conversation.talk_type==1">
                <el-avatar :src=conversation.user_avatar>{{ conversation.nickname }}</el-avatar> {{ conversation.nickname }}
              </div>
              <div v-if="conversation.talk_type==2">
                <el-avatar :src=conversation.group_avatar>{{ conversation.group_name }}</el-avatar> {{ conversation.group_name }}
              </div>
            
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-container>
          <el-main style="padding: 20px;">
            <div v-if="activeConversation">
              <div v-for="(message, index) in activeConversation.messages" :key="index"  class="message">
                <div v-if="message.is_me==1" :class="{'is_me':message.is_me==1}">
                  {{ message.content }} <el-avatar :src=message.user_avatar>{{ message.nickname }}</el-avatar>
                </div>
                <div  v-else>
                  <el-avatar :src=message.user_avatar>{{ message.nickname }}</el-avatar>{{ message.content }}

                </div>
              </div> 
            </div>
            <div v-else>
              请选择一个会话
            </div>
          </el-main>

          <el-footer height="60px" style="padding: 10px; background: #fff;">
            <el-input 
              v-model="newMessage" 
              placeholder="输入消息..."
              @keyup.enter="sendMessage"
              style="width: calc(100% - 100px); margin-right: 10px;">
            </el-input>
            <el-button @click="sendMessage" type="primary">发送</el-button>
          </el-footer>
        </el-container>
      </el-container>


    </div>
    <!--大厅 end------------------------------------------------------------>
  </div>
</template>

<script>
//引入公用样式
import '@/styles/global.less';
// 引入baseUrl
import URL from '@/utils/baseUrl';

export default {
  data() {
    return {
      activeConversation: null,
      newMessage: '',
      conversations: [
       
      ],
      ws: null
    };
  },
  methods: {
    selectConversation(conversation) {
      this.activeConversation = conversation;
    },
    sendMessage() {
      if (this.newMessage.trim() !== '') {

        //msg_type 消息类型  talk_type：聊天类型 1单聊 2群聊
        const message = { 
          msg_type:1,
          talk_type:this.activeConversation.talk_type,
          content:this.newMessage,
          session_id:this.activeConversation.session_id,
          msg_type:1,
          receiver_id:this.activeConversation.user_id?this.activeConversation.user_id:this.activeConversation.group_id
        };
        // this.activeConversation.messages.push(message);
        console.log("发送消息",this.ws,WebSocket.OPEN)
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify(message));
        }
        this.newMessage = '';
      }
    },
    handleIncomingMessage(event) {
      const message = JSON.parse(event.data);
      console.log("监听消息：",message)
      const conversation = this.conversations.find(conv => conv.session_id === message.session_id); // 假设所有消息都发送给Alice
      if (conversation) {
        conversation.messages.push(message);
      }
    },
    //获取会话列表
    getTalkSessionList(){
      let parames  = {
        'page':1,
        'pageSize':10
      }
      // this.$api.chat.getTalkSessionList(parames).then(res=>{
      //     this.conversations =  res.data.row
      // });
      this.$store.dispatch('chat/getTalkSessionList',parames).then(res=> {
        this.conversations =  res.data.row
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '获取聊天记录失败！'
        });
      })
    },
  },
  mounted() {
    //1.获取admin-token
    const adminToken = document.cookie.split('; ').find(row => row.startsWith('Admin-Token=')).split('=')[1];
    //console.log("Admin-Token:", adminToken);
    //2.连接websocket 
    let websocketNewUrl = URL.WebsocketUrl +"?token=" + adminToken;
    this.ws = new WebSocket(websocketNewUrl);
    this.ws.addEventListener('message', this.handleIncomingMessage);

    this.ws.addEventListener('close', function (event) {
      // 连接关闭时执行的操作
      console.log("关闭链接",event)
    });

    this.getTalkSessionList()
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.removeEventListener('message', this.handleIncomingMessage);
      this.ws.close();
    }
  }
};

</script>

<style scoped lang="less">
.layerBoxNoBg {
  padding: 30px 0 0 0;
}
//表单微调 start------------------------------------------------------------>*/
::v-deep .custom-form-item > .el-form-item__label {
  line-height: 140px !important;
}
::v-deep .custom-textarea .el-textarea__inner {
  resize: none; /* 禁止用拖拽调整大小 */
}
::v-deep .custom-align-right .el-form-item__label {
  text-align: right; /* 设置标签文字右对齐 */
}
::v-deep .el-select-group__title {
  color: #909399;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>
