<template>
  <transition name="el-zoom-in-center">
    <div
      ref="container"
      class="current-conversation-wrapper"
      :class="'current-conversation-wrapper-' + (isComplete ? 'complete' : '')"
    >
      <div v-if="isComplete" class="top" @dblclick="handleScreen" @mousedown="onmousedown($event)" @mouseup="onmouseup">
        <div class="title">调度消息</div>
        <div class="btns">
          <i class="item icon" :class="isFullscreen ? 'narrow' : 'fullscreen'" @click="handleScreen"></i>
          <i class="item icon close" @click="close"></i>
        </div>
      </div>
      <div class="main">
        <!-- 切换C2C GROUP -->
        <div v-if="isComplete" class="tabs">
          <el-avatar
            style="margin-top: 10px; margin-bottom: 24px"
            :size="48"
            :src="currentUserProfile.avatar"
            @error="handleImgError"
          >
            <div class="avatar">{{ nick }}</div>
          </el-avatar>
          <div class="tab" :class="active === 'C2C' ? 'tab-active' : ''" @click="switchType('C2C')">
            <i class="icon icon-c2c"></i>
            单聊
          </div>
          <div class="tab" :class="active === 'GROUP' ? 'tab-active' : ''" @click="switchType('GROUP')">
            <i class="icon icon-group"></i>
            多人
          </div>
        </div>
        <!-- 对话列表 -->
        <div v-if="isComplete" class="conversation-list">
          <!-- 历史单聊 -->
          <div v-show="showConversationList" class="scroll-container">
            <conversation-item :conversation="item" v-for="item in conversationList" :key="item.conversationID" />
          </div>
          <!-- 历史组群 -->
          <div v-show="showGroupList" class="scroll-container">
            <group-item v-for="group in groupList" :key="group.groupID" :group="group" />
          </div>
        </div>
        <!-- 对话主体 -->
        <div class="conversation">
          <!-- 标题 -->
          <div class="header" @mousedown="onmousedown($event)" @mouseup="onmouseup">
            <!-- C2C -->
            <div v-if="currentConversationType === TIM.TYPES.CONV_C2C" class="profile">
              <el-avatar :size="48" :src="currentConversation.userProfile.avatar" @error="handleImgError">
                <div class="avatar">
                  {{ currentConversation?.info?.nameSlice || currentConversation?.userProfile?.nick }}
                </div>
              </el-avatar>
              <span class="nick">{{ nick }}</span>
            </div>
            <!-- GROUP -->
            <div v-if="currentConversationType === TIM.TYPES.CONV_GROUP" class="profile">
              <el-popover placement="right" width="400" trigger="click" @show="onGroupShow">
                <el-row class="memberList" :gutter="10">
                  <el-col v-for="(item, index) in currentMemberList" :key="index" :span="6" class="member-item">
                    <el-avatar :size="50" :src="item.avatar" @error="handleImgError">
                      <div class="avatar">{{ item.nick }}</div>
                    </el-avatar>
                    <span class="nick">{{ item.nick }}</span>
                  </el-col>
                </el-row>
                <el-avatar slot="reference" :size="48" :src="groupAvatar" style="background: none; cursor: pointer"></el-avatar>
              </el-popover>

              <span class="nick">{{ groupName }}</span>
            </div>
            <i v-if="!isComplete" class="close el-icon-close" @click="close"></i>
          </div>
          <div class="content" ref="message-list">
            <message-item v-for="(message, index) in currentMessageList" :key="message.ID + '-' + index" :message="message" />
          </div>
          <div class="footer">
            <div class="toolbar">
              <el-popover placement="top" width="400" trigger="click">
                <div class="emojis">
                  <div v-for="item in emojiName" class="emoji" :key="item" @click="chooseEmoji(item)">
                    <img :src="emojiUrl + emojiMap[item]" style="width: 30px; height: 30px" alt="" />
                  </div>
                </div>
                <i class="icon-smile" slot="reference" title="发表情"></i>
              </el-popover>
              <i class="icon-folder" title="发文件" @click="handleSendFileClick"></i>
              <input type="file" id="filePicker" ref="filePicker" @change="sendFile" style="display: none" />
              <i class="icon-image-picker" title="发图片" @click="handleSendImageClick"></i>
              <input
                type="file"
                id="imagePicker"
                ref="imagePicker"
                accept=".jpg, .jpeg, .png, .gif, .bmp"
                @change="sendImage"
                style="display: none"
              />
            </div>
            <div class="message">
              <el-input class="modal" type="textarea" v-model="message" resize="false" @keyup.enter.ctrl.native="send"></el-input>
              <el-button class="send" type="primary" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- resize icon -->
      <div v-if="!isFullscreen" ref="resize" class="resize" @mousedown="handleMousedown($event)"></div>
    </div>
  </transition>
</template>

<script>
import TIM from "tim-js-sdk/tim-js-friendship";
import tim from "@/tim";
import { mapState, mapGetters } from "vuex";
import { emojiMap, emojiName, emojiUrl } from "@/utils/emojiMap";
import messageItem from "@/components/timApp/message/message-item.vue";
import screenfull from "screenfull";
import ConversationItem from "@/components/timApp/conversation/conversation-item.vue";
import GroupItem from "@/components/timApp/group/group-item.vue";
import { getEmployeeDetail } from "@/api/employee-controller";

export default {
  name: "CurrentConversation",
  components: { GroupItem, ConversationItem, messageItem },
  props: {
    isComplete: {
      type: Boolean,
      default: false,
    },
    conversationID: {
      type: String,
    },
    defaultMessage: {
      type: String,
    },
  },
  data() {
    return {
      emojiMap: emojiMap,
      emojiName: emojiName,
      emojiUrl: emojiUrl,
      disX: 0,
      disY: 0,
      down: false,
      isImgError: false,
      isImgLoad: false,
      message: "",
      isFullscreen: false,
      active: "C2C",
      groupAvatar: require("@/assets/images/conversation/群组icon.png"),
      isShowScrollButtomTips: false,
      preScrollHeight: 0,
    };
  },
  computed: {
    screenfull() {
      return screenfull;
    },
    groupList: function () {
      return this.$store.state.group.groupList;
    },
    ...mapState({
      currentUnreadCount: (state) => state.conversation.currentConversation.unreadCount,
      conversationList: (state) => state.conversation.conversationList.filter((x) => x.type === "C2C"),
      currentConversation: (state) => state.conversation.currentConversation,
      currentMessageList: (state) => state.conversation.currentMessageList,
      currentUserProfile: (state) => state.user.currentUserProfile,
      currentMemberList: (state) => state.group.currentMemberList,
    }),
    ...mapGetters(["toAccount", "currentConversationType", "hidden"]),
    nick() {
      // console.log("currentConversation info",this.currentConversation.info)
      let name = this.currentConversation?.info?.name;
      if (!name) {
        const userInfo = localStorage.getItem("userInfo");
        if (userInfo) {
          console.log("userInfo", JSON.parse(userInfo));
          name = JSON.parse(userInfo).name;
        }
      }
      return name;
    },
    groupName() {
      return this.currentConversation.groupProfile.name;
    },
    avatarSrc: function () {
      return this.currentConversation.type === TIM.TYPES.CONV_C2C
        ? this.currentConversation.userProfile.avatar
        : require("@/assets/images/conversation/群组icon.png");
    },
    defaultSrc: function () {
      switch (this.currentConversation.type) {
        case "C2C":
          // 个人头像
          return "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
        case "GROUP":
          // 群默认头像
          return "https://imgcache.qq.com/open/qcloud/video/act/webim-avatar/avatar-3.png";
        case TIM.TYPES.CONV_SYSTEM:
          return "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
        default:
          // 默认头像
          return "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
      }
    },
    showGroupList() {
      return this.active === "GROUP";
    },
    showConversationList() {
      return this.active === "C2C";
    },
  },
  watch: {
    currentUnreadCount(next) {
      if (!this.hidden && next > 0) {
        tim.setMessageRead({
          conversationID: this.currentConversation.conversationID,
        });
      }
    },
    hidden(next) {
      if (!next && this.currentUnreadCount > 0) {
        tim.setMessageRead({
          conversationID: this.currentConversation.conversationID,
        });
      }
    },
  },
  methods: {
    handleScreen() {
      if (screenfull.isEnabled) {
        // console.log("screen",this.$refs.container)
        screenfull.toggle(this.$refs.container);
        this.isFullscreen = !this.isFullscreen;
      }
    },
    /**
     * 监听鼠标移动事件
     * @param evt
     */
    onmousedown(evt) {
      if (this.isFullscreen) return false;
      // event的兼容性
      const ev = evt || event;

      // 获取鼠标按下的坐标
      const x1 = ev.clientX;
      const y1 = ev.clientY;

      // 获取元素的left，top值
      const l = this.$refs.container.offsetLeft;
      const t = this.$refs.container.offsetTop;

      // 给可视区域添加鼠标的移动事件
      document.onmousemove = (eve) => {
        // event的兼容性
        const evn = eve || event;

        // 获取鼠标移动时的坐标
        const x2 = evn.clientX;
        const y2 = evn.clientY;

        // 计算出鼠标的移动距离
        const x = x2 - x1;
        const y = y2 - y1;

        // 移动的数值与元素的left，top相加，得出元素的移动的距离
        const lt = y + t;
        const ls = x + l;

        // 更改元素的left，top值
        this.$refs.container.style.top = lt + "px";
        this.$refs.container.style.left = ls + "px";

        this.$emit("move", [ls, lt]);
      };
    },
    onmouseup(evt) {
      const evn = evt || event;
      this.down = false;
      document.removeEventListener("mousemove", this.onResize);
      document.onmousemove = null;
      document.onmousedown = null;
      document.onmouseup = null;
      const x2 = evn.clientX;
      const y2 = evn.clientY;
      this.$emit("moveEnd", [x2, y2]);
    },
    handleMousedown(e) {
      this.down = true;
      this.disX = e.clientX - this.$refs.resize.offsetLeft;
      this.disY = e.clientY - this.$refs.resize.offsetTop;
      document.addEventListener("mousemove", this.onResize);
      document.onmouseup = () => {
        this.down = false;
        document.removeEventListener("mousemove", this.onResize);
      };
    },
    onResize(e) {
      // 获取鼠标的实时位置
      const curX = e.clientX;
      const curY = e.clientY;
      // 获取拖拽的长度
      const increaseX = curX - this.disX;
      const increaseY = curY - this.disY;
      // 按下开始拖拽改变目标元素大小
      if (this.down) {
        const width = this.$refs.resize.offsetWidth + increaseX;
        const height = this.$refs.resize.offsetHeight + increaseY;
        width < 200 ? (this.$refs.container.style.width = "200px") : (this.$refs.container.style.width = width + "px");
        height < 452 ? (this.$refs.container.style.height = "452px") : (this.$refs.container.style.height = height + "px");
        this.$emit("resize", [curX, curY]);
      }
    },
    handleImgError() {
      this.isImgError = true;
    },
    handleImgLoad() {
      this.isImgLoad = true;
    },
    close() {
      this.$emit("close");
    },
    chooseEmoji(item) {
      this.message += item;
    },
    handleSendImageClick() {
      this.$refs.imagePicker.click();
    },
    handleSendFileClick() {
      this.$refs.filePicker.click();
    },
    sendFile() {
      const message = tim.createFileMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: document.getElementById("filePicker"), // 或者用event.target
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      tim
        .sendMessage(message)
        .then(() => {
          this.$refs.filePicker.value = null;
        })
        .catch((imError) => {
          this.$store.commit("showMessage", {
            message: imError.message,
            type: "error",
          });
        });
    },
    sendImage() {
      const message = tim.createImageMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: document.getElementById("imagePicker"), // 或者用event.target
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      tim
        .sendMessage(message)
        .then(() => {
          // this.$refs.imagePicker.value = null;
          document.getElementById("imagePicker").value = null;
          this.scrollMessageListToButtom();
        })
        .catch((imError) => {
          this.$store.commit("showMessage", {
            message: imError.message,
            type: "error",
          });
        });
    },
    send() {
      if (this.message === "" || this.message.trim().length === 0) {
        this.message = "";
        this.$store.commit("showMessage", {
          message: "不能发送空消息哦！",
          type: "info",
        });
        return;
      }
      let message = tim.createTextMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
        payload: {
          text: this.message,
        },
        // v2.20.0起支持C2C消息已读回执功能，如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
        needReadReceipt: true,
        // 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
        // cloudCustomData: 'your cloud custom data'
      });
      console.log(message);
      // 2. 发送消息
      let promise = tim.sendMessage(message);
      promise
        .then((imResponse) => {
          // 发送成功
          console.log(imResponse);
          this.$store.commit("pushCurrentMessageList", message);
          this.scrollMessageListToBottom();
          this.message = "";
          this.$emit("update:defaultMessage", "");
          this.$bus.$emit("scroll-bottom");
        })
        .catch((imError) => {
          // 发送失败
          console.warn("sendMessage error:", imError);
          this.$store.commit("showMessage", {
            type: "error",
            message: imError.message,
          });
        });
    },
    // 直接滚到底部
    scrollMessageListToBottom() {
      this.$nextTick(() => {
        let messageListNode = this.$refs["message-list"];
        if (!messageListNode) {
          return;
        }
        messageListNode.scrollTop = messageListNode.scrollHeight;
        // this.preScrollHeight = messageListNode.scrollHeight;
        // this.isShowScrollButtomTips = false;
      });
    },
    switchType(type) {
      console.log(this.currentConversation);
      this.active = type;
    },
    onImageLoaded() {
      this.keepMessageListOnButtom();
    },
    // 如果滚到底部就保持在底部，否则提示是否要滚到底部
    keepMessageListOnButtom() {
      let messageListNode = this.$refs["message-list"];
      if (!messageListNode) {
        return;
      }
      // 距离底部20px内强制滚到底部,否则提示有新消息
      if (this.preScrollHeight - messageListNode.clientHeight - messageListNode.scrollTop < 20) {
        this.$nextTick(() => {
          messageListNode.scrollTop = messageListNode.scrollHeight;
        });
        this.isShowScrollButtomTips = false;
      } else {
        this.isShowScrollButtomTips = true;
      }
      this.preScrollHeight = messageListNode.scrollHeight;
    },
    // 直接滚到底部
    scrollMessageListToButtom() {
      this.$nextTick(() => {
        let messageListNode = this.$refs["message-list"];
        if (!messageListNode) {
          return;
        }
        messageListNode.scrollTop = messageListNode.scrollHeight;
        this.preScrollHeight = messageListNode.scrollHeight;
        this.isShowScrollButtomTips = false;
      });
    },
    onGroupShow() {
      console.log(this.currentMemberList);
      const currentMemberList = this.currentMemberList.map(async (member) => {
        if (member.avatar === "undefined") {
          const employeeDetail = await getEmployeeDetail(member.userID);
          console.log(employeeDetail);
        }
        return member;
      });
      console.log(currentMemberList);
    },
  },
  mounted() {
    console.log(this.toAccount);
    console.log("currentConversation", this.currentConversation);
    console.log("currentUserProfile", this.currentUserProfile);
    this.$bus.$on("image-loaded", this.onImageLoaded);
    this.$bus.$on("scroll-bottom", this.scrollMessageListToButtom);
    if (this.defaultMessage) {
      this.message = this.defaultMessage;
      this.send();
    }
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-avatar > img {
  width: 100%;
  object-fit: contain !important;
}
.current-conversation-wrapper {
  width: 899px;
  height: 700px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px 4px 4px 4px;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    overflow: hidden;
    //margin-right: 16px;
    background: #0e71ff;
    font-size: 16px;
    font-weight: 400;
    color: #ffffff;
    img {
      width: 100%;
      height: auto;
    }
  }
  .top {
    width: 100%;
    height: 40px;
    background: #0e70ff;
    border-radius: 4px 4px 0px 0px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    .title {
      font-size: 16px;
      font-weight: 400;
      color: #ffffff;
    }
    .btns {
      display: flex;
      .item {
        margin-left: 16px;
      }
      .icon {
        display: block;
        width: 16px;
        height: 16px;
        cursor: pointer;
        &.fullscreen {
          background: url("~@/assets/images/conversation/全屏.png") no-repeat;
          background-size: 100% 100%;
        }
        &.narrow {
          background: url("~@/assets/images/conversation/全屏.png") no-repeat;
          background-size: 100% 100%;
        }
        &.close {
          background: url("~@/assets/images/conversation/关闭.png") no-repeat;
          background-size: 100% 100%;
        }
      }
    }
  }
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    .conversation {
      width: 100%;
      .header {
        width: 100%;
        height: 68px;
        background: #f5f8ff;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
        border-radius: 4px 4px 0px 0px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 18px 0 24px;
        .profile {
          width: auto;
          height: 48px;
          display: flex;
          align-items: center;

          .nick {
            font-size: 16px;
            font-weight: 400;
            color: #000000;
            margin-left: 16px;
          }
        }
        .close {
          cursor: pointer;
        }
      }
      .content {
        width: 100%;
        height: calc(100% - 92px - 160px);
        min-height: 200px;
        overflow-y: scroll;
        overflow-x: hidden;
        padding: 0 24px;
      }
      .footer {
        width: 100%;
        height: 160px;
        background: #ffffff;
        box-shadow: inset 0px 1px 0px 0px rgba(0, 0, 0, 0.08);
        border-radius: 0px 0px 4px 4px;
        .toolbar {
          width: 100%;
          height: 65px;
          display: flex;
          align-items: center;
          padding-left: 24px;
          .icon-smile {
            display: block;
            width: 24px;
            height: 24px;
            background: url("~@/assets/images/conversation/smile-outlined.png") no-repeat;
            background-size: 100% 100%;
            cursor: pointer;
          }
          .icon-folder {
            display: block;
            width: 24px;
            height: 24px;
            background: url("~@/assets/images/conversation/folder-outlined.png") no-repeat;
            background-size: 100% 100%;
            cursor: pointer;
            margin-left: 16px;
          }
          .icon-image-picker {
            display: block;
            width: 24px;
            height: 24px;
            background: url("~@/assets/images/conversation/image-send-picker.jpg") no-repeat;
            background-size: 100% 100%;
            cursor: pointer;
            margin-left: 16px;
          }
        }
        ::v-deep .modal {
          width: calc(100% - 24px - 120px - 24px);
          height: calc(100% - 56px - 8px);
          .el-textarea__inner {
            border: 0;
          }
        }
        .send {
          width: 120px;
          height: 48px;
          margin-left: 24px;
        }
      }
    }
  }
  &-complete {
    // width: 1347px;
    // height: 870px;
    width: 1100px;
    height: 750px;
    .main {
      height: calc(100% - 40px);
      .tabs {
        width: 80px;
        height: 100%;
        background: rgba(14, 112, 255, 0.04);
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #d9d9d9;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
        .tab {
          width: 60px;
          height: 76px;
          border-radius: 4px 4px 4px 4px;
          opacity: 1;
          cursor: pointer;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: space-between;
          padding: 8px 0;

          .icon {
            display: block;
            width: 24px;
            height: 24px;
            &-c2c {
              background: url("~@/assets/images/conversation/单聊未选.png") no-repeat;
              background-size: 100% 100%;
            }
            &-group {
              background: url("~@/assets/images/conversation/多人未选.png") no-repeat;
              background-size: 100% 100%;
            }
          }
          //&:hover,
          &-active {
            background: rgba(14, 113, 255, 0.1);
            .icon {
              &-c2c {
                background: url("~@/assets/images/conversation/单聊选中.png") no-repeat;
                background-size: 100% 100%;
              }
              &-group {
                background: url("~@/assets/images/conversation/多人选中.png") no-repeat;
                background-size: 100% 100%;
              }
            }
          }
        }
      }
      .conversation-list {
        width: 368px;
        height: 100%;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #d9d9d9;
        //overflow-y: scroll;
        .scroll-container {
          height: 100%;
          overflow-y: auto;
          flex: 1;
        }
      }
      .conversation {
        width: calc(100% - 80px - 368px);
        height: 100%;
      }
    }
  }
  .resize {
    position: absolute;
    bottom: 8px;
    right: 8px;
    cursor: pointer;
    width: 16px;
    height: 16px;
    background: url("~@/assets/images/conversation/输入框拉伸.png") no-repeat;
    background-size: 100% 100%;
  }
}

.memberList {
  width: 100%;
  padding: 0 10px;
  height: 110px;
  background-color: #f5f9ff;
  position: relative;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  display: flex;
  align-items: center;

  .member-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 16px;
      background: #0e71ff;
      font-size: 16px;
      font-weight: 400;
      color: #ffffff;

      img {
        width: 100%;
        height: auto;
      }
    }

    .nick {
      font-size: 14px;
      //font-weight: 400;
      //color: #000000;
      //margin-left: 16px;
      line-height: 21px;
    }
  }
}
</style>
