ya.js 23.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
/**
 * @fileoverview YAS (YOHO! Acquisition System) YOHO!采集系统的前端js的开发包,
 * 用于在网页端采集信息(应用信息,用户信息,用户行为信息,浏览器及其系统信息)。
 */
require('yoho-json2');

// polyfill
var polyfill = require('./polyfill');
polyfill.init();

//工具库
var util = require('./util');

//cookie处理
var cookies = require('./cookie');

//跨域通信
var cross = require('./cross');

//事件处理
var ev = require('./event');

var config = require('./config');

//sdk 版本
var version = config.version;

var yasPath = config.yaPath;

var yasDomain = config.yasDomain;

//应用信息
var appInfo = {
  h: document.domain, //host
  p: window.location.port, //port
  u: window.location.pathname, //url
  //a:window.location.hash,//anchor
  //c:window.document.charset,//code
  ft: 0, //loadFinishTime
  fst: 0, //firstScreenTime
  // dt:document.title,//document title
  sv: '', // YAS版本
  ab: cookies('ab_5') || '',
  op: 'YB_PAGE_OPEN_L',
  apf: window.location.search.indexOf('app_version=') >= 0 ? 'Y' : 'N',
  udid: util.getUdid() // YAS 上报接口 当前的 udid
};

var isApp = /yoho/i.test(navigator.userAgent) || /app_version=/i.test(window.location.search) || !!window.yohoInterface;
var isMobile = /(iPhone|Android|iPad|iPod|iOS)/i.test(navigator.userAgent);
var isWechat = /micromessenger/i.test(navigator.userAgent);
var isMiniProgram = window.__wxjs_environment === 'miniprogram' || /miniProgram/i.test(navigator.userAgent);
var ismyhbuy = /m\.yohobuy\.com/i.test(document.domain);
var isfeature = /feature\.yoho\.cn/i.test(document.domain) || /activity\.yoho\.cn/i.test(document.domain);
var downloadBlackLst = ['m.yohobuy.com/brands', 'm.yohobuy.com/passport'];

//获取跟踪ID
var VisitorId = getVisitorId();

window.addEventListener && window.addEventListener('WeixinJSBridgeReady', function() {
  isMiniProgram = window.__wxjs_environment === 'miniprogram';
}, false)

//用户信息
var custInfo = {
  ak: '',
  cd: VisitorId.cid, //client_id
  vd: (new Date().getTime() + VisitorId.cid),
  ud: '', //uid
  rf: document.referrer, //referer
  ckf: VisitorId.isNew
};

//TODO:用户操作信息
var custOpInfo = {
  mp: '', //mouse postion
  ev: '', //event
  st: 0 //scrollTop
};

var flash = util.flashChecker();

//浏览器信息
var browserInfo = {
  sr: window.screen.width + 'x' + window.screen.height, //screenWidthxscreenHeight
  wr: window.screen.availWidth + 'x' + window.screen.availHeight, //windowWidthxwindowHeight
  sd: window.screen.colorDepth, //screenDepth
  ln: window.navigator.language ? window.navigator.language : window.navigator.browserLanguage, //language
  //bv:window.navigator.userAgent,//browserVersion
  sy: window.navigator.platform, //systemInfo
  ce: window.navigator.cookieEnabled, //cookiesEnabled
  fv: flash.f ? flash.v : 0 //flashVersion
};

// 空方法
var nullFun = function() {};

// 创建空的div,以后所有yas内容都注入该dom下
var yasDombar = document.createElement('div');
document.body.insertBefore(yasDombar, document.body.firstChild);

//入口方法
var _yas = function(initTime, version, tid, uid, geo, selector) {
  window.qs = util.queryString();

  custInfo.ak = tid;
  appInfo.sv = version;
  custInfo.ud = uid ? uid : '';
  custInfo.ts = (new Date()).getTime();

  var channelid = window.qs.yh_channel || util.getChannel();
  if (channelid) {
    appInfo.param = JSON.stringify({C_ID: channelid});
  }

  if (cookies('_yasgeo')) {
    var geoInfo = cookies('_yasgeo').split(',');
    custInfo.la = geoInfo[0];
    custInfo.lo = geoInfo[1];
    cookies('_yasgeo', null, {
      path: "/",
      domain: config.yasDomain,
      expires: 365 * 200
    });
  }

  var beginTime = new Date().getTime();
  var sendFlag = null;
  var isOver3sSend = false;

  appInfo.ft = beginTime - initTime;

  //firstScreenTime
  ev.addEventHandler(window, 'load', function(e) {
    var endTime = new Date().getTime();
    appInfo.fst = endTime - initTime;
    ev.removeEventHandler(window, 'load', arguments.callee);
    window.clearTimeout(sendFlag);
    if (!isOver3sSend) {
      send();
    }
  });

  sendFlag = window.setTimeout(function() {
    appInfo.fst = 0;
    appInfo.fse = '>3s';
    isOver3sSend = true;
    send();
  }, 3000);

  //记录地理信息
  if (geo) {
    util.getGeo(function(lat, lng) {
      if (lat) {
        cookies('_yasgeo', lat + ',' + lng, {
          path: "/",
          domain: yasDomain,
          expires: 365 * 200
        });
      }
    });
  }

  // 进入小程序弹框
  setMiniAppDialog();

  // 设定页面下载条
  setDownloadBar();

  // 页面统计 设定mkt_code
  setMktc();

  // 监控app下载链接,添加union_type
  setUnionType();

  /**
   * 用于统计用户点击的selector元素的序号
   * 记录cookie, 待进入新页面后通过send方法将cookie中的鼠标记录发送并清空.
   *
   */
  if (selector && selector[0]) {
    for (var i = 0, length = selector.length; i < length; i++) {
      selector[i].setAttribute('yoho_index', (i + 1));
    }
  } else {
    /**
     * <a>标签的点击事件,适用于页面跳转的情形
     * 记录cookie, 待进入新页面后通过send方法将cookie中的鼠标记录发送并清空.
     *
     */
    ev.addEventHandler(document, 'click', function(e) {
      e = e || window.event;
      var target = e.target || e.srcElement;
      if (target && (target.nodeName === 'A' || (target.nodeName === 'IMG' && target.parentNode.nodeName === 'A'))) {
        var pos = getMouseEventPosition(e);
        var str = pos.x + ',' + pos.y + ',' + e.type;
        var yoho_index = target.getAttribute('yoho_index') || target.parentNode.getAttribute('yoho_index');
        if (yoho_index) {
          str += ',' + yoho_index;
        }
        cookies('_yasmp', str, {
          path: '/',
          domain: yasDomain,
          expires: 365 * 200
        });
      }
      ix = 0;
    });
  }

  // onerror = handleErr;
  // var txt = "";
  //
  // function handleErr(msg, url, l) {
  //   txt = "This page contains error! \n\n";
  //   txt += "Error message is:" + msg + "\n";
  //   txt += "URL is: " + url + "\n";
  //   txt += "Line is:" + l + "\n\n";

  //   var errString = JSON.stringify({
  //     'er': txt
  //   });
  //   cookies('_yaserror', errString, {
  //     path: '/',
  //     domain: yasDomain,
  //     expires: 365 * 200
  //   });

  //   return false;
  // }

};

function send(callback) {
  var info = util.merge(appInfo, custInfo);
  info = util.merge(info, browserInfo);
  var mktc = getMktc();
  if (mktc) {
    info = util.merge(info, mktc);
  }

  // 鼠标位置
  var mpJson = getMousePosition();
  if (mpJson) {
    info = util.merge(info, mpJson);
    cookies('_yasmp', null, {
      path: "/",
      domain: config.yasDomain,
      expires: 365 * 200
    });
  }

  // 用户自定义信息
  var _custJsonStr = cookies('_yascustjson');
  if (_custJsonStr) {
    var custJson = JSON.parse(_custJsonStr);
    info = util.merge(info, custJson);
    cookies('_yascustjson', null, {
      path: "/",
      domain: config.yasDomain,
      expires: 365 * 200
    });
  }

  // 页面error信息
  // var _yasErrorStr = cookies('_yaserror');
  // if (_yasErrorStr) {
  //   var errorJson = JSON.parse(_yasErrorStr);
  //   info = util.merge(info, errorJson);
  //   cookies('_yaserror', null, {
  //     path: "/",
  //     domain: config.yasDomain,
  //     expires: 365 * 200
  //   });
  // }

  var param = util.genParam(info);
  callback = callback ? callback : function() {};
  cross.imgSend(param, callback);
  var _yasev = cookies('_yasev');
  if (_yasev) {
    cross.imgSend(_yasev, function() {
      cookies('_yasev', null, {
        path: '/',
        domain: config.yasDomain,
        expires: 365 * 200
      });
    });
  }
}

function getVisitorId() {
  var cid = cookies('_yasvd');
  if (cid) {
    return {
      cid: cid,
      isNew: 'N'
    };
  }

  cid = util.Random() ^ util.hashClientInfo() & 2147483647;
  cookies('_yasvd', cid, {
    path: "/",
    domain: yasDomain,
    expires: 365 * 200
  });
  return {
    cid: cid,
    isNew: 'Y'
  };
}

function getMousePosition() {
  var mp = cookies('_yasmp');
  if (mp) {
    var mpObject = mp.split(',');
    if (mpObject.length === 3) {
      return {
        x: mpObject[0],
        y: mpObject[1],
        et: mpObject[2]
      };
    } else if (mpObject.length === 4) {
      return {
        x: mpObject[0],
        y: mpObject[1],
        et: mpObject[2],
        ix: mpObject[3]
      };
    }

  }
  return null;
}

function getMouseEventPosition(e) {
  var x = 0,
    y = 0;

  if (e.pageX || e.pageY) { //Chrome,Safari,FF
    x = e.pageX;
    y = e.pageY;
  } else if (e.clientX || e.clientY) { //IE
    x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }
  x -= window.screen.width / 2;
  y = window.screen.height / 2 - y;
  return {
    x: x,
    y: y
  };
}

function setMktc() {
  var mktc = window.qs.mkt_code || window.qs.union_type || cookies('unionTypeYas') || util.getMktcBySeo();
  if (mktc) {
    var options = {
      path: "/",
      domain: yasDomain,
      expires: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000))
    }

    // 170717 因流量劫持问题要求修改
    if (!cookies('mkt_code') || cookies('mkt_code') !== mktc || mktc === '100000000000349') {
      cookies('mkt_code', mktc, options);
    }

    // if (isWechat) {
    //     // 微信中,不管是否已经种入cookie,直接覆盖
    //     cookies('mkt_code', mktc, options);
    // } else if (!cookies('mkt_code') || mktc === '100000000000349'){
    //     // 如果没有种入mtk_code则种入
    //     cookies('mkt_code', mktc, options);
    // }
  }
}

function getMktc() {
  var mktc = cookies('mkt_code') || window.qs.mkt_code || window.qs.union_type || cookies('unionTypeYas');
  if (mktc) {
    return {
      mktc: mktc
    };
  }
  return null;
}

function setUnionType() {
    var mktc =  window.qs.mkt_code || window.qs.union_type || cookies('unionTypeYas') || util.getMktcBySeo() || cookies('mkt_code') || '100000000000349';
    var aDom = document.getElementsByTagName("a"); //获取页面所有a标签
    for (var i = 0; i < aDom.length; i++) {
      var href = aDom[i].getAttribute('href') || '';
      var isDownappHref = href.indexOf('union.yoho.cn/union/downapp.html') > -1;
      var isAppDownloadsHref = href.indexOf('union.yoho.cn/union/app-downloads.html') > -1;
      var isAddUnion4JumpHref = href.indexOf('union.yoho.cn/union/ClickUnionRest/addUnion4Jump') > -1;

      if (isDownappHref || isAppDownloadsHref || isAddUnion4JumpHref) {
          var params = [];

          if (mktc && href.indexOf('union_type') === -1) {
            params.push('union_type=' + mktc);
          }
          if (href.indexOf('client_id') === -1) {
            params.push('client_id=' + VisitorId.cid);
          }
          if (href.indexOf('openby:yohobuy') === -1 && isAppDownloadsHref) {
            params.push(util.getAppPath());
          }

          if (params.length) {
            if (href.indexOf('?') === -1) {
              href += '?';
              href += params.join('&');
            } else {
              var hrefArray = href.split('?');
              href = hrefArray[0] + '?' + params.join('&') + '&' + hrefArray[1];
            }

            aDom[i].setAttribute('href', href);
          }

          ev.addEventHandler(aDom[i], 'click', function(e) {
            _yas.sendCustomInfo && _yas.sendCustomInfo({
              op: 'YB_DOWNLOAD_C',
              param: JSON.stringify({
                C_ID: window.qs.yh_channel || util.getChannel() || 1,
                TO_URL: e.target.getAttribute('href')
              })
            }, true);
          });
        }
    }
}

// 进入小程序弹框
var miniAppToggle = function() {
  var miniAppDialogBg = document.getElementById('mini-app-dialog-bg');
  var miniAppDialog = document.getElementById('mini-app-dialog');

  if (miniAppDialogBg && miniAppDialog) {
    miniAppDialog.style.display = (miniAppDialog.style.display === 'block' ? 'none' : 'block');
    miniAppDialogBg.style.display = miniAppDialog.style.display;
  }
}

function setMiniAppDialog() {
  if (!isWechat) {
    return false;
  }

  // 设定fontsize
  util.setFontSize();

  var css =  require('../css/wechat-mini-app.css');

  var miniDom = document.createElement('div');
  miniDom.innerHTML = util.getMiniAppDialog();
  yasDombar.appendChild(miniDom);

  var miniAppClose = document.getElementById('mini-app-close');
  var miniAppImg = document.getElementById('mini-app-img');
  var miniAppCodeTimer;

  ev.addEventHandler(miniAppImg, 'touchstart', function(){
    miniAppCodeTimer = setTimeout(function() {
      if (_hmt && _hmt.push) {
        _hmt.push(['_trackEvent', '小程序码', '长按超过1秒']);
      }
    }, 1000);
  });

  ev.addEventHandler(miniAppImg, 'touchend', function(){
    clearTimeout(miniAppCodeTimer);
  });

  ev.addEventHandler(miniAppClose, 'click', function(){
    if (_hmt && _hmt.push) {
      _hmt.push(['_trackEvent', '打开小程序按钮', '关闭']);
    }
    miniAppToggle();
  });

  if ((document.getElementById('main-wrap').getAttribute('data-minipath') || '').indexOf('isOpen=true') > -1) {
    if (_hmt && _hmt.push) {
      _hmt.push(['_trackEvent', '打开小程序按钮', '自动打开']);
    }
    miniAppToggle();
  }
}

function setDownloadBar() {
  var nodownload = document.getElementById('no-download'); // 页面不需要下载条
  var downBar = document.getElementById('top-downloadbar');
  var blackCheck = downloadBlackLst.some(function(url) {
    return new RegExp(url, 'i').test(location.href);
  });

  if (nodownload || window.qs.nodownload || window.qs.openrefer === 'app' || downBar || blackCheck) {
    return;
  }

  if (!isApp && !isMiniProgram && (isMobile || isWechat) && (ismyhbuy || isfeature)) {
    downBar = document.getElementById('float-layer-app');
    if (downBar) {
      // 存在下载条时,删除
      downBar.parentNode.removeChild(downBar);
    }

    if (cookies('_downloadBar')) {
      return;
    }

    // 设定fontsize
    util.setFontSize();

    var css =  require('../css/download.css');

    var downloadDom = document.createElement('div');
    downloadDom.innerHTML = util.getDownloadStr(isWechat);
    yasDombar.appendChild(downloadDom);

    // bindevent
    var closeDom = document.getElementById('download-close');

    ev.addEventHandler(closeDom, 'click', function(){
      cookies('_downloadBar', 'close', {
        path: "/",
        domain: config.yasDomain,
        expires: new Date(Date.now() + (60 * 1000))
      });
      cross.downloadSend('//m.yohobuy.com/activitylog.json?close', '');
      downloadDom.style.display = 'none';

      if (_hmt && _hmt.push) {
        _hmt.push(['_trackEvent', '顶部下载条目', '点击关闭Banner']);
      }
    });

    var goDom = document.getElementById('download-go');
    ev.addEventHandler(goDom, 'click', function(e){
      cross.downloadSend('//m.yohobuy.com/activitylog.json?download', '');

      if (_hmt && _hmt.push) {
        _hmt.push(['_trackEvent', '顶部下载条目', '所有打开和下载', encodeURIComponent(e.currentTarget.getAttribute('href'))]);
      }
    });

    var wechatDom = document.getElementById('download-wechat');
    ev.addEventHandler(wechatDom, 'click', function(){
      cross.downloadSend('//m.yohobuy.com/activitylog.json?attenion', '');

      if (_hmt && _hmt.push) {
        _hmt.push(['_trackEvent', '顶部下载条目', '微信里面关注']);
      }
    });

    var miniAppOpen = document.getElementById('mini-app-open');
    ev.addEventHandler(miniAppOpen, 'click', function(){
      if (_hmt && _hmt.push) {
        _hmt.push(['_trackEvent', '打开小程序按钮', '打开']);
      }
      miniAppToggle();
    });
  }
}

//超过5次发送自定义信息
var evTimes = 0;

//添加或发送自定义信息
_yas.add = function(trackType, input, action, label, value) {
  if (evTimes > 3) {
    cross.imgSend(cookies('_yasev'), function() {
      cookies('_yasev', null, {
        path: "/",
        domain: config.yasDomain,
        expires: 365 * 200
      });
      evTimes = 0;
      _addEv2Cookies(trackType, input, action, label, value);
    });
  } else {
    _addEv2Cookies(trackType, input, action, label, value);
  }
};

//把自定义事件信息加入cookies
function _addEv2Cookies(trackType, input, action, label, value) {
  var ev = cookies('_yasev');
  if (ev) {
    ev += '&';
  } else {
    ev = '';
  }
  cookies('_yasev', ev + 'vd=' + custInfo.vd + '&t=' + trackType + '&i=' + input + '&l=' + label + '&v=' + value, {
    path: "/",
    domain: yasDomain,
    expires: 365 * 200
  });
  evTimes++;
}

/**
 * 发送用户鼠标事件的位置, 此方法提供给用户调用, 本方法不对参数合法性进行检查, 调用者自己保证。
 * @param e 用户鼠标事件, 必选参数
 * @param flag 用户事件执行后, 页面是否停留当前页, 是可选参数
 *        true表示停留,false表示跳转, 默认值是false
 *        取值是false时, 记录cookie, 待进入新页面后通过send方法将cookie中的事件记录发送并清空。
 */
_yas.sendMouseEvent = function(e, flag) {
  e = e || window.event;
  var pos = getMouseEventPosition(e);

  if (!flag) {
    cookies('_yasmp', pos.x + ',' + pos.y + ',' + e.type, {
      path: '/',
      domain: yasDomain,
      expires: 365 * 200
    });
  } else {
    var mp = {
      x: pos.x,
      y: pos.y,
      et: e.type
    };
    var info = util.merge(appInfo, custInfo);
    info = util.merge(info, browserInfo);
    info = util.merge(info, mp);
    var param = util.genParam(info);
    cross.imgSend(param, function() {});
  }
};

/**
 * 发送用户订制信息, 此方法提供给用户调用, 本方法不对参数合法性进行检查, 调用者自己保证。
 * @param json 用户订制信息, 必选参数,采用json格式
 * @param flag 用户事件执行后, 页面是否停留当前页, 是可选参数, 默认是页面跳转
 *        true表示停留,false表示跳转, 默认值是false
 *        取值是false时, 记录cookie, 待进入新页面后通过send方法将cookie中的事件记录发送并清空。
 * 本方法使用场合:
 *        1. wap中的事件上报
 *        2. app和wap中都需要的事件上报
 */
_yas.sendCustomInfo = function(json, flag, callback) {
  if (window.appBaseLogs && json.appop) {
    // 从app中打开的wap页
    json.op = json.appop;
    return _yas.sendAppLogs(json, true);
  } else {
    // wap页上报数据中去掉 appop
    delete json.appop;
    json.ts = (new Date()).getTime();

    if (!flag) {
      var string = JSON.stringify(json);
      cookies('_yascustjson', string, {
        path: '/',
        domain: yasDomain,
        expires: 365 * 200
      });
    } else {
      var info = util.merge(appInfo, custInfo);
      info = util.merge(info, browserInfo);
      info = util.merge(info, json);
      var mktc = getMktc();
      if (mktc) {
        info = util.merge(info, mktc);
      }
      var param = util.genParam(info);
      cross.imgSend(param, callback);
    }
  }
};

/**
 * 发送用户订制信息, 此方法提供给用户调用, 本方法不对参数合法性进行检查, 调用者自己保证。(app上报数据使用)
 * @param json 用户订制信息, 必选参数,采用json格式
 * @param asyncindx 是否需要同步indx
 *        true表示同步,false表示不需要同步, 默认值是false
 * 本方法使用场合:
 *        1. app中的事件上报
 */
_yas.sendAppLogs = function(json, asyncindx) {
  if (!window.appBaseLogs) {
    return;
  }

  // 数据整合
  var param = JSON.parse(json.param);
  if (param.F_URL) {
    param.F_URL = decodeURIComponent(param.F_URL);
  }

  // abtype
  var ev = window.appBaseLogs.events[0];
  if(ev.abtype) {
    param.AB_TYPE = ev.abtype;
  }
  var event = util.merge(ev, {
    ts: (new Date()).getTime().toString(),
    indx: ++window.indx,
    op: json.appop,
    param: param
  });
  var logs = util.merge(window.appBaseLogs, {
    events: [event]
  });

  // 上报数据
  cross.appSend("_mlogs=" + encodeURIComponent(JSON.stringify(logs)));
  window._yasloaded = true;

  if (asyncindx) { // 将indx同步到app中
    if (window.isandroidyas) {
      window.prompt(JSON.stringify({
        method: 'set.analyticEventIndex',
        arguments: {
          indx: window.indx
        }
      }));
    } else {
      window.yohoInterface.triggerEvent(nullFun, nullFun, {
        method: 'set.analyticEventIndex',
        arguments: {
          indx: window.indx
        }
      });
    }
  }
}

function appPageOpen(data, actionUrl) {
  if (!data.av) {
    return;
  }
  window.indx = data.indx;
  window.originUrl = data.origin || location.href;
  window.appBaseLogs = {
    device: {
      ak: data.ak,
      udid: data.udid,
    },
    status: [{
      av: data.av,
      udid: data.udid,
      sid: data.sid,
    }],
    events: [{
      uid: data.uid,
      sid: data.sid,
      abtype: data.abtype
    }]
  }

  // 上报页面打开事件
  if (window.originUrl && window.qs) {
    _yas.sendAppLogs({
      appop: 'YB_H5_PAGE_OPEN_L',
      param: JSON.stringify({
        C_ID: window.qs.yh_channel || util.getChannel() || 1,
        PAGE_URL: window.originUrl,
        PAGE_NAME: decodeURI(window.qs.title || document.title),
        ACTION_URL: actionUrl
      })
    }, false);
  }
}

if (navigator.userAgent.indexOf('YohoBuy-android-yas') > -1) {
  // 针对android商品详情页做特殊处理
  window.isandroidyas = true;
  var data = window.prompt(JSON.stringify({
    method: 'get.analyticAppData'
  }));

  appPageOpen(JSON.parse(data || '{}'));
} else {
  // 监听app加载的deviceready事件
  ev.addEventHandler(document, 'deviceready', function(e) {
    window._yasloaded = false;

    var actionUrl = [];
    var aDom = document.getElementsByTagName("a"); //获取页面所有a标签
    for (var i = 0; i < aDom.length; i++) {
      var href = aDom[i].getAttribute('href');
      if (href && !/^#.*$/.test(href) && !/^javascript.*$/i.test(href)) {
        actionUrl.push(href);
      }
    }

    ev.addEventHandler(document, 'click', function(e) {
      if (window.originUrl) {
        e = e || window.event;
        var target = e.target || e.srcElement;

        target = util.closest(target, 'a');
        if (target) {
          var param = {
            C_ID: window.qs.yh_channel || util.getChannel() || 1,
            PAGE_URL: window.originUrl,
            PAGE_NAME: decodeURI(window.qs.title || document.title),
            F_URL: target.getAttribute('href')
          }

          var fp = target.getAttribute('fp');
          if (fp) {
            // 增加楼层信息
            fp = JSON.parse(fp);
            param.F_ID = fp.F_ID;
            param.F_NM = fp.F_NM;
            param.F_INDEX = fp.F_INDEX;
            param.I_INDEX = fp.I_INDEX;
            param.I_NM = fp.I_NM || '';
          }

          // 上报曝光事件
          _yas.sendAppLogs({
            appop: 'YB_H5_PAGE_FLR_C',
            param: JSON.stringify(param)
          }, true);
        }
      }
    });

    window.yohoInterface.triggerEvent(function(data) {
      appPageOpen(data, actionUrl);
    }, nullFun, {
      method: 'get.analyticAppData'
    });

    // 同步indx(需延迟处理)
    var timer = setInterval(function() {
      if (window._yasloaded) {
        clearInterval(timer);
        window.yohoInterface.triggerEvent(nullFun, nullFun, {
          method: 'set.analyticEventIndex',
          arguments: {
            indx: window.indx
          }
        });
      }
    }, 500);
  });
}

module.exports = _yas;