import { Notification } from 'element-ui';
const websocketHelper = {
  WS_APP_BONUS: 'bonus',
  HAND_SHAKE: 'setWebSocketFd',
  SEND_MESSAGE: 'sendMessage',
  handShakeFormat(userId){
    return JSON.stringify({
      cmd: this.HAND_SHAKE,
      app: this.WS_APP_BONUS,
      userId: userId,
    });
  },
  parse(response){
    if(!response['data']){
      return false;
    }
    let data = response.data;
    return JSON.parse(data);
  },
  onMessage(response,userData){
    console.log('-----')
    console.log(response)
    console.log('-----')
    let data = this.parse(response);
    console.log(data)
    if(!data || !data['app'] || !data['cmd']){
      return false;
    }

    //不是前台的通讯，就不执行下面的操作了
    if(data.app !== this.WS_APP_BONUS || data.cmd === this.HAND_SHAKE){
      return false;
    }

    if(data.cmd === this.SEND_MESSAGE ){
      let user =  userData

      if(!this.allowPull(user, data.pullType, data.typeValue)){
        return false;
      }
    }

    let options = Object.assign(data, {
      title: data.title,
      message: data.message,
      type: 'info',
      duration:0,
    });

    console.log(111)
    console.log(options)

    Notification(options);
  },
  pushData(data){
    if(!data['message']){
      data['message'] = '您有一条新的消息';
    }
    return JSON.stringify(data);
  },
  allowPull(user, pullType, typeValue){
    let result = false;
    switch (pullType){
      case 'all':
        result = true;
        break;
      case 'dec_lv':
        result = (typeValue === user.DEC_LV) ? true : false;
        break;
      case 'emp_lv':
        result = (typeValue === user.EMP_LV) ? true : false;
        break;
      case 'user_name':
        result = (typeValue === user.USER_NAME) ? true : false;
        break;
      case 'location':
        if(typeof typeValue === 'string'){
          typeValue = JSON.parse(typeValue);
        }
        let userArea = [user.PROVINCE, user.CITY, user.COUNTY], len, needLen = 3, diff;
        typeValue.forEach(value=>{
          if(value[0] === ''){
            result = true;
            return false;
          }
          len = value.length;
          diff = needLen - len;
          if(diff > 0){
            value = value.concat(new Array(num).fill(''));
          }
          if(value[0] == userArea[0] && (value[1]=='' || value[1]==userArea[1]) && (value[2]=='' || value[2]==userArea[2])){
            result = true;
            return false;
          }
        });
        break;
    }
    return result;
  }
};
export default websocketHelper;
