/**
 * Created by F on 17/5/9.
 * 分类列表统计打点
 * rank_click
 * rank_down
 * 进入专区-down
 * click: 添加count-click 类
 * download：添加count-download 类
 * portalDown: 添加count-portal-download 类
 * 数据写在父节点,并添加count-list-item 类
 */
(function () {

  var IsSpider = function() {
    return !!window.navigator.userAgent.toLowerCase().match('spider') || !!window.navigator.userAgent.toLowerCase().match('bot');
  }

  var count = {
    url: '/stat/report/',
    adUrl: '/stat/ad/report/',
    newsUrl: '/nstat/report/log',
    type: 'POST',
    local: window.localStorage,
    cacheStatusList: [],
    countClick: 'count-click',
    countDown: '.count-download',
    countItem: '.count-list-item',
    adCountClick: '.ad-count-click',
    adCountDown: '.ad-count-down',
    adCountItem: '.ad-count-item',
    countPortalDown: '.count-portal-download',
    xlyx: '[type=xlyx]',
    recommend: '[type=template]',
    touch: ('ontouchstart' in window),
    mouse: ('onmousedown' in window),
    game_recommend: '.game-recommend',
    status: true,
    dotstatus: true,
    isVisit: function (item) {
      const el = item[0];
      if (el) {
        const rect = el.getBoundingClientRect() || '';
        return (
          rect.top >= 0 &&
          rect.left >= 0 &&
          rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
          rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
      }

    },
    init: function () {

      var _this = this;

      // rank_down
      $(document).on('click', _this.countDown, function () {
        var _that = $(this);
        if (_this.adjustRec(_that)) {
          _this.recommend_count(_this.getParentNode($(this)), 'rec_down');
          _this.recommend_count(_this.getParentNode($(this)), 'rec_click');
        } else {
          _this.count(_this.getParentNode($(this)), 'rank_down');
          _this.count(_this.getParentNode($(this)), 'rank_click');
        }
      });

      // rank_click
      var event = "click";
      $(document).on(event, function (event) {

        var _that = $(event.target);
        if (_that.hasClass(_this.countClick) || _that.closest('.count-click').length > 0) {
          _this.local.removeItem('count');

          if (_this.adjustRec(_that)) {
            _this.setLocalInfo('count', _this.setRecommendData(_this.getParentNode(_that), 'rec_detaildown'));
            _this.recommend_count(_this.getParentNode(_that), 'rec_click');
          } else {
            _this.count(_this.getParentNode(_that), 'rank_click');
            _this.setLocalInfo('count', _this.setData(_this.getParentNode(_that), 'rec_down'));
          }

          // 当前元素即有a标签，又是btn跳转时，禁止a标签默认行为
          var item = _that.hasClass(_this.countClick) ? _that : _that.closest('.count-click');
          var tagName = item.prop('tagName').toLowerCase();
          var btn = item.prop('type');
          if (tagName === 'a' && btn === 'btn') {
            //event.preventDefault();
          }
        }
      });

      // 首屏曝光打点,需延迟,有些游戏为异步加载
      setTimeout(function () {
        _this.count_show();
        _this.ad_count_show();
      }, 1000);

      // rank_show
      _this.addHandler(document, 'scroll', _this.debounce(function () {
        _this.count_show();
        _this.ad_count_show();
      }, 100));

      // portal rank_down
      $(_this.countPortalDown).on('click', function () {
        var info = _this.getLocalInfo('count');
        var AdInfo = _this.getLocalInfo('ad-count');
        if (info) {
          _this.ajax({
            data: info,
            callback: function () {
              console.log('success');
            }
          })
        }

        if (AdInfo) {
          _this.adAjax({
            data: AdInfo,
            callback: function () {
              console.log('success');
            }
          })
        }
      });

      _this.initAdCount();
    },

    adjustRec: function (_that) {
      var _this = this;
      if (_that.closest(_this.xlyx).length > 0 || _that.closest(_this.recommend).length > 0 || _that.closest(_this.game_recommend).length > 0) {
        return true;
      } else {
        return false;
      }
    },

    isExpose: function (item) {
      var _this = this;
      var gameId = item.data('gameId');
      var scenarioId;

      if (item.closest('[type=xlyx]').length > 0) {
        scenarioId = item.closest('[type=xlyx]').siblings('.xlyx_template').data('scenarioId');
      } else if (item.closest(_this.game_recommend).length > 0) {
        scenarioId = item.closest(_this.game_recommend).siblings('.xlyx_template').data('scenarioId');
      } else if (item.closest('[type=template]').length > 0) {
        scenarioId = item.closest('[type=template]').data('scenarioId');
      } else {
        scenarioId = 'public'
      }

      return 'count' + gameId + scenarioId;
    },

    count_show: function () {
      var _this = this;
      var areaClassList = $(_this.countItem);
      var areaLength = areaClassList.length;

      for (var k = 0; k < areaLength; k++) {
        var $currentElement = $(areaClassList[k]);
        if (_this.isVisit($currentElement)) {
          if (!/@\w+@/.test($currentElement.data('gameId')) && _this.cacheStatusList['count' + $currentElement.data('gameId')] === undefined) {
            if (_this.adjustRec($currentElement)) {
              _this.recommend_count($currentElement, 'rec_show');
            } else {
              _this.count($currentElement, 'rank_show');
            }
            _this.cacheStatusList['count' + $currentElement.data('gameId')] = true;
          }
        }
      }
    },

    getParentNode: function (item) {
      var _this = this;
      return item.closest(_this.countItem)
    },

    setData: function (item, type, portal) {
      var _this = this;
      return {
        ac: type,
        a1: portal ? 'xqy_' + _this.getRankId(item) : _this.getRankId(item),
        a2: item.data('gameId'),
        a3: _this.a3Controller(item),
        a4: item.data('filter')
      };
    },

    setRecommendData: function (item, type) {
      var _this = this, an;

      if (item.closest(_this.xlyx).length > 0 || item.closest(_this.game_recommend).length > 0) {
        an = item.closest(_this.countItem).data('an');
        an.sgid = item.closest(_this.game_recommend).data('fromDownId')
      } else {
        an = item.closest(_this.countItem).data('an');
      }

      return {
        ac: type,
        a1: item.data('slotId'),
        a2: item.data('gameId'),
        an: JSON.stringify(an)
      }
    },

    a3Controller: function (item) {
      var a3 = [item.data('rankType')];
      var categoryId = item.data('categoryId');
      categoryId ? a3.unshift(categoryId) : '';
      return a3.join('_');
    },
    count: function (item, type, href) {
      var _this = this;
      _this.ajax({
        data: _this.setData(item, type),
        callback: function () {
          if (href === true) {
            window.location.href = item.data('href');
          }
        }
      })
    },
    recommend_count: function (item, type, href) {
      var _this = this;
      _this.ajax({
        data: _this.setRecommendData(item, type),
        callback: function () {
          if (href === true) {
            window.location.href = item.data('href');
          }
        }
      })
    },
    ajax: function (arg) {
      var that = this;
      if (!IsSpider()) {
        $.ajax({
          type: that.type,
          url: that.url,
          data: arg.data,
          timeout: 4000,
          beforeSend: function () {
            // console.log('start');
          },
          success: function (data) {
            // console.log(data);
            arg.callback();
          },
          error: function (err) {
            console.log(err);
            // arg.callback();
          }
        });
      } else {
        console.log(window.navigator.userAgent.toLowerCase(), '是爬虫');
      }
    },
    getRankId: function (item) {
      // pointsId: 分桶ID
      // orderId: 顺序
      // accessId: 访问ID
      var points = item.data('bucketId');
      var order = item.data('order');
      var _this = this;
      return [_this.getAccessId(), points, order].join('_');
    },
    getAccessId: function () {
      var _this = this;
      return this.getTimestamp() + this.getRandom();
    },
    getRandom: function () {
      return Math.floor(Math.random() * (99999 - 10000) + 10000);
    },
    getTimestamp: function () {
      return new Date().valueOf();
    },
    checkKey: function (key) {
      if (typeof key === 'string' && key !== '' && !!this.local) {
        return true;
      } else {
        return false;
      }
    },
    setLocalInfo: function (key, data) {
      var setDate = JSON.stringify(data);

      if (this.checkKey(key)) {
        localStorage.setItem(key, setDate);
      }
    },
    getLocalInfo: function (key) {
      if (this.checkKey(key)) {
        var info = localStorage.getItem(key);
        return JSON.parse(info);
      }
    },
    addHandler: function (element, type, handler) {
      $(element).on(type, handler);
    },
    debounce: function (func, wait, immediate) {
      var timeout;
      return function debounceHandler() {
        var context = this, args = arguments;
        var later = function () {
          timeout = null;
          if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
      };
    },
    getAdCountInfo: function (action, item) {
      var _this = this;
      var countItem = item.closest(_this.adCountItem);
      return {
        ac: action,
        a1: countItem.data('recId'),
        a2: countItem.data('gameId'),
        a4: countItem.data('picId'),
        adpId: countItem.data('adpId'),
        admId: countItem.data('admId')
      }
    },
    adAjax: function (arg) {
      var that = this;
      if (!IsSpider()) {
        $.ajax({
          type: that.type,
          url: that.adUrl,
          data: arg.data,
          timeout: 4000,
          beforeSend: function () {
            // console.log('start');
          },
          success: function (data) {
            console.log(data);
            // arg.callback();
          },
          error: function (err) {
            console.log(err);
            // arg.callback();
          }
        });
      } else {
        console.log(window.navigator.userAgent.toLowerCase(), '是爬虫');
      }
    },
    initAdCount: function () {
      var _this = this;
      $(document)
        .on('click', _this.adCountDown, function () {
          _this.adCount('recsys_down', $(this));
          _this.adCount('recsys_click', $(this));
        })
        .on('click', _this.adCountClick, function () {
          var $this = $(this);
          _this.adCount('recsys_click', $this);
          _this.setLocalInfo('ad-count', _this.getAdCountInfo('recsys_detaildown', $this));
        });
    },
    adCount: function (action, item) {
      var info = this.getAdCountInfo(action, item);
      this.adAjax({ data: info });
    },
    ad_count_show: function () {
      var _this = this;
      var areaClassList = $(_this.adCountItem);
      var areaLength = areaClassList.length;

      for (var k = 0; k < areaLength; k++) {
        var $currentElement = $(areaClassList[k]);
        if (_this.isVisit($currentElement)) {
          if (!/@\w+@/.test($currentElement.data('gameId')) && _this.cacheStatusList['ad-count' + $currentElement.data('gameId')] === undefined) {

            _this.adCount('recsys_show', $currentElement);
            _this.cacheStatusList['ad-count' + $currentElement.data('gameId')] = true;
          }
        }
      }
    },
    // 资讯打点
    newsinit() {
      const _this = this;
      const lowestDot = $('.statistics-lowerdot');
      const needExposureEle = $('.statistics-show');
      const needLength = needExposureEle.length;
      for (let k = 0; k < needLength; k++) {
        const $currentElement = $(needExposureEle[k]);
        $currentElement.data('showstatus', true);
      }
      _this.news_count_show('news_expose');

      $(document).on('scroll', function () {
        _this.news_count_show('news_expose');
        // 当资讯页触底的时候的时候触发打点
        var aa = _this.isVisit(lowestDot);
        if (_this.isVisit(lowestDot) && _this.dotstatus) {
          _this.news_count(lowestDot, 'news_finsh', 0);
          _this.dotstatus = false;
        }
      });

      // 点击资讯的时候上报点击打点news_click;
      $(document).on('click', '.statistics-click', function () {
        const ele = $(this);
        const type = 'news_click';
        const click_game_id = type + ele.data('gameid');
        let newsClickCount = _this.local.getItem(click_game_id) || 0;
        newsClickCount++;
        _this.news_count(ele, type, newsClickCount);
      });

      // 用户离开该资讯页面时打点
      const offElement = $('.statistics-off');
      if (offElement.length) {
        window.onbeforeunload = function () {
          const endTime = +new Date();
          const stayTime = endTime - startTime;
          const type = 'news_stay';
          let datas = _this.setNewsCount(offElement, type, 0, stayTime);
          _this.newsajax({
            data: datas,
            callback(ele) {
              console.log('上报成功')
            }
          })
        };
      }
    },

    news_count(ele, type, numbers) {
      const _this = this;
      const data = _this.setNewsCount(ele, type, numbers);
      _this.newsajax({
        data: _this.setNewsCount(ele, type, numbers),
        callback(ele) {
          console.log('回调成功');
          // const game_id = type + ele.data('gameid');
          // _this.setLocalInfo(game_id, numbers);
        }
      });
    },
    setNewsCount(ele, type, numbers, times) {
      const newsId = ele.data('newsid') || '';
      const gameId = ele.data('gameid') || '';
      const businessed = ele.data('businessid');
      const uid = ele.data('uid') || '';
      const pageid = ele.data('pageid') || '';
      let stayTime = times || '';
      return {
        ac: type,
        data: `newsId=${newsId}\`gameId=${gameId}\`businessed=${businessed}\`uid=${uid}\`pageid=${pageid}\`staytime=${stayTime}`,
      };
    },
    news_count_show(type) {
      const _this = this;
      const needExposureEle = $('.statistics-show');
      const needLength = needExposureEle.length;
      for (let k = 0; k < needLength; k++) {
        const $currentElement = $(needExposureEle[k]);
        const game_id = type + $currentElement.data('gameid');
        const elestatus = $currentElement.data('showstatus');

        if (_this.isVisit($currentElement) && elestatus) {
          let exposureCount = _this.local.getItem(game_id) || 0;
          exposureCount++;
          _this.news_count($currentElement, type, exposureCount);
          _this.status = false;
          $currentElement.data('showstatus', false)
        } else if (!_this.isVisit($currentElement) && !elestatus) {
          $currentElement.data('showstatus', true);
        }



      }
    },
    news_click_count(ele, type) {
      const click_game_id = type + ele.data('gameId');
      // _this指向
      const newsClickCount = this.local.getItem(click_game_id) || 0;
      this.news_count(ele, type, newsClickCount);
    },
    newsajax(arg) {
      const that = this;
      if (!IsSpider()) {
        $.ajax({
          type: that.type,
          url: that.newsUrl,
          data: arg.data,
          timeout: 4000,
          beforeSend() {
            // console.log('start');
          },
          success(data) {
            // console.log(data);
            arg.callback();
          },
          error(err) {
            console.log('error', err);
            // arg.callback();
          }
        });
      } else {
        console.log(window.navigator.userAgent.toLowerCase(), '是爬虫');
      }
    },

  };
  count.init();
  count.newsinit();


  window.countFunc = count;
})();
