import { mapGetters, mapMutations } from 'vuex';

const mixin = {
  data() {
    return {
      dmsTimer: null
    };
  },
  computed: {
    ...mapGetters({
      type: 'type',
      status: 'status',
      userInfo: 'userInfo',
      menuList: 'menuList',
      channelInfo: 'channelInfo'
    }),
    reportDms() {
      let dms = '';
      const menuList = this.menuList || [];
      for (let i = 0; i < menuList.length; i++) {
        const item = menuList[i];
        if (item.menuType === 'report' && item.menuInfo) {
          dms = `pic_text_${item.menuInfo}`;
        }
      }
      return dms;
    },
    otherTopic() {
      const channelInfo = this.channelInfo || {};
      return {
        audience: `dms_${channelInfo.uin}_audience`,
        config: `channel_config_${channelInfo.id}`
      };
    }
  },
  async mounted() {
    if (this.status !== 200) {
      return false;
    }
    this._DMSInit();
    this._enterDms();
  },
  methods: {
    ...mapMutations({
      set_channelInfo: 'set_channelInfo',
      set_channelConfig: 'set_channelConfig',
      set_userInfo: 'set_userInfo',
      set_white: 'set_white'
    }),
    _enterDms() {
      clearTimeout(this.dmsTimer);
      this.dmsTimer = null;
      this.dmsTimer = setTimeout(() => {
        this._makeClientId();
        this.dmsTimer = null;
      }, 500);
    },
    _makeClientId() {
      ROP.Leave();
      const uin = this.channelInfo.uin || '0';
      const channelId = this.channelInfo.id || '0';
      const timeStr = String(new Date().getTime() + Math.floor(Math.random() * 100000));
      const clientId = `${uin}_${channelId}_${timeStr}`;
      console.log(clientId);
      ROP.Enter('', this.channelInfo.sub_key, clientId, true);
    },
    _DMSInit() {
      const self = this;
      // chat连接成功后的消息
      ROP.On('enter_suc', function() {
        console.log('服务器连接成功');
        ROP.Subscribe(self.channelInfo.dmsTopic);
        ROP.Subscribe(self.channelInfo.dmsDataTopic);
        ROP.Subscribe(self.channelInfo.dmsRewardTopic);
        ROP.Subscribe(self.channelInfo.dmsRedpacketTopic);
        ROP.Subscribe(self.otherTopic.audience);
        ROP.Subscribe(self.otherTopic.config);
        if (self.channelInfo.dmsActivityManage) {
          ROP.Subscribe(self.channelInfo.dmsActivityManage);
        }
        if (self.channelInfo.dmsActivityDraw) {
          ROP.Subscribe(self.channelInfo.dmsActivityDraw);
        }
        if (self.reportDms) {
          ROP.Subscribe(self.reportDms);
        }
      });
      ROP.On('reconnect', function(err) {
        console.log('重连', err);
      });
      // chat连接失败后的消息
      ROP.On('enter_fail', function(err) {
        console.log('服务器连接失败', err);
      });
      // chat接收到的消息
      ROP.On('publish_data', function(res, topic) {
        const data = JSON.parse(res);
        switch (topic) {
          case self.channelInfo.dmsTopic:
          case self.channelInfo.dmsRewardTopic:
          case self.channelInfo.dmsRedpacketTopic:
            self._dmsChat(data);
            break;
          case self.channelInfo.dmsDataTopic:
            self._dmsChannelInfo(data);
            break;
          case self.channelInfo.dmsActivityManage:
            self._dmsActivity(data);
            break;
          case self.channelInfo.dmsActivityDraw:
            self.$Bus.$emit('bus-drawStatus', data);
            break;
          case self.reportDms:
            self.$Bus.$emit('bus-reportAdd', data);
            break;
          case self.otherTopic.audience:
            self._dmsAudience(data);
            break;
          case self.otherTopic.config:
            self._dmsChannelConfig(data);
            break;
          default:
            break;
        }
      });
      // chat断开连接后的消息
      ROP.On('losed', function() {
        console.log('服务器断开连接');
      });
    },
    _dmsChat(data) {
      if (data.cmd === 'watchCode') {
        const tokenKey = `white-${this.type}-${this.channelInfo.id}`;
        if (data.clearAll === 1) {
          this.set_white(true);
          this.$cookie.remove(tokenKey);
        } else {
          const watchObj = this.$cookie.get(tokenKey) || '{}';
          const { ticket, code } = JSON.parse(watchObj);
          const watchData = data.watchData;
          if (watchData.ticket === ticket && watchData.code === code) {
            this.set_white(true);
            this.$cookie.remove(tokenKey);
          }
        }
        return false;
      }
      if (Number(data.msgType) === 1) {
        this.$Bus.$emit('bus-sendBarrage', data.filterContent);
      }
      if (Number(data.msgType) === 6 && data.redpacketId) {
        this.$Bus.$emit('bus-addShareList', {
          redpacketId: data.redpacketId
        });
        return false;
      }
      if (Number(data.msgType) === 10 && data.redpacketId) {
        this.$Bus.$emit('bus-addAnswerList', {
          redpacketId: data.redpacketId
        });
        return false;
      }
      if (Number(data.msgType) === 12 && data.redpacketId) {
        this.$Bus.$emit('bus-addBusinessList', {
          redpacketId: data.redpacketId,
          isRob: 2
        });
        return false;
      }
      if (Number(data.msgType) === 2 || Number(data.msgType) === 14) {
        this.$Bus.$emit('bus-giftRoll', data);
      }
      if (data.isTop) {
        this.$Bus.$emit('bus-addTopChat', data);
      }
      this.$Bus.$emit('bus-addChat', data);
      this.$Bus.$emit('bus-chatNum', 1);
    },
    _dmsChannelInfo(data) {
      if (data.cmd === 'praise') {
        // 点赞
        this.$Bus.$emit('bus-praiseNum', data.num);
        return false;
      }
      if (data.cmd === 'watchNum') {
        // 自定义观看量
        this.$Bus.$emit('bus-customWatchNum', data.watchNum);
        return false;
      }
      if (data.cmd === 'realWatchNum') {
        // 真实观看量
        this.$Bus.$emit('bus-realWatchNum', data.realWatchNum);
        return false;
      }
      if (data.cmd === 'chatDisable') {
        // 是否全员禁言
        const info = JSON.parse(JSON.stringify(this.channelInfo));
        info.chatDisable = data.status;
        this.set_channelInfo(info);
        return false;
      }
      if (data.cmd === 'chatLogin') {
        // 是否禁止游客聊天
        const info = JSON.parse(JSON.stringify(this.channelInfo));
        info.chatLogin = data.status;
        this.set_channelInfo(info);
      }
      if (data.cmd === 'chatSee') {
        // 聊天是否自己可见
        const info = JSON.parse(JSON.stringify(this.channelInfo));
        info.chatSee = data.status;
        this.set_channelInfo(info);
        return false;
      }
      if (data.cmd === 'chatCountStatus') {
        // 是否显示聊天数
        const info = JSON.parse(JSON.stringify(this.channelInfo));
        info.chatCountStatus = data.status;
        this.set_channelInfo(info);
        return false;
      }
      if (data.cmd === 'living') {
        // 开启结束直播
        const info = JSON.parse(JSON.stringify(this.channelInfo));
        info.liveStatus = data.status;
        this.set_channelInfo(info);
        return false;
      }
      if (data.cmd === 'isTop') {
        // 是否置顶
        if (Number(data.status) === 0) {
          this.$Bus.$emit('bus-delTopChat', data.chatInfo.id);
        }
        return false;
      }
      if (data.cmd === 'office_live') {
        // 文档信息
        this.set_channelConfig({
          officeLive: data.data
        });
        return false;
      }
      if (data.id) {
        // 删除聊天

        if (typeof data.id === 'string') {
          const ids = data.id.split(',');
          ids.forEach(item => {
            this.$Bus.$emit('bus-delTopChat', Number(item));
            this.$Bus.$emit('bus-delChat', Number(item));
            this.$Bus.$emit('bus-chatNum', -1);
          });
        } else if (typeof data.id === 'number') {
          this.$Bus.$emit('bus-delTopChat', data.id);
          this.$Bus.$emit('bus-delChat', data.id);
          this.$Bus.$emit('bus-chatNum', -1);
        }
      }
    },
    _dmsActivity(data) {
      if (data.cmd === 'vote_set_include') {
        this.$Bus.$emit('bus-voteList', data);
        return false;
      }
      if (data.cmd === 'vote_edit') {
        this.$Bus.$emit('bus-voteEdit', data);
        return false;
      }
      if (data.cmd === 'vote_service') {
        this.$Bus.$emit('bus-voteStatus', data);
        return false;
      }
      if (data.cmd === 'draw_bind') {
        if (Number(data.status) === 1) {
          this.$Bus.$emit('bus-drawInfo', data.drawInfo);
        } else {
          this.$Bus.$emit('bus-drawInfo', {});
        }
        return false;
      }
      if (data.cmd === 'vote_set_source') {
        if (Number(data.status) === 1) {
          this.$Bus.$emit('bus-voteInfo', data.voteInfo);
        } else {
          this.$Bus.$emit('bus-voteInfo', {});
        }
        return false;
      }
      if (data.cmd === 'editShop') {
        this.$Bus.$emit('bus-editShop', data);
        return false;
      }
      if (data.cmd === 'deleteShop') {
        this.$Bus.$emit('bus-deleteShop', data);
        return false;
      }
      if (data.cmd === 'addShopBind') {
        this.$Bus.$emit('bus-addShopBind', data);
        return false;
      }
      if (data.cmd === 'cancelShopBind') {
        // 下架商品
        this.$Bus.$emit('bus-cancelShopBind', data);
        return false;
      }
      if (data.cmd === 'changeSort') {
        // 商品排序
        this.$Bus.$emit('bus-changeSort', data);
        return false;
      }
      if (data.cmd === 'setTopShop') {
        // 推荐商品
        this.$Bus.$emit('bus-setTopShop', data);
        return false;
      }
      if (data.cmd === 'cancelTopShop') {
        // 取消推荐商品
        this.$Bus.$emit('bus-cancelTopShop', data);
        return false;
      }
    },
    _dmsAudience(data) {
      const ids = data.ids.map(x => Number(x));
      if (ids.indexOf(Number(this.userInfo.id)) === -1) {
        return false;
      }
      if (data.cmd === 'disableChat') {
        const info = JSON.parse(JSON.stringify(this.userInfo));
        info.isDisableChat = Number(data.isDisable);
        this.set_userInfo(info);
        return false;
      }
      if (data.cmd === 'setStatus') {
        const info = JSON.parse(JSON.stringify(this.userInfo));
        info.status = Number(data.status);
        this.set_userInfo(info);
        return false;
      }
    },
    _dmsChannelConfig(data) {
      if (data.cmd === 'commodity') {
        const list = [];
        const { cad } = data;
        if (cad) {
          list.push(cad);
        }
        this.$Bus.$emit('bus-commodity', list);
      }
    }
  }
};
export default mixin;
