<template>
  <div id="contextxx">
    <template v-if="view == 'room'">
      <rooms :list="list" @toChat="toChat"></rooms>
    </template>
    <template v-else>
      <chat :room="room" @toRoom="toRoom"></chat>
    </template>
  </div>
</template>

<script>
import _ from 'lodash';
import rooms from './parts/room.vue';
import chat from './parts/chat.vue';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('personalroom');
const { mapActions: personalChat } = createNamespacedHelpers('personalchat');
export default {
  name: 'contextxx',
  props: {},
  components: { rooms, chat },
  data: () => {
    return {
      view: 'room',
      list: [],
      room: {},
    };
  },
  created() {
    this.search();
  },
  mounted() {
    this.channel();
  },
  methods: {
    ...mapActions(['query', 'fetch']),
    ...personalChat({ getChatList: 'query' }),
    async search() {
      let res = await this.query({ receiver_id: this.user.uid });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.onMessage();
      }
    },
    async toChat(data) {
      let res = await this.fetch(data.id);
      if (this.$checkRes(res)) {
        this.$set(this, `room`, res.data);
        this.view = 'chat';
      }
    },
    toRoom() {
      this.view = 'room';
      this.onMessage();
    },
    channel() {
      this.$stomp({
        [`/exchange/chat_message/${this.user.uid}`]: this.onMessage,
      });
    },
    async onMessage(message) {
      let res = await this.getChatList({ status: 0, receiver_id: this.user.uid });
      if (this.$checkRes(res)) {
        let arr = this.list.map(i => {
          i.needRead ? '' : (i.needRead = 0);
          // let findRes = res.data.filter(f => i.sender_id == f.sender_id);
          i.needRead = res.data.length || 0;
          return i;
        });
        this.$set(this, `list`, arr);
      }
    },
  },
  computed: {
    ...mapState(['user']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
