<template>
    <div class="chat-bubble" @mousedown.stop @contextmenu.prevent>
        <div class="conversation-container">
            <ConversationSelectedList   @getList="getList"></ConversationSelectedList>
            <div class="conversation-list-btn">
                <span class="conversation-btn" @click="cancel">取消</span>
                <span class="conversation-btn" @click="messageRelay">发送</span>
            </div>
        </div>
    </div>
</template>

<script>
  import { mapState } from 'vuex'
  import ConversationSelectedList from '../../conversation/conversation-selected-list'
  import { getOpenIM } from '@/utils/openIM';
  export default {
    name: 'MessageBubble',
    components: {
      ConversationSelectedList
    },
    data() {
      return {
        OpenIM:null,
        isTimeout: false,
        showConversationList: false,
        selectedConversation: [],
        testMergerMessage: {}
      }
    },
    created() {
      this.OpenIM = getOpenIM();
    },
    mounted() {
      if (this.$refs.dropdown && this.$refs.dropdown.$el) {
        this.$refs.dropdown.$el.addEventListener('mousedown', this.handleDropDownMousedown)
      }
    },
    beforeDestroy() {
      if (this.$refs.dropdown && this.$refs.dropdown.$el) {
        this.$refs.dropdown.$el.removeEventListener('mousedown', this.handleDropDownMousedown)
      }
    },
    updated() {
    },
    computed: {
      ...mapState({
        isShowConversationList: state => state.conversation.isShowConversationList,
        selectedMessageList: state => state.conversation.selectedMessageList,
        relayType: state => state.conversation.relayType,
        relayMessage: state => state.conversation.relayMessage
      }),
    },
    methods: {
      cancel() {
        this.$store.commit('showConversationList', false)
      },
      getList(value) {
        this.selectedConversation = value

      },
      sendSingleMessage(to, type, message) {
        return this.OpenIM.createForwardMessage(message)
          .then(({ data }) => {
            console.log("创建转发消息成功111", data);
            this.$store.commit('pushCurrentMessageList', data);
            return data
          })
          .catch(({ errCode, errMsg }) => {
            console.error("创建转发消息失败", errCode, errMsg);
          });
      },
      mergerSort() {
        this.selectedMessageList.sort((a, b) =>  {
          if(a.time !== b.time) {
            return a.time - b.time
          }else {
            return a.sequence - b.sequence
          }
        })
      },
      updateConversationList(){
        this.OpenIM.getAllConversationList().then(({ data }) => {
            // 调用成功
            console.log(data,"147852")
            this.$store.commit('updateConversationList', data)
          })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          })
      },
      mergerMessage(to, type, messageList) {
        let _summaryList = [];
        const _count = this.selectedMessageList.length < 3 ? this.selectedMessageList.length : 3;
        for (let i = 0; i < _count; i++) {
          _summaryList.push(this.setAbstractList(this.selectedMessageList[i]));
        }

        /*const _title = this.selectedMessageList[0].conversationType === 'GROUP'
          ? '群聊的聊天记录'
          : `${this.selectedMessageList[0].senderNickname || this.selectedMessageList[0].from} 和 ${this.selectedMessageList[0].to} 的聊天记录`;*/
        const _title = "聊天记录"
        console.log("创建合并转发消息参数",this.selectedMessageList)
        return this.OpenIM.createMergerMessage({
          messageList: this.selectedMessageList,
          title: _title,
          summaryList: _summaryList
        })
          .then(({ data }) => {
            // 将返回的合并消息对象存入 Vuex 或其他状态管理
            this.$store.commit('pushCurrentMessageList', data);
            console.log("wwwwwwwwwww",data)
            return data;  // 返回创建的合并消息对象
          })
          .catch(({ errCode, errMsg }) => {
            console.error('合并消息创建失败:', errCode, errMsg);
            throw new Error(errMsg || '合并消息创建失败');
          });
      },

      async messageRelay() {

        let _type = '', _to = ''
        const myId = this.$store.getters.userID
        for (let item of this.selectedConversation) {
          if(item.startsWith("si")) {
            _type = 1
            _to = item.replace("si","").replace(myId,"").replaceAll("_","");
          }
          if(item.startsWith("sg")) {
            _type = 3
            _to = item.substring(5, item.length)
          }
          // 排序
          console.log(this.$store.state.conversation,"||||")
          this.mergerSort()
          if (this.relayType === 1) {
            this.relayMessage.recvID = _to
            let message =await this.sendSingleMessage(_to, _type, this.relayMessage)
            console.log(message,"message")
            this.sendMessageHandler(message)
          }

          if (this.relayType === 2) {
            if(this.selectedMessageList.length > 30) {
              this.$store.commit('showMessage', {
                message: '转发消息仅支持30条以内',
                type: 'error'
              })
              return
            }

            for (let selectedMessage of this.selectedMessageList) {
              console.log("selectedMessage",selectedMessage)
              selectedMessage.recvID = _to
              let message = await this.sendSingleMessage(_to, _type, selectedMessage)
              console.log("转发类型",message)
              const sendText={
                message:message,
                recvID:message.recvID,
                groupID:"",
                offlinePushInfo : {
                  title:message.senderNickname,
                  desc:this.setAbstractList(message),
                  iOSPushSound:"",
                  iOSBadgeCount:true,
                  operatorUserID:"",
                  ex:""
                }
              }
              console.log("this.OpenIM",this.OpenIM)
              await this.OpenIM.sendMessage(sendText)
                .then((res) => {
                  return res
                })
                .catch(error => {
                  this.$store.commit('showMessage', {
                    type: 'error',
                    message: error.message
                  })
                })

            }
          }
          if (this.relayType === 3) {
            let message =await this.mergerMessage(_to, _type,this.selectedMessageList)

            message.recvID = _to
            console.log("wwwwwwwwwwwwwwwwww",message)
            this.sendMessageHandler(message)
          }
        }
        this.$store.commit('showConversationList', false)
        this.$store.commit('resetSelectedMessage', false)
      },

      sendMessageHandler(message) {
        console.log("this.OpenIM111",message)
        const sendText={
          message:message,
          recvID:message.recvID,
          groupID:"",
          offlinePushInfo : {
            title:message.senderNickname,
            desc:this.setAbstractList(message),
            iOSPushSound:"",
            iOSBadgeCount:true,
            operatorUserID:"",
            ex:""
          }
        }
        this.OpenIM.sendMessage(sendText).then(({ data }) => {
          const msgList = Array.isArray(data) ? data : [data];
          this.$store.commit('pushCurrentMessageList', msgList)
          this.updateConversationList()
          this.$bus.$emit('scroll-bottom')
        }).catch(({ errCode, errMsg }) => {
          // 调用失败
          this.$store.commit('showMessage', {
            message: errMsg.message,
            type: 'error'
          })
        });
      },
      setAbstractList(message) {
        console.log(message,"message1111111111111111111111")
        let nickname = message.senderNickname || message.from
        let text = ''
        switch (message.contentType) {
          case 101:
            text = message.textElem.content || ''
            if (text.length > 20) {
              text = text.slice(0, 20)
            }
            return `${nickname}: ${text}`
          case 107:
            return `${nickname}: [聊天记录]`
          case 102:
            return `${nickname}: [图片]`
          case 103:
            return `${nickname}: [音频]`
          case 104:
            return `${nickname}: [视频]`
          case 110:
            return `${nickname}: [自定义消息]`
          case 105:
            return `${nickname}: [文件]`
          case 115:
            return `${nickname}: [动画表情]`
        }
      },
      handleDropDownMousedown(e) {
        if (e.buttons === 2) {
          if (this.$refs.dropdown.visible) {
            this.$refs.dropdown.hide()
          } else {
            this.$refs.dropdown.show()
          }
        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
    .conversation-container {
        position absolute
        top 0
        left 0
        right 0
        width 80%
        margin auto
        background-color #fff
        z-index 999
    }
    .conversation-list-btn {
        width 140px
        display flex
        float right
        margin 10px 0
        .conversation-btn {
            cursor pointer
            padding 6px 12px
            background #00A4FF
            color #ffffff
            font-size 14px
            border-radius 20px
            margin-left 13px
        }
    }
</style>
