<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container"
      @toggleClick="toggleSideBar" />

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" v-if="!topNav" />
    <top-nav id="topmenu-container" class="topmenu-container" v-if="topNav" />

    <div class="right-menu">
      <template v-if="device !== 'mobile'">
        <search id="header-search" class="right-menu-item" />

        <!-- <div style="position: absolute; top: 0; right: 300px; font-weight: 200">
          <el-button class="el-icon-s-comment" @click="chat = true" style=""
            >打开聊天</el-button
          >
          <chat-component
            :drawerVisible="chat"
            ref="chatComponent"
            @close="hiddenChat"
          />
        </div> -->
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
        <el-tooltip content="用户" effect="dark" placement="bottom">
          <div class="right-menu-item hover-effect">
            {{ roleGroup }} / {{ user.nickName }}
          </div>
        </el-tooltip>
      </template>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img :src="avatar" class="user-avatar" />
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item @click.native="setting = true">
            <span>布局设置</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { getContact, listContact } from "@/api/system/contact";
import { addMessage } from "@/api/system/message";
import { getUserProfile } from "@/api/system/user";
import Breadcrumb from "@/components/Breadcrumb";
import Hamburger from "@/components/Hamburger";
import Search from "@/components/HeaderSearch";
import RuoYiDoc from "@/components/RuoYi/Doc";
import RuoYiGit from "@/components/RuoYi/Git";
import Screenfull from "@/components/Screenfull";
import SizeSelect from "@/components/SizeSelect";
import TopNav from "@/components/TopNav";
import AIChat from "@/layout/components/AIChat/index.vue";
import { parseTime } from "@/utils/ruoyi";
import { mapGetters } from "vuex";
// import {
//   default as ChatComponent,
//   default as chatComponent,
// } from "./ChatComponent/index.vue";

export default {
  components: {
    // ChatComponent,
    Breadcrumb,
    TopNav,
    Hamburger,
    Screenfull,
    SizeSelect,
    Search,
    RuoYiGit,
    RuoYiDoc,
    AIChat,
  },
  computed: {
    // chatComponent() {
    //   return chatComponent;
    // },
    ...mapGetters(["sidebar", "avatar", "device"]),
    setting: {
      get () {
        return this.$store.state.settings.showSettings;
      },
      set (val) {
        this.$store.dispatch("settings/changeSetting", {
          key: "showSettings",
          value: val,
        });
      },
    },
    topNav: {
      get () {
        return this.$store.state.settings.topNav;
      },
    },
  },
  data () {
    return {
      user: {},
      chat: false,
      roleGroup: {},
      // postGroup: {},

      //联系人列表
      contactList: [],
      contactListTotal: 0,
      contactListLoading: false,
      //消息记录
      msgList: [],
      msgListTotal: 0,
      msgListLoading: false,
      inputVal: "",
      search: "",
      contactUserId: null,
      userId: null,
      contactQueryParams: {
        pageSize: 10,
        pageNum: 1,
      },
      currentContact: {},
      contactUser: {},
    };
  },
  mounted () {
    window.addEventListener("onmessageWS", this.subscribeMessage);
  },
  created () {
    this.getUser();
    this.userId = this.$store.state.user.id;
    this.subscribeMessage();
    this.getContactList();
  },
  methods: {
    toggleSideBar () {
      this.$store.dispatch("app/toggleSideBar");
    },

    hiddenChat () {
      this.chat = false;
      console.log(this.chat, "关闭chat");
    },

    getUser () {
      getUserProfile().then((response) => {
        this.user = response.data.user;
        this.roleGroup = response.data.roleGroup;
        this.postGroup = response.data.postGroup;
      });
    },
    async logout () {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            console.log('退出登录')
            location.href = process.env.VUE_APP_CONTEXT_PATH + "index";
          });
        })
        .catch(() => { });
    },

    /***********************************************************************/

    getContactList () {
      this.contactListLoading = true;
      this.contactQueryParams.userId = this.userId;
      listContact(this.contactQueryParams).then((response) => {
        if (response.code === 200) {
          this.contactList = response.rows;
          this.contactListTotal = response.total;
          const contactUserId = this.$route.query.userId;
          if (contactUserId) {
            this.contactUserId = contactUserId;
            let contact = response.rows.find(
              (row) => row.contactUserId == contactUserId
            );
            this.loadMessage(contact.id);
          }
        }
        this.contactListLoading = false;
      });
    },
    contactLoadMore () {
      // this.contactQueryParams.pageSize = 5;
      // this.contactQueryParams.pageNum++;
      this.getContactList();
    },
    loadMessage (concatId) {
      this.msgListLoading = true;
      getContact(concatId).then((response) => {
        if (response.code === 200) {
          this.currentContact = response.data;
          this.contactUser = response.data.user;
          this.msgList = response.data.messages;
        }
        this.msgListLoading = false;
        this.fleshScroll();
      });
    },
    insertEmoji (emoji) {
      this.inputVal += emoji.data;
    },
    send () {
      const message = {
        contactId: this.currentContact.id,
        userId: this.userId,
        content: this.inputVal,
        roomId: this.currentContact.roomId,
      };
      this.msgList.push({
        ...message,
        id: this.msgList.length + 1,
        createTime: parseTime(new Date()),
      });
      this.fleshLastMsg();
      addMessage(message);
      const msg = {
        sendUserId: this.userId,
        sendUserName: this.$store.state.user.name,
        userId:
          this.currentContact.contactUserId === this.userId
            ? this.currentContact.user.userId
            : this.currentContact.contactUserId,
        type: "chat",
        detail: this.inputVal,
      };
      // this.$webSocket.sendWebsocket(JSON.stringify(msg));
      this.inputVal = "";
      this.fleshScroll();
    },
    subscribeMessage (res) {
      if (res) {
        const { sendUserId, sendUserName, userId, type, detail } =
          res.detail.data;

        const message = {
          id: 1,
          contactId: this.currentContact.id,
          userId: sendUserId,
          content: detail,
          roomId: this.currentContact.roomId,
          createTime: parseTime(new Date()),
          user: this.contactUser,
        };
        this.msgList.push(message);
        this.fleshLastMsg();
        this.fleshScroll();
      }
    },
    fleshLastMsg () {
      const index = this.contactList.findIndex(
        (e) => e.id === this.currentContact.id
      );
      this.contactList[index].endMsg =
        this.msgList[this.msgList.length - 1].content;
    },
    fleshScroll () {
      this.$nextTick(() => {
        document.getElementById("message_content_end").scrollIntoView();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.navbar {
  height: 40px;
  overflow: hidden;
  position: relative;
  background: #f5f5f5;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 36px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 40px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;
        font-size: 14px;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 30px;
      height: 100%;

      .avatar-wrapper {
        margin-top: 5px;
        // position: relative;

        .user-avatar {
          cursor: pointer;
          width: 30px;
          height: 30px;
          border-radius: 8px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          top: 50%;
          transform: translate(-50%);
          right: -20px;
          // top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}

.app-container {
  background: linear-gradient(180deg,
      rgba(0, 190, 189, 0.1),
      rgba(136, 255, 254, 0.2) 50%,
      rgba(242, 244, 247, 0.1));
}

.app {
  background-color: white;
  border-radius: 12px 12px 0 0;
}

.msgListMain {
  height: 500px;
  overflow-y: auto;
  margin-top: 15px;
}

.msgUserList {
  border-radius: 10px;
}

.msgListMain_empty {
  display: flex;
  height: 500px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.hover_down_menu {
  display: none;
}

.msgUserList:hover {
  background-color: #f2f2f2;
  cursor: pointer;
}

.msgUserList:hover .hover_down_menu {
  display: block;
}

.el-dropdown-link {
  cursor: pointer;
}

.el-icon-arrow-down {
  font-size: 15px;
  font-weight: 500;
}

.main {
  background-color: white;
  height: 86%;
  margin-left: 5px;
}

.main_empty {
  display: flex;
  background-color: white;
  height: 600px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.main_empty .el-row {
  text-align: center;
}

.main_empty img {
  width: 25%;
}

.msg_content {
  margin-top: 30px;
  height: 50%;
  overflow: auto;
  //background-color: gray;
}

.chat_bubble {
  float: right;
  margin-right: 35px;
  color: #333;
  background-color: rgba(0, 190, 189, 0.2);
  height: 40px;
  line-height: 40px;
  padding: 0 12px 0 12px;
  border-radius: 5px;
}

.input_top_menu_img {
  width: 22px;
  height: 22px;
  cursor: pointer;
}
</style>
