<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"
        :label="item.qwUserId"
        :name="item.appKey"/>
    </el-tabs>

    <div class="imui-center qq-lemon-imui" v-show="showQW">
      <lemon-imui  class="lemon-slot"
                   :width="isMaximized ? '100vw' : windowWidth"
                   :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 #sidebar-message-top>
          <div style="padding: 8px;">
            <el-input
              v-model="searchKeyword"
              prefix-icon="el-icon-search"
              placeholder="搜索"
              size="small"
              clearable
              @input="handleSearch"
              style="width: 100%;"
            />
          </div>
        </template>
        <template #message-title>
<!--          <div @click="openDrawer('right')" style="position: absolute;right: 14px;top: 10px;">-->
<!--            <i class="el-icon-more" style="cursor: pointer"/>-->
<!--          </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} 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 {ImSocket} from "@/utils/ImSocket";
import {getToken} from '@/utils/auth'
import {uploadOss} from "@/api/common";
import {mapState} from "vuex";
import {generateUUID} from "@/components/LemonUI/utils";

let pages = {};
export default {
  name: "qqChat",
  components: {
    VideoPlayer,
    UserDetail
  },
  props: {
    showQw: Boolean,
    isMaximized: Boolean
  },
  data() {
    return {
      contactName:'',
      appKey: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.6,  //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight*0.7,   //实时屏幕高度
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conversationId: null,
        userId:null
      },
      detail: {
        title: '',
        open: false
      },
      imSocket: null,
      imUrl: process.env.VUE_APP_IM_WS_URL,
      searchKeyword: '',
    };
  },
  created(){
    //获取企微列表
    getQwUserList().then(response => {
      this.qwUserList = response.data;
      if (this.qwUserList.length>0){
        this.qwUser = this.qwUserList[0];
        this.appKey = this.qwUser.appKey;
        this.setQwUserInfo();
        this.getConversation();
        this.initImSocket(this.qwUser.companyId)
      }else {
        this.qwUser={};
      }
    });
  },
  computed: {
    ...mapState('qwIm', ['shareCourse'])
  },
  watch: {
    showQw(nv, ov) {
      if (nv) {
        this.$nextTick(() => {
          this.$refs.IMUI.messageViewToBottom();
        });
      }
    },
    shareCourse(nv) {
      if (nv) {
        console.log('shareCourse', nv)
        // 发送小程序卡片消息
        const IMUI = this.$refs.IMUI;
        const contact = IMUI.currentContact;
        if (!contact) {
          return;
        }

        // 创建消息对象
        let message = {
          id: generateUUID(),
          status: 'going',
          type: 'miniprogram',
          sendTime: Date.now(),
          content: {
            appid: nv.miniprogramAppid,
            pagepath: nv.miniprogramPage,
            title: nv.miniprogramTitle,
            thumbnail: nv.miniprogramPicUrl
          },
          toContactId: contact.conversationId,
          fromUser: {
            id: this.qwUser.id,
            displayName: this.qwUser.qwUserName,
            avatar: "https://cos.his.cdwjyyh.com/fs/20241231/22a765a96da247d1b83ea94fef438a41.png"
          },
        };

        this.detail.open = false
        this.$store.dispatch('qwIm/shareCourse', null)

        this.appendRemoteMessage(message)
        // 使用handleSend方法发送消息
        this.handleSend(
          message,
          (replaceMessage = { status: "succeed" }) => {
            IMUI.updateMessage(Object.assign(message, replaceMessage));
          },
          null
        );
      }
    }
  },
  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",
      }
    ]);
    IMUI.initEmoji(EmojiData);
    IMUI.initEditorTools([
      { name: "emoji" },
      { name: "uploadImage" }
    ])
  },
  beforeDestroy() {
    if (this.imSocket) {
      this.imSocket.close();
    }
  },
  methods: {
    initImSocket(companyId) {
      this.imSocket = new ImSocket(`${this.imUrl}/${companyId}?token=${getToken()}`);
      this.imSocket.onMessage(data => {
        const { IMUI } = this.$refs;
        let message = JSON.parse(data);
        this.appendRemoteMessage(message)

        let conversation = IMUI.findConversation(message.toContactId);
        if (conversation.msgId) {
          conversation.lastSendTime = message.sendTime;
          conversation.lastContent = IMUI.lastContentRender(message)//message.content;
          IMUI.topPopConversations(conversation);
        }
      })
    },
    // 切换企微账号
    qwUserChange(tab, event){
      this.appKey = tab.name;
      let index= this.qwUserList.findIndex(item => item.appKey === tab.name);
      this.qwUser=this.qwUserList[index];
      this.getConversation();   //获取会话信息
      this.setQwUserInfo();
    },
    setQwUserInfo(){
      this.userData.id=this.qwUser.id;
      this.userData.displayName=this.qwUser.qwUserName;
      this.userData.avatar="https://cos.his.cdwjyyh.com/fs/20241231/22a765a96da247d1b83ea94fef438a41.png";
    },
    getConversation(){
      const IMUI = this.$refs.IMUI;
      getConversations(this.qwUser.id).then(response => {
        this.conversationData = response.data;
        IMUI.initConversations(response.data);
        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;
          next(response.data.list, isEnd);
          if(!isEnd){
            pages[contact.conversationId]++;
            this.queryParams.pageNum=pages[contact.conversationId];
            this.queryParams.userId = this.qwUser.id
          }
        }
      });
    },
    handleChangeConversation(conversation, instance) {
      if (!pages[conversation.conversationId]){
        pages[conversation.conversationId] =1;
      }
      this.queryParams.pageNum=pages[conversation.conversationId];
      this.queryParams.conversationId=conversation.conversationId;
      this.queryParams.userId = this.qwUser.id
      if(conversation.unread>0){
        conversation.unread=0;
        instance.updateContact(conversation);
      }
    },
    handleChangeContact(contact, instance) {
      console.log("ChangeContact:", contact, instance)
    },

    //收到消息后添加消息显示
    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 = message.content;
            IMUI.topPopConversations(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 = message.content;
                IMUI.topPopConversations(conversation);
                next();
              } else {
                next({status:'failed'})
              }
            });
          }
        })
      }
      // 小程序
      else if(message.type === "miniprogram"){
        // 小程序消息参数
        params = {
          "sessionId": message.toContactId,
          "appKey": this.qwUser.appKey,
          "content": JSON.stringify(message.content),
          "msgType": 5 // 小程序消息类型
        };
        sendMsg(params).then(response => {
          const {code} = response
          if(code === 200){
            let conversation = IMUI.findConversation(message.toContactId);
            conversation.lastSendTime = message.sendTime;
            conversation.lastContent = "小程序";
            IMUI.topPopConversations(conversation);
            next && next();
          } else {
            next && next({status:'failed'})
          }
        });
      }
      // 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: generateRandId(),
        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;
      IMUI.appendMessage(message, true);
    },
    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.$refs.IMUI.initConversations(this.conversationData);
        return;
      }
      // 过滤会话列表
      const filtered = this.conversationData.filter(item => {
        // 搜索最后一条消息内容和联系人名
        return (
          (item.lastContent && item.lastContent.toLowerCase().includes(keyword)) ||
          (item.displayName && item.displayName.toLowerCase().includes(keyword))
        );
      });
      this.$refs.IMUI.initConversations(filtered);
    },
  },
};
</script>

<style lang="scss" scoped>
.imui-center{
  align-items: center;
  justify-content: center;
}
.lemon-wrapper{
  border:1px solid #ddd;
  //height: !important;
}
.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;
}

/deep/.el-dialog:not(.is-fullscreen) {
  margin-top: 0 !important;
}

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

</style>


<style lang="stylus">
.lemon-container__title{
  padding-bottom:10px;
}
.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>
