<template>
  <div v-show="this.messageShow" class="popoverContainer">
    <!--el-popover 与tooltip类似，可在default插槽内 添加其他元素  -->
    <el-popover popper-class="popoverContainer" placement="left" trigger="click" width="700" v-model="popUpFlag"
                @after-enter="handlePopUpFlag" @after-leave="handlePopUpFlag">
      <template #default>
        <Row style="width: 100%;max-height: 600px;
        min-height: 500px;
        box-shadow: 0 2px 17px 0 rgba(0, 0, 0, 0.2);
  background-color: rgba(255, 255, 255, 1);
  border-radius: 6px;">
          <Col :span="8" class="chatList" @mouseout="mouseHandle">
            <Row>
              <Col :span="24">
                <CustomForm :value="queryParams">
                  <CustomInput class="popoverInput"
                               prefix="el-icon-search"
                               :sm-span="24"
                               :lg-span="24"
                               :md-span="24"
                               :xs-span="24"
                               :span="24" prop="chatName" @input="queryChatRoom"/>
                </CustomForm>
              </Col>
            </Row>
            <Row class="chatRooms">
              <Col v-for="item in chatRooms" style="cursor: pointer" @click="toActive(item)"
                   @mouseover="mouseHandle(item)"
                   :class="item.id===activeChatRoom.id?'active':'noActive'">
                <Row>
                  <Col :span="6">
                    <el-badge is-dot :hidden="!item.hasUnReadMessage" class="newMessage">
                      <el-image style="width: 40px;height: 40px;" :src="require('../../assets/images/from.png')"/>
                    </el-badge>
                  </Col>
                  <Col :span="18" style="padding-left: 5px">
                    <Row>
                      <Col class="chatName" :span="24">
                        {{ item.chatName }}
                      </Col>
                      <Col class="chatTime" :span="24">
                        {{
                          !isBlank(item.maxUnReadMessageTime) ?
                            (judgeIsBeforeNow(item.createTime) ? item.maxUnReadMessageTime : parseTime(item.maxUnReadMessageTime, '{h}:{i}:{s}')) : ''
                        }}
                      </Col>


                    </Row>
                  </Col>

                  <div class="mark" v-show="showMarkItem&& showMarkItem.id===item.id" @click.stop="handleDelete(item)">
                    <i CLASS="el-icon-close"/>
                  </div>
                </Row>

              </Col>
            </Row>
          </Col>
          <Col :span="16" class="messageView">
            <Row>
              <Col :span="24"
                   style="background-color: rgba(242, 243, 244, 1);
                   border-radius: 0 6px 0 0;
                   height: 40px; display: flex;
                   align-items: center;">
                <span v-if="chatRooms.length>0" class="activeRoomName">{{ activeChatRoom.chatName }}</span>
              </Col>
              <Col v-if="messageList&&messageList.length>0" ref="messageList" id="messageList" :span="24"
                   style="max-height: 260px;min-height:220px;overflow-y: scroll;overflow-x: hidden">
                <Row v-loading="messageLoad">
                  <Col class="record-wrapper" :span="24" v-for="item in messageList">
                    <!--聊天时间-->
                    <div class="time">{{
                        judgeIsBeforeNow(item.createTime) ? item.createTime : parseTime(item.createTime, '{h}:{i}:{s}')
                      }}
                    </div>
                    <!--          自己-->
                    <div v-if="item.sendUserId == userId" class="msg msg-right">
                      <div class="msg-right-content">
                        <span class="nickName">{{ item.nickName }}</span>
                        <div class="message-wrapper-right">
                          <div class="message-right" v-if="item.messageType==='0'">
                            <span>{{ item.messageContent }}</span>
                          </div>
                          <div class="message-right-img" v-if="item.messageType==='1'" v-html="item.messageContent"
                               @click="handleContentClick(item)"></div>
                        </div>
                      </div>

                      <!--                      <div class="message-wrapper-right-img">-->
                      <!--                        <img style="width: 40px;height:40px;border-radius: 20px" :src="avatar"/>-->
                      <!--                      </div>-->
                    </div>

                    <!--他人-->
                    <div v-else class="msg msg-left">
                      <!--                      <div class="img-wrapper">-->
                      <!--                        <img style="width: 40px;height:40px;border-radius: 20px"-->
                      <!--                             :src="isBlank(item.avatar)?avatar: avatarPrefix+item.avatar"/>-->
                      <!--                      </div>-->
                      <div>
                        <span class="nickName">{{ item.nickName }}</span>
                        <div class="message-wrapper-left">
                          <div class="message-left" v-if="item.messageType==='0'">
                            <span>{{ item.messageContent }}</span>
                          </div>
                          <div class="message-left-img" v-if="item.messageType==='1'" v-html="item.messageContent"
                               @click="handleContentClick(item)"></div>
                        </div>
                      </div>

                    </div>

                  </Col>
                </Row>
                <Row>

                </Row>
              </Col>
              <Col v-else :span="24" style="height: 260px;">
                <div style="width: 100%;height: 100%;background: #FFFFFF"/>
              </Col>

              <Col :span="24" style="margin-top: 5%">
                <ChatInput :lg-span="24" :xs-span="24" :md-span="24" :sm-span="24"
                           :value="sendMessageInfo.messageContent" @input="val=>sendMessageInfo.messageContent=val"
                           @ChatInput="appendClick"></ChatInput>
              </Col>

            </Row>

          </Col>
        </Row>


      </template>
      <!-- slot=reference 不能被替换 此处为弹出框实际可见部分，点击后 展示上面 default插槽内的部分 -->
      <!-- 通过draggable="true" 开启元素可拖拽，然后通过三个事件，实现拖拽后位置变化 -->
      <div ref="draggable" class="floating-component" draggable="true"
           slot="reference"

           @dragstart="dragstart($event)"
           @dragenter="dragenter($event)"
           @dragend="dragend($event)"
           :style="draggStyle">
        <!--    悬浮内容-->
        <span>
                <el-badge :value="totalQty" :max="max" :hidden="totalQty===0">
                <el-image class="label_1" referrerpolicy="no-referrer" style="margin-top: 5px"
                          :src=" require('../../assets/images/liaotianshi.svg')"/>
                </el-badge>
            </span>
      </div>
    </el-popover>
  </div>
</template>

<script>
import {isBlank} from "@/utils";
import Row from "../CustomElement/layout/Row.vue";
import Col from "../CustomElement/layout/Col.vue";
import CustomForm from "../CustomElement/CustomForm/CustomForm.vue";
import CustomInput from "../CustomElement/CustomForm/items/CustomInput.vue";
import {getChatRoomByQuery, getUnReadTotal, readChatMessage, tosendInputMessage} from "@/api/common/MessageChat";
import ChatInput from "../CustomElement/ChatInput.vue";
import {getPageMessageChatContent} from "@/api/common/MessageChatContent";
import {judgeIsBeforeNow, parseTime} from "@/utils/dateUtils";
import {mapGetters} from "vuex";
import {initFuncRegpx} from "@/utils/formula";
import {messageChatUserDelete} from "@/api/common/MessageChatUser";

export default {
  props: {
    icon: {
      type: String,
      default: "el-icon-chat-dot-square"
    },
    /*
    * 角标可展示的最大数字
    */
    max: {
      type: Number,
      default: 99,
    },
    size: {
      type: String,
      default: "medium"
    },
  },
  name: "FloatingComponent",
  components: {ChatInput, CustomInput, CustomForm, Col, Row},
  data: function () {
    return {
      userId: this.$store.getters.userId,
      deviceNum: 0,
      drugNum: 0,
      goodsNum: 0,
      totalQty: 0,
      popUpFlag: false,
      startX: 0,
      startY: 0,
      // 父元素的宽-自适应值
      initWidth: 0,
      // 父元素的高-自适应值
      initHeight: 0,
      // 元素拖拽前距离浏览器的X轴位置
      startclientX: 0,
      //元素拖拽前距离浏览器的Y轴位置
      startclientY: 0,
      // 元素的左偏移量
      elLeft: 20,
      // 元素的右偏移量
      elTop: 52,
      messageShow: true,
      messageLoad: false,
      messageList: [],
      chatRooms: [],
      showMarkItem: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      sendMessageInfo: {
        messageContent: "",
      },
      activeChatRoom: {},
      activeScrollTop: 0,
      avatarPrefix: process.env.VUE_APP_BASE_API,
      firstEnter: 0,

    };
  },
  computed: {
    draggStyle() {
      return {
        right: this.elLeft + 'px',
        bottom: this.elTop + 'px',
      }
    },
    ...mapGetters([
      'avatar'
    ]),

  },
  watch: {},
  methods: {
    judgeIsBeforeNow,
    parseTime,
    // isBlank 内部判断  obj === null || obj === undefined || obj === "";
    isBlank,
    handleClick() {
      this.popUpFlag = !this.popUpFlag;
    },

    // 页面初始化
    initBodySize() {
      // 拿到父元素宽
      this.initWidth = this.$parent.$el.clientWidth;
      // 根据宽计算高实现自适应(80 =30+50 面包屑+tag标签高度)
      this.initHeight = this.$parent.$el.offsetHeight;

    },
    // 拖拽开始事件
    dragstart(e) {
      this.popUpFlag = false
      this.startclientX = e.clientX; // 记录拖拽元素初始位置
      this.startclientY = e.clientY;
      e.dataTransfer.effectAllowed = "move";
    },
    //拖拽中
    dragenter(e) {
      e.dataTransfer.effectAllowed = "move";
    },
    // 拖拽完成事件
    dragend(e) {
      // 计算偏移量
      let x = e.clientX - this.startclientX;
      let y = e.clientY - this.startclientY;
      // 实现拖拽元素随偏移量移动
      this.elLeft -= x;
      this.elTop -= y;
      if (this.elLeft <= 0 || this.elTop <= 0) {
        this.elLeft = 20;
        this.elTop = 52;
      }
      if (this.elLeft >= this.initWidth - 70) {
        this.elLeft = 20;
        this.elTop = 52;
      }
      if (this.elTop >= (this.initHeight - 70)) {
        this.elLeft = 20;
        this.elTop = 52;
      }
    },

    queryChatRoom() {
      getChatRoomByQuery(this.queryParams).then(async res => {
        if (200 === res.code) {
          this.chatRooms = res.data;
          this.activeChatRoom = this.chatRooms.find(item => item.active === '0') || this.chatRooms[0];
          if (this.activeChatRoom) {
            this.messageList = this.activeChatRoom.chatContentList;
          }
          if (res.data && res.data.length === 0) {
            this.messageList = [];
          }
          let ress = await getUnReadTotal();
          this.totalQty = ress.data;
        }
      })


    },
    appendClick() {
      if (isBlank(this.activeChatRoom) || isBlank(this.activeChatRoom.id)) {
        this.$message.error(this.$t('chatRoom.needRoom'));
        return
      }
      if (isBlank(this.sendMessageInfo.messageContent) || this.sendMessageInfo.messageContent === "br") {
        this.$message.error(this.$t('chatRoom.needMsg'));
        return;
      }
      let row = {
        id: this.activeChatRoom.id,
        quotationId: this.activeChatRoom.quotationId,
        quotationNo: this.activeChatRoom.quotationNo,
        currentActiveContent: {
          messageType: "0",
          messageContent: this.sendMessageInfo.messageContent
            .replaceAll("<img", "<img style=\"max-width:50px;height:40px \" ")
            .replaceAll("<p>", "")
            .replaceAll("</p>", "")
        },
        currentActiveContentList: [],
      }
      let matches = [row.currentActiveContent.messageContent]
      if (row.currentActiveContent.messageContent.includes("<img style=")) {
        const regex = /(\b\d+\b|[^<]*<img[^>]*>|[^<>\s]+)/g;
        matches = row.currentActiveContent.messageContent.match(regex);
      }
      let contetnArray = []
      let regex = initFuncRegpx("<br>")

      for (let item of matches) {
        let str = item;
        while (str.indexOf("<br>") > -1) {
          str = str.replace("<br>", "")
        }

        if (str === 'br' || str === '<br>') {
          continue
        }
        if (str.trim() === '') {
          this.$set(this.sendMessageInfo, 'messageContent', '')
          this.$modal.msgError("请勿输入空白信息");
          return;
        }
        contetnArray.push({
          messageType: str.includes("<img") ? "1" : "0",
          messageContent: str.replaceAll("&lt;", "<").replaceAll("&gt;", ">")
            .replaceAll("&amp;", "&")
        })
      }

      if (contetnArray.length === 0) {
        this.$set(this.sendMessageInfo, 'messageContent', '')
        this.$message.error(this.$t('chatRoom.needMsg'));
        return;
      }
      row.currentActiveContentList = contetnArray;
      tosendInputMessage(row).then(async res => {
        if (res && res.code === 200) {
          this.$set(this.sendMessageInfo, 'messageContent', '')
          let unreadRes = await readChatMessage(this.activeChatRoom);
          this.totalQty = unreadRes.data;
          await this.handleQueryContentList(this.activeChatRoom);
        }
      }).finally(() => {
        this.$nextTick(() => {
          const div = document.getElementById('messageList')
          if (div) {
            div.scrollTop = div.scrollHeight
          }
        })
      })
    },
    handleQueryContentList(activeChatRoom) {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.messageChatId = activeChatRoom.id;
      this.messageLoad = true;
      getPageMessageChatContent(this.queryParams).then(res => {
        if (res && res.code === 200) {
          this.messageList = res.rows || [];
          this.queryParams.total = res.total;
        }
      }).finally(() => {
        this.$nextTick(() => {
          const div = document.getElementById('messageList')
          if (this.firstEnter===0) {
            this.activeScrollTop = div.scrollHeight;
          }
          console.log(this.firstEnter)
          console.log(this.activeScrollTop)
          console.log(div.scrollHeight)


          if (div) {
            div.scrollTop =this.firstEnter===0?  this.activeScrollTop:div.scrollHeight
          }
        })
        this.messageLoad = false;
      })
    },
    mouseHandle(item) {

      if (item) {
        this.showMarkItem = {...item};
      } else {
        this.showMarkItem = {}
      }
    },
    handleDelete(item) {
      messageChatUserDelete({
        messageChatId: item.id
      }).then(res => {
        if (res && res.code === 200) {
          this.totalQty = res.data;
          this.queryChatRoom();
        }
      })
    },


    async toActive(item) {
      this.activeChatRoom = item;
      this.activeChatRoom.hasUnReadMessage = false;
      let res = await readChatMessage(item);
      this.totalQty = res.data;

      this.handleQueryContentList(item);
    },
    loadMoreMessageList() {
      //如果 已经查询到之前的所有讯息 则不加载
      let {pageNum, pageSize, total} = this.queryParams;
      if (pageNum * pageSize >= total) {
        return;
      }
      this.queryParams.pageNum++;
      this.queryParams.messageChatId = this.activeChatRoom.id;
      this.messageLoad = true;
      getPageMessageChatContent(this.queryParams).then(res => {
        if (res && res.code === 200) {
          if (res.rows && res.rows.length > 0 && res.total > 10) {
            this.messageList.unshift(...res.rows);
            this.queryParams.total = res.total;
          }

        }
      }).finally(() => {
        this.messageLoad = false;
      })
    },

    // 消息记录点击
    handleContentClick(content) {
      if (!isBlank(content.messageContent)) {
        if (content.messageContent.includes("<img")) {
          //取出图片地址
          let imgSrc = content.messageContent.match(/src="(.*?)"/)[1];
          this.$parent.messagePreview(imgSrc);
        }
      }

    },
    scrollHandle(event) {
      let scrollTop = event.target.scrollTop;
      let scrollableDiv = event.target;
      this.activeScrollTop = scrollTop;

      //滚动到顶部触发查询
      if (scrollTop === 0) {
        this.loadMoreMessageList();
      } else if (scrollableDiv.scrollTop + scrollableDiv.clientHeight >= scrollableDiv.scrollHeight) {
        // 滚动到底部
        // 执行加载最新的十条记录
        if (this.chatRooms.length > 0) {
          this.handleQueryContentList(this.activeChatRoom);
        }
      }
    },
    handlePopUpFlag() {
      let that = this;
      if (this.popUpFlag) {
        setTimeout(() => {
          const scroll = document.getElementById('messageList');
          if (scroll) {
            scroll.addEventListener('scroll', that.scrollHandle, true);
            //如果是第一次进入，则滚动至底部
            if(that.firstEnter===0){
              scroll.scrollTo({
                top: scroll.scrollHeight,
                behavior: 'smooth'
              })
            }else {
              scroll.scrollTo({
                top: that.activeScrollTop,
                behavior: 'smooth'
              })
            }
            this.firstEnter++;
          }
        }, 200)


      } else {
        this.$set(this.queryParams, 'chatName', null)
      }


    }

  },


  created() {

  },
  mounted() {
    //下面两个监听，用于监听 store中 SSEMessage 消息体的变化，从而实现元素的重新渲染，主要复写第二个function (val, oldVal)
    this.$watch(
      function () {
        return this.$store.state.selections.SSEChatMessage
      },
      async function (val, oldVal) {
        //如果有过滤条件则不渲染
        if (!isBlank(this.queryParams.chatName)) {
          this.queryChatRoom();
          return;
        }
        if (val && val.chatRooms && val.chatRooms.length > 0) {
          this.chatRooms = val.chatRooms
          this.totalQty = val.chatRoomsTotal;
          this.activeChatRoom = this.chatRooms.find(item => item.active === '0') || this.chatRooms[0];
          if (this.activeChatRoom) {
            this.messageList = this.activeChatRoom.chatContentList;

          }
          await this.handleQueryContentList(this.activeChatRoom);
          this.messageShow = true
          this.totalQty = isNaN(Number(val.chatRoomsTotal)) ? 0 : Number(val.chatRoomsTotal);
          // 是否弹出消息列表
          this.popUpFlag = val.popUpFlag
        }
      },
      {
        immediate: true,
        deep: true,
      }
    );
    this.initBodySize();
  },
}
</script>

<style>
.popoverContainer {
  background: rgb(255, 255, 255, 0) !important;
  padding: 0 !important;
  border: 0 !important;
}

</style>

<style scoped>


.floating-component {
  cursor: pointer;
  box-shadow: 0 2px 9px 10px rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 1);
  border-radius: 50%;
  position: fixed;
  right: 20px;
  bottom: 40px;
  width: 68px;
  height: 68px;
  z-index: 1000;
  display: grid;
  align-content: center;
  justify-content: center;
}

.label_1 {
  width: 34px;
  height: 32px;
}

</style>

<style lang="scss" scoped>
::v-deep .el-popover {
  padding: 0 !important;
  border: 0 !important;
  background: rgb(255, 255, 255, 0);
}

.newMessage {
  ::v-deep .el-badge__content {
    top: 3px;
  }

}


.record-wrapper {
  margin: 4px;
  padding: 4px;
}

.time {
  text-align: center;
}

.chatList {
  background-color: #F6F7F8;
  border-radius: 6px;
  border-right: 1px solid #E5E6E8;
  padding: 1%;
  min-height: 500px;

  .chatRooms {
    max-height: 500px;
    overflow-y: scroll;
    overflow-x: hidden;

    .active {
      background-color: #fff;

    }

    .noActive {
      background-color: #F6F7F8;
    }

    .noActive :hover {
      background-color: #FFF6F6;
    }

    .mark {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      right: 0;
      width: 20%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.1) !important;
      z-index: 2024;

      .el-icon-close {
        background-color: rgba(0, 0, 0, 0) !important;
      }
    }

  }

  .chatName {
    height: 20px;
    overflow-wrap: break-word;
    color: rgba(0, 0, 0, 0.85);
    font-size: 13px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    text-align: left;
    white-space: nowrap;
    line-height: 20px;
  }

  .chatTime {
    height: 14px;
    overflow-wrap: break-word;
    color: rgba(107, 118, 136, 1);
    font-size: 10px;
    font-weight: normal;
    white-space: nowrap;
    line-height: 14px;
    margin-top: 3px;
  }
}


.msg-right {
  flex-direction: row;
  justify-content: flex-end;
  padding-right: 2%;

  .msg-right-content {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .nickName {
      color: rgba(107, 118, 136, 1);
      font-size: 12px;
      font-weight: normal;
      margin-right: 8px;
    }
  }

}

.msg-left {
  .nickName {
    color: rgba(107, 118, 136, 1);
    font-size: 12px;
    font-weight: normal;
    margin-left: 8px;
  }
}

.msg {
  display: flex;

  .message-wrapper-left {
    background-color: rgba(246, 247, 248, 1);
    border-radius: 4px;
    max-width: 230px;
    margin: 0 0 0 8px;
    padding: 8px;
    justify-content: center;

    .message-left {
      display: flex;
      align-items: center;
      word-wrap: break-word; //英文换行
      height: 100%;
      width: 100%;
      overflow-wrap: break-word;
      color: rgba(0, 0, 0, 1);
      font-size: 14px;
      font-weight: normal;
      text-align: left;
      white-space: pre-wrap;
      line-height: 20px;
      margin-left: 2%;
    }

    .message-left-img {
      width: 50px;
      height: 100%;
      cursor: pointer;
      align-items: center;
      display: flex;
      padding: 5%;
      justify-content: center;
    }
  }


  .message-wrapper-right {
    max-width: 230px;
    background-color: rgba(241, 25, 83, 1);
    border-radius: 4px;
    margin: 0 8px 0 8px;
    padding: 8px;
    justify-content: center;

    .message-right {
      display: flex;
      height: 100%;
      width: 100%;
      align-items: center;
      color: rgba(255, 255, 255, 1);
      font-size: 14px;
      font-weight: normal;
      text-align: left;
      line-height: 20px;
      margin-left: 2%;
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    .message-right-img {
      width: 50px;
      height: 100%;
      cursor: pointer;
      align-items: center;
      display: flex;
      padding: 5%;
      justify-content: center;
    }
  }


}


.img {
  flex: auto;
  height: 36px;
  width: 36px;
  border-radius: 8px;
}

.activeRoomName {
  overflow-wrap: break-word;
  color: rgba(0, 0, 0, 1);
  font-size: 16px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  white-space: nowrap;
  line-height: 22px;
  margin: 0 0 0 13px;
}

</style>
