<template>
  <div class="customer-service-list bg-grey">
    <mescroll-vue
      ref="mescrollRef"
      @init="mescrollInit"
      :down="downOptions"
      :up="upOptions"
    >
      <div class="list-item">
        <list-item
          v-for="(item, index) of listData"
          :key="index + Math.random()"
          :index="index"
          :itemData="item"
          @readMessage="readMessage"
        />
      </div>
      <m-no-data v-if="listData.length == 0" type="msg" />
    </mescroll-vue>
  </div>
</template>

<script>
import ListItem from "./list-item.vue";
import { mapState, mapGetters, mapMutations } from "vuex";
import { MescrollMixin } from "@/mixins";
export default {
  mixins: [MescrollMixin],
  components: { ListItem },
  data() {
    return {
      listData: [],
      downOptions: {
        autoShowLoading: false,
        callback: this.downCallback,
      },
      upOptions: {
        callback: this.upCallback,
      },
      socketTask: null,
      is_open_socket: false,  
      scoketList: {},
    };
  },
  computed: {
    ...mapState(["accountInfo"]),
  },
  mounted() {
    this.closeAllSocket();
  },
  beforeDestroy(){
    this.closeAllSocket();
  },
  methods: {
    downCallback() {
      this.mescroll.resetUpScroll();
    },
    upCallback(page) {
      if (this.hasLogin) {
        this.requestData();
      }
    },
    readMessage(index) {
      let obj = this.listData[index];
      obj.newsNumber = 0;
      this.$set(this.listData, index, obj);
    },
    connectSocketInit(groupId, index) {
      const host = window.location.host;
      if (groupId) {
        let protocol = "ws://";
        if (window.location.protocol === "https:") {
          protocol = "wss://";
        }
        this.scoketList[groupId] = new WebSocket(
          protocol +
            host +
            "/chat/mallcustomer/websocket/" +
            this.accountInfo.userId +
            "/" +
            groupId
        );
        // this.scoketList[groupId] = uni.connectSocket({
        //   url:
        //     "ws://" +
        //     host +
        //     "/chat/mallcustomer/websocket/" +
        //     this.accountInfo.userId +
        //     "/" +
        //     groupId,
        //   success(data) {
        //     console.log("websocket连接成功");
        //   },
        // });
        // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
        this.scoketList[groupId].onopen = (res) => {
          console.log("WebSocket连接正常打开中...！");
          // 注：只有连接正常打开中 ，才能正常收到消息
          this.scoketList[groupId].onmessage = (res) => {
            let obj = JSON.parse(res.data);
            let data = this.listData[index];
            data.messageList.push(obj);
            data.newsNumber++;
            this.$set(this.listData, index, data);
          };
        };
        // 这里仅是事件监听【如果socket关闭了会执行】
        this.scoketList[groupId].onclose = () => {
          console.log("已经被关闭了");
        };
      }
    },
    closeAllSocket() {
      let arr = Object.keys(this.scoketList);
      for (let item of arr) {
        this.closeSocket(item);
      }
    },
    // 关闭websocket【离开这个页面的时候执行关闭】
    closeSocket(groupId) {
      this.scoketList[groupId].close();
    },
    requestData() {
      this.$api({
        apiName: "customerServiceList",
        postData: { userId: this.accountInfo.userId },
        success: (res) => {
          this.listData = res;
          this.mescroll.endBySize(res.length, res.length);
          for (let i = 0, len = this.listData.length; i < len; i++) {
            this.listData[i].newsNumber = 0;
            this.connectSocketInit(this.listData[i].group.groupId, i);
          }
        },
        fail: (err) => {
          this.mescroll.endErr();
        },
        complete: () => {
          this.$hideLoading();
          this.mescroll.endDownScroll();
        },
      });
    },
  },
};
</script>
<style lang="less">
.customer-service-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .list-item {
    background-color: #ffffff;
  }
  ::v-deep.mescroll-uni-warp {
    .mescroll-uni-fixed {
      height: 100%;
    }
  }
}
</style>
