<template>
  <div style="width: 100%;height: 100%">

<!-- <el-tabs class="im-tabs" type="card" v-model="appKey" @tab-click="qwUserChange">
                            <el-tab-pane
                              v-for="item in qwUserList"
                              :key="item.id"
                              :name="item.appKey">
                              <span slot="label">
                                <el-badge :value="getUnreadCount(item.appKey)"
                                          :max="99"
                                          v-if="getUnreadCount(item.appKey) > 0">
                                  {{ item.qwUserName }}
                                </el-badge>
                                <template v-else>
                                  {{ item.qwUserName }}
                                </template>
                              </span>
                            </el-tab-pane>
                          </el-tabs> -->

<!-- <div class="close-box">
            <i class="el-icon-close" @click="handleClose" style="font-size: 22px;margin-right: 8px;cursor: pointer;"/>
          </div> -->

    <div class="imui-center qq-lemon-imui" v-show="showQW">
      <lemon-imui  class="lemon-slot"
                   :width="isMaximized ? '100vw' : '100%'"
                   :height="isMaximized ? '90vh' : windowHeight"
                   :user="userData"
                   ref="IMUI"
                   :contact-contextmenu="contactContextmenu"
                   :theme="theme"
                   :hide-menu="hideMenu"
                   :hide-menu-avatar="hideMenuAvatar"
                   :hide-message-name="hideMessageName"
                   :hide-message-time="hideMessageTime"
                   :messageTimeFormat="messageTimeFormat"
                   @change-menu="handleChangeMenu"
                   @pull-messages="handlePullMessages"
                   @change-contact="handleChangeContact"
                   @change-conversation="handleChangeConversation"
                   @message-click="handleMessageClick"
                   @menu-avatar-click="handleMenuAvatarClick"
                   @pick-image="handleImageClick"
                   @send="handleSend">
                    <template #menu-top>
                      <div class="qiwei">
                         <div  v-for="item in qwUserList" :key="item.id" @click="qwUserChange(item)" :class="appId==item.id?'q-item active':'q-item'">
                          <el-badge :value="getUnreadCount(item.appKey)"
                                     :max="99"
                                     :hidden="getUnreadCount(item.appKey) < 1">
                                       <el-avatar shape="square" :src="item.avatar"></el-avatar>
                                       <el-popover
                                       popper-class="popover"
                                           placement="right"
                                           :title="'姓名：'+item.qwUserName"
                                           trigger="hover"
                                           :content="'所属公司：'+item.corpName">
                                           <div slot="reference">
                                             <div class="name" >{{item.qwUserName}}</div>
                                             <div class="text" >{{item.corpName}}</div>
                                           </div>
                                         </el-popover>

                           </el-badge>
                         </div>
                      </div>
                    </template>
        <template #sidebar-message-top>
          <div style="padding: 12px; display: flex; align-items: center;">
            <el-input
              v-model="searchKeyword"
              prefix-icon="el-icon-search"
              placeholder="搜索"
              size="small"
              clearable
              @input="handleSearch"
              style="flex: 1;height: 32px;margin-right: 8px;"
              class="top-input"
            />
            <el-popover
              placement="bottom-end"
              width="200"
              v-model="filterPopoverVisible"
              trigger="click"
            >
              <!-- 这里放你的过滤选项内容 -->
              <div>
                <el-checkbox-group v-model="selectedFilters">
                  <el-checkbox label="1">去掉重粉</el-checkbox>
                  <el-checkbox label="2">去掉黑粉</el-checkbox>
                  <!-- <el-checkbox label="3">按催课排序</el-checkbox> -->
                </el-checkbox-group>
                <div style="margin-top: 10px; text-align: right;">
                  <el-button size="mini" type="primary" @click="applyFilter">确定</el-button>
                </div>
              </div>
              <el-button
                slot="reference"
                icon="el-icon-setting"
                style="padding: 8px;height: 32px;border: none;background: #F1F4F8;width:32px;"
                size="medium"
                :type="selectedFilters.length > 0 ? 'primary' : 'default'"
              ></el-button>
            </el-popover>
          </div>
        </template>
        <template #sidebar-contact-top>
          <!-- 联系人顶部 -->
        </template>
       <template #group-top>
           <div class="group-item" @click="toggleGroup" style="padding-top: 14px;">
             <div class="left">
               <i class="el-icon-arrow-right" :class="{ 'rotate': openGroup }"></i>
               <div class="name">群聊</div>
             </div>
             <div class="num">{{qwGroupNum}}</div>
           </div>
        </template>
        <template #contact-top>
            <div class="group-item" @click="toggleContact">
              <div class="left">
                <i class="el-icon-arrow-right" :class="{ 'rotate': openContact }"></i>
                <div class="name">联系人</div>
              </div>
              <div class="num">{{qwContactNum}}</div>
            </div>
         </template>
        <template #message-title="contact">
          <div class="user-name">
            {{contact.displayName}}
          </div>
<!--          <div @click="openDrawer('right')" style="position: absolute;right: 14px;top: 10px;">-->
<!--            <i class="el-icon-more" style="cursor: pointer"/>-->
<!--          </div>-->
<!--          <div>-->
<!--            <el-button-->
<!--              type="primary"-->
<!--              size="small"-->
<!--              style="position: absolute;right: 14px;top: 10px;z-index: 1000"-->
<!--              @click="showDetail(contact.extId)"-->
<!--            >详情</el-button>-->
<!--          </div>-->
        </template>
        <template #message-extend="contact">
           <div class="close-box">
             <i class="el-icon-close" @click="handleClose" style="font-size: 22px;cursor: pointer;"/>
           </div>
          <div v-if="contact.extId" style="width:100%;overflow: auto">
            <userDetail :ext-id="contact.extId" :conversation-id="contact.conversationId" :extend="true" ref="userDetail" />
           </div>
            <!-- 课程管理 -->
            <div v-if="showCourseManage">
                <course-manage :conversationId="contact.conversationId" :extend="true"/>
            </div>

        </template>
      </lemon-imui>
    </div>

    <el-dialog :visible.sync="dialogVisible" append-to-body width="35%">
      <img style="width:100%;height:auto" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <el-dialog :visible.sync="dialogVideoVisible"
               :close-on-click-modal="false"
               :destroy-on-close="true"
               :width="aplayer.pWidth"
               :height="aplayer.height"
               @close="dialogVideoVisible=false"
               ref="player">
      <videoPlayer  :width="aplayer.width" :height="aplayer.height"  :videoWidth="aplayer.videoWidth"  :videoHeight="aplayer.videoHeight"   :vid="aplayer.vid"  :autoplay="true"
                    :source="dialogVideoUrl" :cover="dialogVideoCover" ref="player"></videoPlayer>
    </el-dialog>

    <!-- 用户详情 -->
    <el-drawer
      append-to-body
      :with-header="false"
      size="35%"
      :destroy-on-close="true"
      :title="detail.title" :visible.sync="detail.open">
      <userDetail ref="userDetail" />
    </el-drawer>

  </div>
</template>

<script>

import {getConversations,getMessageList,getConversation,sendMsg,getQwUserList,getContactList,getGroupList,getConversationId} from '@/api/qw/im';
import Conversations from "@/components/LemonUI/database/conversations";
import EmojiData from "@/components/LemonUI/database/emoji";
import '@/components/LemonUI/index.css';
import VideoPlayer from '@/components/VideoPlayer/VueAliplayer.vue'
import UserDetail from "@/views/qw/qwChat/userDetail/index.vue";
import courseManage from "@/views/qw/qwChat/userDetail/courseManage.vue";
import {ImSocket} from "@/utils/ImSocket";
import {getToken} from '@/utils/auth'
import {uploadOss} from "@/api/common";
import {mapState} from "vuex";
import {generateUUID} from "@/components/LemonUI/utils";
import {getTime} from "@/utils";
import notificationMp3 from '@/assets/voice/new-notification.mp3'

export default {
  name: "qqChat",
  components: {
    VideoPlayer,
    UserDetail,
    courseManage
  },
  props: {
    showQw: Boolean,
    isMaximized: Boolean
  },
  data() {
    return {
      activeNames: ['0'],
     openContact:false,
      openGroup:false,
      contactName:'',
      appKey:null,
      appId:null,
      qwUserId:null,
      qwUserList:[],
      theme: "default",
      IMUI:null,
      contactContextmenu: [],
      hideMenuAvatar: false,
      hideMenu: false,
      hideMessageName: false,
      hideMessageTime: true,
      qwUser:{},
      showQW:false,
      userData: {},
      contactData:null,
      conversationData:Conversations,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVideoVisible:false,
      dialogVideoUrl:'',
      dialogVideoCover:'',
      imageArr:[],
      pickUploadImgData:null,
      aplayer: {
        vid: "bf9b7e4a36d84aea8cee769765fbc28b",
        pWidth:"1040px",
        width:"1000px",
        height:"900px",
        videoWidth:"1000px",
        videoHeight:"900px"

      },
      player: null,
      roomMembers:[],
      roomAdmins:[],
      roomInfo:null,
      windowWidth: document.documentElement.clientWidth * 0.9,  //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight * 0.85,   //实时屏幕高度
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conversationId: null,
        userId:null
      },
      pageParams: {
        pageNum: 1,
        pageSize: 500
      },
      detail: {
        title: '',
        open: false
      },
      imSocket: null,
      imUrl: process.env.VUE_APP_IM_WS_URL,
      searchKeyword: '',
      filterPopoverVisible: false,
      selectedFilters: [],
      // 存储每个企微账号的会话记录和状态
      qwUserSessions: {},
      // 存储每个企微账号的分页信息
      qwUserPages: {},
      // 销售ID，用于WebSocket连接
      companyUserId: null,
      // 存储每个企微账号的未读消息数
      qwUserUnreadCount: [],
      //联系人列表
      qwContactList:[],
      qwContactNum:0,
      //群聊列表
      qwGroupList:[],
      qwGroupNum:0,
      //课程列表
      showCourseManage:false
    };
  },
  created(){
    // 初始化企微账号会话页码对象
    this.qwUserPages = {};
    //获取企微列表
    getQwUserList().then(response => {
      this.qwUserList = response.data;
      if (this.qwUserList.length>0){
        this.qwUser = this.qwUserList[0];
        this.appKey = this.qwUser.appKey;
        this.appId=this.qwUser.id;
        this.companyUserId = this.qwUser.companyUserId;
        this.setQwUserInfo();
        this.getConversation();
        // 初始化单个WebSocket连接
        this.initImSocket();

        // 初始化未读消息数
        this.initUnreadCount();
        //群聊
        this.initGroup(this.qwUser.id)
        //this.toggleContact();
        //联系人
        // this.initContact(this.qwUser.id)

      }else {
        this.qwUser={};
      }
    });
    console.log(this.contact,'---')
  },
  computed: {
    ...mapState('qwIm', ['shareCourse']),
    // 计算所有企微账号的未读消息总数
    totalUnreadCount() {
      return this.qwUserUnreadCount.reduce((sum, item) => sum + item.unreadCount, 0);
    },
  },
  watch: {
    showQw(nv, ov) {
      if (nv) {
        this.clearUnreadCount(this.appKey)
        this.$nextTick(() => {
          this.$refs.IMUI.messageViewToBottom();
        });
      }
    },
    shareCourse(nv) {
      if (nv) {        // 发送小程序卡片消息
        const IMUI = this.$refs.IMUI;
        const contact = IMUI.currentContact;
        if (!contact) {
          return;
        }
        // 创建消息对象
        let message = {
          type: 'miniprogram',
          title: nv.title,
          image: nv.thumbnail,
          content: nv.url,
          toContactId: contact.conversationId,
        };
        this.detail.open = false
        this.$store.dispatch('qwIm/shareCourse', null)

        // 使用handleSend方法发送消息
        this.handleSend(
          message,
          (replaceMessage = { status: "succeed" }) => {
            IMUI.updateMessage(Object.assign(message, replaceMessage));
          },
          null
        );
      }
    },
    // 监听未读消息数变化
    qwUserUnreadCount: {
      handler() {
        this.$store.dispatch('qwIm/totalUnreadCount', this.totalUnreadCount)
      },
      deep: true // 深度监听对象内部变化
    }
  },
  mounted() {
    this.showQW=true;
    const IMUI = this.$refs.IMUI;

    const conversationData = Conversations.filter(item => item.conversationId <= 1);
    conversationData.sort((a1, a2) => {
      return a2.lastSendTime - a1.lastSendTime;
    });

    IMUI.initMenus([
      {
        name: "messages",
      },
      {
        name:'contacts'
      }
    ]);
    IMUI.initEmoji(EmojiData);
    IMUI.initEditorTools([
      { name: "emoji" },
      { name: "uploadImage" }
    ])
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    if (this.imSocket) {
      this.imSocket.close();
      this.imSocket = null;
    }
    this.clearSessionCache()
  },
  methods: {
    getUnreadCount(appKey) {
      const index = this.qwUserUnreadCount.findIndex(entry => entry.appKey === appKey);
      return index !== -1 ? this.qwUserUnreadCount[index].unreadCount : 0;
    },
    // 清除会话缓存
    clearSessionCache() {
      this.qwUserSessions = {};
      this.qwUserPages = {};
    },

    // 初始化WebSocket连接
    initImSocket() {
      // 如果已经有连接，先关闭
      if (this.imSocket) {
        this.imSocket.close();
      }

      // 创建新的WebSocket连接，使用公司ID
      this.imSocket = new ImSocket(`${this.imUrl}/${this.companyUserId}?token=${getToken()}`);

      // 处理接收到的消息
      this.imSocket.onMessage(data => {
        const { IMUI } = this.$refs;
        try {
          let message = JSON.parse(data);
          this.appendRemoteMessage(message);

          // 播放声音 暂时不播放声音
          // const audio = new Audio(notificationMp3);
          // audio.play().catch(err => {
          //   console.warn("播放声音失败", err);
          // });

          // 确定消息所属的企微账号
          const messageAppKey = message.appKey;

          // 检查消息是否属于当前企微账号
          if (messageAppKey === this.appKey) {

            if (!this.showQw) {
              this.incrementUnreadCount(messageAppKey);
            }

            let conversation = IMUI.findConversation(message.toContactId);
            if (conversation && Object.keys(conversation).length !==0) {
              conversation.lastSendTime = message.sendTime;
              conversation.lastContent = IMUI.lastContentRender(message);
              IMUI.topPopConversations(conversation);

              // 更新缓存中的会话记录
              this.updateSessionConversation(conversation);
            } else {
              // 如果找不到会话，可能需要刷新会话列表
              this.refreshSession(messageAppKey);
            }
          } else if (messageAppKey) {
            // 如果不是当前账号的消息，增加对应账号的未读消息数
            this.incrementUnreadCount(messageAppKey);

            if (this.qwUserSessions[messageAppKey]) {
              const index = this.qwUserSessions[messageAppKey].findIndex(
                item => item.conversationId === message.toContactId
              );

              if (index === -1) {
                this.refreshSession(messageAppKey, false)
              }

              if (index !== -1) {
                let conversation = this.qwUserSessions[messageAppKey][index]
                conversation.lastSendTime = message.sendTime;
                conversation.lastContent = IMUI.lastContentRender(message);
                conversation.unread = conversation.unread + 1;
                this.qwUserSessions[messageAppKey][index] = {...conversation};
              }
            }
          }
        } catch (error) {
          console.error("处理WebSocket消息时出错:", error);
        }
      });
    },
    // 初始化未读消息数
    initUnreadCount() {
      // 为每个企微账号初始化未读消息数为0
      this.qwUserUnreadCount = []; // 先清空

      this.qwUserList.forEach(user => {
        this.qwUserUnreadCount.push({
          appKey: user.appKey,
          qwUserId: user.qwUserId,
          unreadCount: 0
        });
      });
    },

    // 增加指定企微账号的未读消息数
    incrementUnreadCount(appKey) {
      if (!appKey) {
        console.error("incrementUnreadCount: appKey不能为空");
        return;
      }

      // 查找对应的企微账号记录
      const index = this.qwUserUnreadCount.findIndex(item => item.appKey === appKey);

      if (index !== -1) {
        // 如果找到，则增加未读消息数
        const newCount = this.qwUserUnreadCount[index].unreadCount + 1;
        this.$set(this.qwUserUnreadCount[index], 'unreadCount', newCount);
      } else {
        // 如果没找到，则添加新记录
        const user = this.qwUserList.find(u => u.appKey === appKey);
        if (user) {
          this.qwUserUnreadCount.push({
            appKey: appKey,
            qwUserId: user.qwUserId,
            unreadCount: 1
          });
        }
      }
    },

    // 清除指定企微账号的未读消息数
    clearUnreadCount(appKey) {
      // 查找对应的企微账号记录
      const index = this.qwUserUnreadCount.findIndex(item => item.appKey === appKey);

      if (index !== -1) {
        // 如果找到，则清除未读消息数
        this.$set(this.qwUserUnreadCount[index], 'unreadCount', 0);
      }
    },

    // 切换企微账号
    qwUserChange(tab){
      this.appKey = tab.appKey;
      this.appId = tab.id;
      let index= this.qwUserList.findIndex(item => item.appKey === tab.appKey);
      this.qwUser=this.qwUserList[index];
      // 清除当前账号的未读消息数
      this.clearUnreadCount(this.appKey);
      // 不需要重新创建WebSocket连接，只需更新当前账号信息
      this.setQwUserInfo();
      this.getConversation();   //获取会话信息
      this.initGroup(this.qwUser.id)
    },
    //联系人列表
    initContact(id){
      getContactList(id).then(response => {
        this.qwContactList=response.rows;
        this.qwContactNum=response.total
        const mergedList = [...this.qwGroupList, ...this.qwContactList];
        this.$refs.IMUI.initContacts(mergedList);
        // this.getConversationId(id)
      });
    },
    //群聊列表
    initGroup(id){
      getGroupList(id).then(response => {
        this.qwGroupList=response.rows
        this.qwGroupNum = response.total
        this.initContact(id)
        //this.$refs.IMUI.initContacts(this.qwContactList);
      });
    },
    // 切换分组展开/收起状态
        toggleGroup() {
          this.openGroup = !this.openGroup;
          this.$refs.IMUI.changeOpenGroup(this.openGroup);
        },
 // 切换分组展开/收起状态
        toggleContact() {
          this.openContact = !this.openContact;
          this.$refs.IMUI.changeOpenContact(this.openContact);
        },
    handleOpenGroup(val){
      // console.log(val,'val')
    },
    handleChange(val) {
           this.activeNames=val
          },
    setQwUserInfo(){
      this.userData.id=this.qwUser.id;
      this.userData.displayName=this.qwUser.qwUserName;
      this.userData.avatar=this.qwUser.avatar;
    },
    getConversation(){
      const IMUI = this.$refs.IMUI;

      // 检查是否已有该企微账号的会话记录缓存
      if (this.qwUserSessions[this.appKey]) {
        // 如果有，直接使用缓存的会话记录
        this.conversationData = this.qwUserSessions[this.appKey];
        IMUI.initConversations(this.conversationData);

        // 恢复上次选中的会话
        const lastSelectedConversation = this.qwUserSessions[`${this.appKey}_selected`];
        if (lastSelectedConversation) {
          IMUI.changeContact(lastSelectedConversation);
        } else {
          // 如果没有上次选中的会话，选择第一个会话
          const fstConversation = this.conversationData[0];
          if(fstConversation) {
            IMUI.changeContact(fstConversation.conversationId);
          }
        }
      } else {
        // 如果没有缓存，则从服务器获取会话记录
        getConversations(this.qwUser.id,this.pageParams).then(response => {
          this.conversationData = response.data.list;

          // 缓存会话记录
          this.qwUserSessions[this.appKey] = response.data.list;

          IMUI.initConversations(response.data.list);
          const fstConversation = this.conversationData[0];
          if(fstConversation) {
            IMUI.changeContact(fstConversation.conversationId);
          }
        });
      }
    },
    messageTimeFormat(time) {
      return this.friendlyDate(time);
    },
    openDrawer(position) {
      const IMUI = this.$refs.IMUI;
      const params = {
        width: '30%',
        position,
        render: contact => {
          return (
            <div style="padding:15px">
              <h5>{contact.displayName}</h5>
            </div>
          );
        },
      };
      IMUI.changeDrawer(params);
    },
    handlePullMessages(contact, next,instance) {
      const { IMUI } = this.$refs;
      let isEnd = false;
      getMessageList(this.queryParams).then(response => {
        if(response.code==200){
          isEnd=response.data.isLastPage;
          console.log(isEnd,'isEnd')
          next(response.data.list, isEnd);
          if(!isEnd){
            this.qwUserPages[contact.conversationId]++;
            this.queryParams.pageNum=this.qwUserPages[contact.conversationId];
            this.queryParams.userId = this.qwUser.id
          }
        }
      });
    },
    handleChangeConversation(conversation, instance) {
      console.log(conversation,'conversation')
        this.showCourseManage=false
      if(conversation.isGroup){
        // this.contact.extId=conversation.extId
        this.showCourseManage=conversation.isGroup
      }
      // 保存当前选中的会话ID
      this.qwUserSessions[`${this.appKey}_selected`] = conversation.conversationId;

      // 检查是否已有该会话的分页信息
      if (!this.qwUserPages[conversation.conversationId]){
        this.qwUserPages[conversation.conversationId] =1;
      }

      this.queryParams.pageNum=this.qwUserPages[conversation.conversationId];
      this.queryParams.conversationId=conversation.conversationId;
      this.queryParams.userId = this.qwUser.id

      if(conversation.unread>0){
        conversation.unread=0;
        instance.updateContact(conversation);

        // 更新缓存中的会话记录
        this.updateSessionConversation(conversation);
      }
    },

    // 更新缓存中的会话记录
    updateSessionConversation(conversation) {
      if (this.qwUserSessions[this.appKey]) {
        const index = this.qwUserSessions[this.appKey].findIndex(
          item => item.conversationId === conversation.conversationId
        );
        if (index !== -1) {
          this.qwUserSessions[this.appKey][index] = {...conversation};
        }
      }
    },
    handleChangeContact(contact) {
      const IMUI = this.$refs.IMUI;
      console.log(contact,'contact')
      if(contact.conversationId==null){
        const data={
          id:contact.id,
          isGroup:contact.isGroup,
          qwUserId:this.qwUser.id,
        }
        getConversationId(data).then(response => {
          IMUI.appendConversation(response.data)
          IMUI.changeContact(contact.conversationId);
          IMUI.currentNewContactId=contact.id;
        });
      }
    },

    //收到消息后添加消息显示
    appendMessageAction(msgData){
      if(msgData.type=="text" || msgData.type=="image" || msgData.type=="voice"){     //文本   text  image  video  voice
        const message = {
          id: msgData.id,
          status: msgData.status,
          type: msgData.type,
          sendTime: msgData.sendTime,
          content: msgData.content,
          params1: "1",
          params2: "2",
          toContactId: msgData.toContactId,
          fromUser: msgData.fromUser,
        };
        this.appendRemoteMessage(message);
      }
      else if(msgData.type=="file"){
        const message = {
          id: msgData.id,
          status: msgData.status,
          type: msgData.type,
          sendTime: msgData.sendTime,
          content: msgData.content,
          toContactId: msgData.toContactId,
          fromUser: msgData.fromUser,
          fileName:msgData.fileName,
          fileSize:msgData.fileSize
        };
        this.appendRemoteMessage(message);
      }
      else{
        const message = {
          id: msgData.id,
          status: msgData.status,
          type: msgData.type,
          sendTime: msgData.sendTime,
          content: msgData.content,
          toContactId: msgData.toContactId,
          fromUser: msgData.fromUser,
        };
        this.appendRemoteMessage(message);
      }
    },
    //发送消息
    handleSend(message, next, file) {
      const IMUI = this.$refs.IMUI;
      let params = {};
      if(message.type === "text"){  //text   image   voice   video
        params = {"sessionId":message.toContactId,"appKey":this.qwUser.appKey,"content":message.content, "msgType": 1};
        sendMsg(params).then(response => {
          const {code, data} = response
          if(code === 200){
            this.appendRemoteMessage(data)
            let conversation = IMUI.findConversation(message.toContactId);
            conversation.lastSendTime = message.sendTime;
            conversation.lastContent = IMUI.lastContentRender(message)
            IMUI.topPopConversations(conversation);

            // 更新缓存中的会话记录
            this.updateSessionConversation(conversation);

            next();
          } else {
            next({status:'failed'})
          }
        });
      }
      // image
      else if(message.type === "image"){
        const formData = new FormData();
        formData.append("file", file);
        uploadOss(formData).then(response => {
          const {code, url} = response
          if (code === 200) {
            params = {"sessionId":message.toContactId,"appKey":this.qwUser.appKey,"content":url, "msgType": 2};
            sendMsg(params).then(response => {
              const {code} = response
              if(code === 200){
                let conversation = IMUI.findConversation(message.toContactId);
                conversation.lastSendTime = message.sendTime;
                conversation.lastContent = IMUI.lastContentRender(message)
                IMUI.topPopConversations(conversation);

                // 更新缓存中的会话记录
                this.updateSessionConversation(conversation);

                next();
              } else {
                next({status:'failed'})
              }
            });
          }
        })
      }
      // 小程序
      else if(message.type === "miniprogram"){
        // 小程序消息参数
        params = {
          "sessionId": message.toContactId,
          "appKey": this.qwUser.appKey,
          "title": message.title,
          "image": message.image,
          "content": message.content,
          "msgType": 5 // 小程序消息类型
        };
        sendMsg(params).then(response => {
          const {code, data} = response
          if(code === 200){
            this.appendRemoteMessage(data)
            let conversation = IMUI.findConversation(message.toContactId);
            conversation.lastSendTime = message.sendTime;
            conversation.lastContent = IMUI.lastContentRender(message)
            IMUI.topPopConversations(conversation);

            // 更新缓存中的会话记录
            this.updateSessionConversation(conversation);
          }
        });
      }
      // file
      else if(message.type === "file"){
        console.log("Event:file-click", message, next, file)
      }
    },
    handleMenuAvatarClick() {
      console.log("Event:menu-avatar-click");
    },
    //聊天工具栏点击图片
    handleImageClick() {
      // this.$refs.material.openMaterial(this.qwUser.deviceId);
      console.log("Event:handleImageClick");
    },
    //选择图片框确定按钮回调
    handlePickImageDone(data){
      console.log("handlePickImageDone:"+JSON.stringify(data));
      this.pickUploadImgData=data;
      const IMUI = this.$refs.IMUI;
      IMUI._handleRemoteImage(data.url);
    },
    tooglePlayVideo(data){
      this.dialogVideoVisible=true;
      this.dialogVideoUrl=data.content;
      this.dialogVideoCover=data.url;
      const player = this.$refs.player.instance
      player && player.play()
    },
    handleMessageClick(e, key, message, instance) {
      if (key === 'avatar') {
        this.qwUser.id !== message.fromUser.id && this.showDetail(message.extId)
        return
      }

      if(message.type=="image"){
        var url=!!message.url?message.url:message.content;
        this.handlePicturePreview(url);
      }
      else if(message.type=="video"){
        this.tooglePlayVideo(message);
      }
      else if(message.type=="file"){

      }
      if (key == "status") {
        instance.updateMessage({
          id: message.id,
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          instance.updateMessage({
            id: message.id,
            status: "succeed",
            content: "发送成功",
          });
        }, 2000);
      }
    },
    changeMenuAvatarVisible() {
      this.hideMenuAvatar = !this.hideMenuAvatar;
    },
    changeMenuVisible() {
      this.hideMenu = !this.hideMenu;
    },
    changeMessageNameVisible() {
      this.hideMessageName = !this.hideMessageName;
    },
    changeMessageTimeVisible() {
      this.hideMessageTime = !this.hideMessageTime;
    },
    removeMessage() {
      const { IMUI } = this.$refs;
      const messages = IMUI.getCurrentMessages();
      const id = messages[messages.length - 1].id;
      if (messages.length > 0) {
        IMUI.removeMessage(id);
      }
    },
    updateMessage() {
      const { IMUI } = this.$refs;
      const messages = IMUI.getCurrentMessages();
      const message = messages[messages.length - 1];
      if (messages.length > 0) {
        const update = {
          id: message.id,
          status: "succeed",
          type: "file",
          fileName: "被修改成文件了.txt",
          fileSize: "4200000",
        };
        if (message.type == "event") {
          update.fromUser = this.user;
        }
        IMUI.updateMessage(update);
        IMUI.messageViewToBottom();
      }
    },
    appendCustomMessage() {
      const { IMUI } = this.$refs;
      const message = {
        id: generateUUID(),
        status: "succeed",
        type: "voice",
        sendTime: getTime(),
        content: "语音消息",
        params1: "1",
        params2: "2",
        toContactId: "contact-1",
        fromUser: this.user,
      };
      IMUI.appendMessage(message, true);
    },
    appendMessage() {
      const { IMUI } = this.$refs;
      const contact = IMUI.currentContact;
      const message = generateMessage("contact-3");
      message.fromUser = {
        ...message.fromUser,
        ...this.user,
      };
      IMUI.appendMessage(message, true);
      console.log("🚀 ~ file: App.vue ~ line 1508 ~ appendMessage ~ message", message)
    },
    appendRemoteMessage(message) {  //从服务端返回的消息
      const { IMUI } = this.$refs;
      if (!IMUI) {
        console.error("IMUI引用不存在，无法添加消息");
        return;
      }

      try {
        // 确保消息对象包含必要的字段
        if (!message.id) {
          message.id = generateUUID(); // 使用UUID生成唯一ID
        }

        if (!message.status) {
          message.status = "succeed";
        }

        if (!message.sendTime) {
          message.sendTime = new Date().getTime();
        }

        // 根据消息类型处理
        switch (message.type) {
          case "text":
            // 文本消息不需要特殊处理
            break;
          case "image":
            // 确保图片消息有content或url字段
            if (!message.content && message.url) {
              message.content = message.url;
            }
            break;
          case "voice":
            // 确保语音消息有content字段
            if (!message.content) {
              message.content = "语音消息";
            }
            // 添加语音时长
            if (message.duration) {
              message.params1 = message.duration.toString();
            }
            break;
          case "file":
            // 确保文件消息有fileName和fileSize字段
            if (!message.fileName) {
              message.fileName = "未命名文件";
            }
            if (!message.fileSize && message.fileSize !== 0) {
              message.fileSize = 0;
            }
            break;
          case "miniprogram":
            // 小程序消息处理
            if (!message.content) {
              message.content = "小程序卡片";
            }
            break;
          default:
            console.warn("未知消息类型:", message.type);
            break;
        }

        // 添加消息到UI
        IMUI.appendMessage(message, true);

        // 更新缓存中的会话记录
        if (message.toContactId && IMUI.conversations) {
          const conversation = IMUI.findConversation(message.toContactId);
          if (conversation) {
            this.updateSessionConversation(conversation);
          }
        }
      } catch (error) {
        console.error("添加远程消息时出错:", error);
      }
    },
    handleChangeMenu() {
      console.log("Event:change-menu");
    },
    handlePicturePreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    // 详情
    showDetail(extId) {
      this.detail.open = true
      setTimeout(() => {
        this.$refs.userDetail.getDetail(extId);
      }, 1);
    },
    // 搜索
    handleSearch() {
      const keyword = this.searchKeyword.trim().toLowerCase();
      if (!keyword && !this.selectedFilters) {
        // 为空时显示全部
        this.$refs.IMUI.initConversations(this.conversationData);
        return;
      }

      const notRepeat = this.selectedFilters.some(item => item === '1')
      const notBlack = this.selectedFilters.some(item => item === '2')

      // 过滤会话列表
      const filtered = this.conversationData.filter(item => {
        // 搜索最后一条消息内容和联系人名
        return (
          (item.lastContent && item.lastContent.toLowerCase().includes(keyword)) ||
          (item.displayName && item.displayName.toLowerCase().includes(keyword))
        )
          && (notRepeat ? !item.isRepeat : true)
          && (notBlack ? !item.isBlack : true);
      });
      this.$refs.IMUI.initConversations(filtered);
    },
    applyFilter() {
      this.filterPopoverVisible = false;
      this.handleSearch();
    },
    // 刷新企微账号会话列表
    refreshSession(appKey, isCurrent = true) {
      // 删除当前企微账号的会话缓存
      delete this.qwUserSessions[appKey];
      delete this.qwUserSessions[`${appKey}_selected`];

      // 重新获取会话列表
      getConversations(this.qwUser.id,this.pageParams).then(response => {
        this.conversationData = response.data.list;

        // 缓存会话记录
        this.qwUserSessions[appKey] = response.data.list;

        if (isCurrent) {
          this.$refs.IMUI.initConversations(response.data.list);
          const fstConversation = this.conversationData[0];
          if(fstConversation) {
            this.$refs.IMUI.changeContact(fstConversation.conversationId);
          }
        }
      });
    },
    handleClose() {
      this.$emit('close')
    }
  },
};
</script>

<style lang="scss" scoped>
  .close-box{
    width: 100%;
    height: 52px;
    padding: 12px;
    background: #FFFFFF;
    // border-bottom: 1px solid #EDEFF2;
    display: flex;
    align-items: center;
    justify-content: right;
  }
  .qiwei{
    width: 90px;
    padding: 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items:center;
     position: relative;
     background: #409EFF;
    overflow-y: auto;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 和 Edge */
    position:relative;
    &::-webkit-scrollbar {
      display: none; /* 隐藏滚动条 */
    }
    .q-item{
      width: 72px;
      padding: 12px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
 transition: border-radius 0.2s ease, background 0.2s ease; /* 只过渡需要变化的属性 */
border-radius: 0 6px 6px 0;

      .el-avatar{
        width: 36px;
        height: 36px;
        border-radius: 4px 4px 4px 4px;
      }
      .name{
        margin-top: 10px;
        font-weight: 500;
        font-size: 14px;
        width: 72px;
            padding: 0 2px;
         white-space: nowrap; /* 强制文本不换行 */
          overflow: hidden;    /* 超出部分隐藏 */
          text-overflow: ellipsis; /* 超出部分显示省略号 */
        color: #fff;
        text-align: center;
}
      .text{
        margin-top: 2px;
        font-weight: 500;
        font-size: 14px;
        width: 72px;
            padding: 0 2px;
         white-space: nowrap; /* 强制文本不换行 */
          overflow: hidden;    /* 超出部分隐藏 */
          text-overflow: ellipsis; /* 超出部分显示省略号 */
        color: #fff;
        text-align: center;
      }
      &.active{
        background: #F1F4F8;
        border-radius: 6px;
        //border-radius: 6px 0px 0px 6px;
        position: relative; /* 确保z-index生效 */
          z-index: 1; /* 高于相邻元素的默认层级 */
        .name{
          color: #202124;
        }
        .text{
          color: #202124;
        }
        // &:before{
        //   content: '';
        //   position: absolute;
        //   z-index: 0;
        //   right: 0;
        //   width: 10px;
        //   height: auto;
        //   background: #F1F4F8;
        // }
      }
    }
    /* 下一个元素：仅保留右上圆角，清除默认的右下圆角 */
    // .q-item.active + .q-item {
    //   border-top-right-radius: 6px;
    //   border-bottom-right-radius: 0; /* 避免与选中元素底部衔接处的多余圆角 */
    // }
    // /* 上一个元素：仅保留右下圆角，清除默认的右上圆角 */
    // .q-item + .q-item.active {
    //   border-bottom-right-radius: 6px;
    //   border-top-right-radius: 0; /* 避免与选中元素顶部衔接处的多余圆角 */
    // }
  }
    .group-item{
      padding-left: 12px;
      padding-right: 12px;
      width: 100%;
      height: 45px;
      line-height: 45px;
      // padding-bottom: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      position: -webkit-sticky;
    top: 0px;
        z-index: 9;
        background-color: #fff;
      /* 箭头旋转动画 */
      .el-icon-arrow-right {
        transition: transform 0.3s ease;
        margin-right: 5px;
      }
      .el-icon-arrow-right.rotate {
        transform: rotate(90deg); /* 展开时箭头向右旋转90度（指向下方） */
      }
      .left{
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #141F36;
      }
      .num{
        font-weight: 400;
        font-size: 12px;
        color: #84868C;
      }
  }

  .user-name{
     font-weight: 500;
     font-size: 18px;
     color: #202124;
  }
.imui-center{
  align-items: center;
  justify-content: center;
}
.lemon-drawer{
  border:1px solid #ddd;
  border-left:0;
}
.more {
  font-size: 12px;
  line-height: 24px;
  height: 24px;
  position: absolute;
  top: 14px;
  right: 14px;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  color: #f1f1f1;
  display: inline-block;
  border-radius: 4px;
  background: #111;
  padding: 0 8px;
}

/deep/.el-dialog__headerbtn{
  top:10px;
}

::v-deep .im-tabs {
  width: 97%;
  .el-tabs__header {
    margin: 0 !important;
    .el-tabs__item {
      border-bottom: 0 !important;
    }
  }

  /* 未读消息徽标样式 */
  .el-badge__content {
    border: none;
    font-size: 12px;
    font-weight: bold;
    background-color: #F56C6C;
    transform: translateY(-2px);
    right: unset
  }
}
</style>


<style lang="stylus">
  // .el-popover{
  //       color: #409EFF !important;
  //     }

  .q-item{
    .el-badge{
      display: flex;
          flex-direction: column;
          align-items: center;
    }
    .el-badge__content {
      background-color:#FC4B0E !important;
      border: none !important;;
    }
}
.lemon-container__title{
  padding:12px !important;
  background: #fff !important;
}
.lemon-menu{
  width: 150px !important;
  flex-direction: row !important;
   background: #F1F4F8 !important;
  .lemon-avatar{
    width: 36px !important;
    height: 36px !important;
    line-height:36px !important;
    margin-bottom: 0 !important
  }

}
.lemon-menu-right{
  width:60px;
  height: 100%;
   display: flex;
   flex-direction: column;
   align-items: center;
   padding: 12px;
   .lemon-menu__item{
     padding:0 !important;
     margin-top: 12px;
     color:#666 !important;
   }
   .lemon-menu__item--active{
     color:#409EFF !important;
   }
}
.lemon-container{
  border-left: 1px solid #EDEFF2;
}
.lemon-editor__tool{
  box-shadow: none !important;
   border-top: 1px solid #EDEFF2;
}
.lemon-editor__tool-item{
  padding: 0px 10px 0 0 !important;
}
.lemon-container:empty {
  display: none;
}
.lemon-container div{
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 和 Edge */
}
/* Chrome、Safari 和 Opera */
.lemon-container div::-webkit-scrollbar {
  display: none;
}
.lemon-menu{
  padding: 0!important;
   // background-color:#409EFF !important;
}
.lemon-message-event__content{
  background: #F1F4F8 !important;
  color:#84868C !important;
}
.lemon-sidebar{
  width:228px !important;
  background: #fff !important;
}
.lemon-sidebar div::-webkit-scrollbar {
  display: none;
}
.lemon-contact{
  background: #fff !important;
}

.lemon-contact--active{
  background: #E9F1FE !important;
}
.lemon-editor{
  background: #fff !important;
}
.lemon-button--color-default{
  color: #fff !important;
      background: #409EFF !important;
}
.top-input .el-input__inner{
    border: none !important;
    background-color: #F1F4F8 !important;
  }
.slot-group{
  width:200px;
}

.slot-group-title{
  padding:0 0 10px 0;
}

.slot-group-notice{
  padding: 10px 10px;
}


.slot-search{
  width:calc(100% - 20px) ;
  margin:5px 10px;
  padding:3px 0px;
}


.slot-group-member{
  display: flex;
  padding: 5px 0;
  flex:1;
  font-size: 14px;
  align-items: center;
}

.avatar{
  width: 30px;
  height: 30px;
  line-height: 30px;
  margin-right:5px;
}

.img{
  vertical-align: middle;
  border-style: none;
  width: 100%;
  height: 100%;
  line-height: 30px;
  border-radius: 50%;
}




</style>
