common.js 18.8 KB
Newer Older
txy committed
1 2

// 公共变量
txy committed
3
var activityCode = typeof rules !== 'undefined' ? rules.acActivity.code : '';
txy committed
4
var baseUrl = "https://space-api.check.icaremgt.com";
txy committed
5
var manageUrl = "http://api-admin-manage.check.icaremgt.com";
txy committed
6

txy committed
7 8 9
// 防止投票连点
var gb_vote_loaded = false

txy committed
10 11 12
if(typeof data !== 'undefined'){
  data.htmlJson = JSON.parse(data.htmlJson);
}
txy committed
13

14 15 16 17
// 分享用户信息
var shareUserId = '';
var shareUserName = '';

txy committed
18 19 20 21 22 23 24 25 26
// 设置token
function setToken(){
  if(user.token !== '') {
    sessionStorage.setItem('x-token', user.token);
  }else {
    sessionStorage.setItem('x-token', '');
  }
}

胡畅 committed
27 28 29 30 31 32 33 34 35 36 37 38
// 机构id
function orgIdFn(id) {
    var signupOrg = rules.acActivityOrgs
    var org = signupOrg && signupOrg.filter(function(item){
        return id == item.id
    })
    if(org.length == 1) {
        return org[0]
    }else {
        return null
    }
}
txy committed
39 40
// 获取token
function getToken() {
txy committed
41 42 43
  // var t = sessionStorage.getItem('x-token');
  // return t
  return user.token
txy committed
44 45
}

txy committed
46 47
// 获取域名及二级目录
function getBaseOrigin(){
txy committed
48
  var _base = '';
txy committed
49 50 51 52
  var _origin = window.location.origin;
  var _pathname = window.location.pathname;
  var index = _pathname.indexOf('/ACTIVITY');
  var _secondFolder = '';
txy committed
53 54
  
  if(index !== 0){
txy committed
55
      _secondFolder = _pathname.slice(0,index);
txy committed
56
  }
txy committed
57
  _base = _origin + _secondFolder;
txy committed
58 59 60 61 62 63 64 65

  return _base;
}

// 页面跳转
function transPage(_pageNumber, _activityCode, _token, _addParam) {
  var url = '';
  var _base = '';
66 67
  var _urlParam = getRequest();
  var _newUrlParam = '';
txy committed
68
  _base = getBaseOrigin();
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

  // 报名页之外的页面过滤url参数-userId
  if(_pageNumber !== '2'){
    // 移除userId参数
    delete _urlParam.userId;
    var flag = false;
    if(!$.isEmptyObject(_urlParam)){
      for(var key in _urlParam){
        // 第一次进入
        if(!flag){
          _newUrlParam += '?'+key+'='+_urlParam[key];
          flag = true;
        }else { 
          _newUrlParam += '&'+key+'='+_urlParam[key];
        }
      }
    }else {
      _newUrlParam = '';
    }
  }else {
    // 报名页面正常携带参数
    _newUrlParam = window.location.search;
  }

  if (typeof _newUrlParam !== 'undefined' && _newUrlParam !== '') {
      url = _base + "/ACTIVITY/view/" + _activityCode + "/" + _pageNumber + _newUrlParam + (_addParam !== undefined ? ('&' + _addParam) : '');
txy committed
95
  } else {
txy committed
96
      url = _base + "/ACTIVITY/view/" + _activityCode + "/" + _pageNumber + (_addParam !== undefined ? ('?' + _addParam) : '');
txy committed
97 98
  }

txy committed
99 100 101 102
  // var _form = document.createElement('form');
  // _form.action = url;
  // _form.method = "post";
  // _form.style.display = "none";
txy committed
103

txy committed
104 105 106 107 108 109 110
  // var inputToken = document.createElement('input');
  // inputToken.value = _token;
  // inputToken.name = 'x-token';
  // _form.appendChild(inputToken);
  // document.body.appendChild(_form);
  // _form.submit();
  window.location.href = url;
txy committed
111 112 113 114 115 116 117 118 119 120 121 122
}

// 获取URL中指定参数
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
      return unescape(r[2]);
  }
  return null;
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136
// 获取url所有参数
function getRequest() {
  var url = window.location.search; //获取url中"?"符后的字串
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for(var i = 0; i < strs.length; i ++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}

txy committed
137

txy committed
138 139 140
// 加载HTML结构
function loadHtmlJson() {
  $('body').prepend(json2html(data.htmlJson));
txy committed
141
  var _relationship = JSON.parse(data.relationship);
txy committed
142 143 144 145 146 147
  for(var i=0;i<_relationship.childs.length;i++) {
      var _page = _relationship.childs[i].page
      var _pageNumber = _relationship.childs[i].pageNumber
      $('body').prepend(json2html(JSON.parse(data[_page].htmlJson)));
      $('#html-template-'+_pageNumber).addClass('global-none')
  }
txy committed
148 149
}

txy committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
// 获取机构名称
function getOrgNameFn(callback) {
  var signupId = getQueryString('bindId')
  var orgId = orgIdFn(signupId).orgId
  $.ajax({
      type: 'GET',
      url: baseUrl + '/ORG/hospital/community/hospitalInfo/' + orgId,
      headers: {
          'x-token': getToken()
      },
      success: function(data) {
          if(data.code == 200) {
            callback && callback(data)
          }
      },
txy committed
165
      error: function(data) {
txy committed
166
          $.dialog({
txy committed
167 168
            type : 'tips',
            autoClose : 3000,
txy committed
169
            infoText : data.responseJSON.message
txy committed
170
        });
txy committed
171 172 173 174
      }
  })
}

txy committed
175 176
// 关注弹出框
function appendAttentionDialog() {
txy committed
177 178 179 180 181 182 183 184 185 186
  var bindId = getQueryString("bindId");
  var orgQrCode = '';
  var orgId = '';

  for(var k = 0; k < rules.acActivityOrgs.length; k++){
    if(rules.acActivityOrgs[k].id == bindId){
      orgId = rules.acActivityOrgs[k].orgId;
      orgQrCode = rules.acActivityOrgs[k].qrCodeUrl;
      break;
    }
txy committed
187
  }
txy committed
188

txy committed
189 190 191 192 193 194 195 196
  var str = '<section id="html-container-attention" style="display: none;">'+
              '<div>'+
                '<div class="c-modal-wrap">'+
                  '<div class="mshe-mask"></div> '+
                  '<div class="c-modal">'+
                    '<div class="modal-dialog">'+
                      '<div c_type="dialog" c_typename="dialog_playerVote1" class="modal-content" style="background: rgb(255, 255, 255);">'+
                      '<div class="modal-header">'+
txy committed
197
                        '<img src="http://qnfile.icareyou.net/363a344aa7424d219a5fc86eff7265751561343712294.jpg" class="header-pic">'+
txy committed
198 199 200 201
                      '</div>'+ 
                      '<div class="modal-body">'+
                        '<p class="struct">长按关注后继续活动</p>'+
                        '<div>'+
txy committed
202
                          '<img src="'+ orgQrCode +'" alt="" style="width: 100%;">'+
txy committed
203 204 205 206 207
                        '</div>'+
                      '</div>'+
                      '<div class="modal-close">'+
                        '<img src="http://qnfile.icareyou.net/ddae57885c424abdb13d37c78038c6a01561343787282.jpg">'+
                      '</div>'+
txy committed
208 209 210 211 212
                      '</div>'+
                    '</div>'+
                  '</div>'+
                '</div>'+
              '</div>'+
txy committed
213
            '</section>';
txy committed
214 215

  $('body').prepend(str);
txy committed
216 217
  // 事件绑定
  $("#html-container-attention .modal-close").off("click").on("click", function(){
txy committed
218
    $("#html-container-attention").fadeOut();
txy committed
219 220
  });

txy committed
221 222 223 224 225 226
  // 获取机构名称
  getOrgNameFn(function(data){
    var orgName = '长按关注'+  data.records.orgName +'后继续活动';
    $('#html-container-attention .modal-body .struct').text(orgName);
  });

txy committed
227
  // 未关注过默认显示弹出框  
txy committed
228
  if (!user.attention){
txy committed
229
    $("#html-container-attention").fadeIn('normal', function() {
230
      // $(document).scrollTop(0);
txy committed
231
    });
txy committed
232 233 234
  }
}

txy committed
235 236
// 显示强关弹出框
function showAttentionDialog() {
txy committed
237
  $("#html-container-attention").fadeIn('normal', function() {
238
    // $(document).scrollTop(0);
txy committed
239
  });
txy committed
240
}
txy committed
241

txy committed
242 243 244 245 246 247 248
// 隐藏强关弹出框
function hideAttentionDialog() {
  $("#html-container-attention").hide();
}

// 不在审核页面插入强关弹出框
if(typeof user !== 'undefined' && $("#examineTitle").length === 0){
txy committed
249 250
  appendAttentionDialog();
}
txy committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

// 判断是否关注
function isAttention(successCallback,errorCallback) {
  // 未关注
  if(!user.attention){
    if(errorCallback) {
      errorCallback();
    }else {
      // 强关弹出框
      showAttentionDialog();
    }
  } else {
    successCallback && successCallback();
  }
}
txy committed
266

txy committed
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
// 是否报名
function isSignUp(successCallback,errorCallback) {
  var _t = getToken();
  // 已报名
  if(user.reviewStatus !== '') {
      switch (user.reviewStatus) {
          // 0-待审核
          case 0:
              alert('您的报名信息正在审核中...');
          break;
          // 1-审核通过
          case 1:
            if(successCallback){
              successCallback();
            }else {
              alert('您当前已通过报名,请到个人主页去拉票!');
            }
          break;
          // 2-审核未通过
          case 2:
              alert('审核未通过!');
              transPage('2',activityCode,_t);
          break;
          default:
              break;
      }
  } else {// 未报名
    if(errorCallback) {
      errorCallback();
    }else {
      // 跳转到报名页面 
      transPage('2',activityCode,_t);
    }
  }
txy committed
301 302 303 304 305 306 307 308 309 310 311 312
}

// 获取活动名称
function getActivityTitle() {
  var activityCode = getQueryString('activityCode');
  var params = {
    activityCode: activityCode
  }
  $.ajax({
      type: 'GET',
      url: baseUrl + '/ACTIVITY/'+ activityCode +'/settings',
      data: params,
txy committed
313 314 315
      headers: {
        'x-token': getToken()
      },
txy committed
316 317 318 319
      success: function(data) {
          if(data.status == 200) {
            var title = data.result.settings.szText.h5Title;
            document.title = title;
txy committed
320 321

            var $body = $('body');
txy committed
322
            var $iframe = $('<iframe src=""></iframe>');
txy committed
323 324 325 326 327
            $iframe.on('load',function() {
              setTimeout(function() {
                  $iframe.off('load').remove();
              }, 0);
            }).appendTo($body);
txy committed
328 329 330 331 332 333 334 335 336 337
          }
      },
      error: function() {
          $.dialog({
              type : 'tips',
              autoClose : 3000,
              infoText : '请求超时,请尝试刷新页面!'
          });
      }
  })
txy committed
338 339
}

txy committed
340
// 加载loading
txy committed
341
function showLoading(msg){
txy committed
342 343
  $.dialog({
    type : 'info',
txy committed
344
    infoText : msg ? msg : '加载中…',
txy committed
345 346 347 348 349 350 351 352 353 354
    infoIcon : 'https://raw.githubusercontent.com/tinytxy/h5_activity_github/master/showPhotos/images/loading_2.gif',
    direction: '',
	  align: 'center'
  });
}
// 关闭loading
function hideLoading() {
  $.dialog.close();
}

txy committed
355 356 357 358 359 360 361 362 363
/* ***********************弹出框控制全部逻辑************************** */
// 投票
function voteClickFn(params, successCallback, errorCallback){ 

  if(gb_vote_loaded) {
    return
  }
  gb_vote_loaded = true;

364 365 366
  shareUserId = params.userId;
  shareUserName  = params.userName;
  
txy committed
367 368 369 370 371 372 373 374 375 376 377 378
  $.ajax({
    type: 'PUT',
    url: baseUrl + '/ACTIVITY/sz/vote/' + activityCode,
    data: params,
    headers: {
        'x-token': getToken()
    },
    success: function(data) {
        if(data.status == 200) {
          // 已报名-通过审核
          if(user.reviewStatus === 1) {
            $('#html-template-4 .struct span').text(data.result.voteNumDay)
txy committed
379
            $('#html-template-4').fadeIn('normal', function() {
380
              // $(document).scrollTop(0);
txy committed
381
            });
txy committed
382 383
          }else {
            $('#html-template-6 .struct span').text(data.result.voteNumDay)
txy committed
384
            $('#html-template-6').fadeIn('normal', function() {
385
              // $(document).scrollTop(0);
txy committed
386
            });
txy committed
387 388 389 390 391 392
          }
          successCallback && successCallback(data); 
        }else if(data.status == 201) {
          // 已报名-通过审核
          if(user.reviewStatus === 1) {
            $('#html-template-5 .struct span').text(rules.settings.szRule.voteNumDay)
txy committed
393
            $('#html-template-5').fadeIn('normal', function() {
394
              // $(document).scrollTop(0);
txy committed
395
            });
txy committed
396 397
          }else {
            $('#html-template-7 .struct span').text(rules.settings.szRule.voteNumDay)
txy committed
398
            $('#html-template-7').fadeIn('normal', function() {
399
              // $(document).scrollTop(0);
txy committed
400
            });
txy committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
          }
          errorCallback && errorCallback(data); 
        }else {
            // 异常处理
            $.dialog({
                contentHtml : '<p style="text-align:center;">'+ data.message +'</p>'
            });
        }
        gb_vote_loaded = false;
    },
    error: function(data){
        // 异常处理
        $.dialog({
            contentHtml : '<p style="text-align:center;">'+ data.responseJSON.message +'</p>'
        });
        gb_vote_loaded = false;
    }
  });
txy committed
419 420 421 422 423 424 425 426 427 428 429 430
}

// 参赛选手投票-有票
function playerHasVoteDialogBind(){
  // 继续投票
  $('#html-template-4 .vote-btn-1').off("click").on('click',function(){
      $('#html-template-4').fadeOut();
  });

  // 我要拉票
  $('#html-template-4 .vote-btn-2').off("click").on('click',function(){
      $('#html-template-4').hide();
txy committed
431 432 433
      $('#html-template-8').fadeIn('normal', function() {
        $(document).scrollTop(0);
      });
434 435 436 437 438
      // 设置分享参数
      setWxShare({
        userId: shareUserId,
        userName: shareUserName
      });
txy committed
439 440 441 442 443 444 445 446 447 448
  });

  // 关闭按钮
  $('#html-template-4 .modal-close').off("click").on('click',function(){
      $('#html-template-4').fadeOut();
  });
}

// 参赛选手投票-无票
function playerNoVoteDialogBind(){
txy committed
449
  // 查看排行
txy committed
450 451
  $('#html-template-5 .vote-btn-1').off("click").on('click',function(){
      $('#html-template-5').fadeOut();
txy committed
452 453 454 455 456 457 458 459 460 461 462
      var _url = window.location.href;
      var indexKey = 'view/'+ activityCode + '/1';
      // 当前是首页则触发切换按钮
      if(_url.indexOf(indexKey) > -1){
        $("#act3152823482970").click();
      }else {
        // 当前非首页则跳转
        var _t = getToken();
        var _addParam = 'toRanger=1'
        transPage('1',activityCode,_t,_addParam);
      }
txy committed
463 464 465 466 467
  });

  // 我要拉票
  $('#html-template-5 .vote-btn-2').off("click").on('click',function(){
      $('#html-template-5').hide();
txy committed
468 469 470
      $('#html-template-8').fadeIn('normal', function() {
        $(document).scrollTop(0);
      });
471 472 473 474 475
      // 设置分享参数
      setWxShare({
        userId: shareUserId,
        userName: shareUserName
      });
txy committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  });

  // 关闭按钮
  $('#html-template-5 .modal-close').off("click").on('click',function(){
      $('#html-template-5').fadeOut();
  });
}

// 投票者-有票
function visitorHasVoteDialogBind(){
  // 继续投票
  $('#html-template-6 .vote-btn-1').off("click").on('click',function(){
      $('#html-template-6').fadeOut();
  });

  // 我要拉票
  $('#html-template-6 .vote-btn-2').off("click").on('click',function(){
      $('#html-template-6').hide();
txy committed
494 495 496
      $('#html-template-8').fadeIn('normal', function() {
        $(document).scrollTop(0);
      });
497 498 499 500 501
      // 设置分享参数
      setWxShare({
        userId: shareUserId,
        userName: shareUserName
      });
txy committed
502 503 504 505 506 507 508 509 510 511 512 513 514
  });

  // 关闭按钮
  $('#html-template-6 .modal-close').off("click").on('click',function(){
      $('#html-template-6').fadeOut();
  });
}

// 投票者-无票
function visitorNoVoteDialogBind(){
  // 我要参赛
  $('#html-template-7 .vote-btn-1').off("click").on('click',function(){
      $('#html-template-7').fadeOut();
txy committed
515 516 517
      var _t = getToken();
      // 跳转到报名
      transPage('2',activityCode,_t);
txy committed
518 519 520 521 522
  });

  // 我要拉票
  $('#html-template-7 .vote-btn-2').off("click").on('click',function(){
      $('#html-template-7').hide();
txy committed
523 524 525
      $('#html-template-8').fadeIn('normal', function() {
        $(document).scrollTop(0);
      });
526 527 528 529 530
      // 设置分享参数
      setWxShare({
        userId: shareUserId,
        userName: shareUserName
      });
txy committed
531 532 533 534 535 536 537 538 539 540 541 542
  });

  // 关闭按钮
  $('#html-template-7 .modal-close').off("click").on('click',function(){
      $('#html-template-7').fadeOut();
  });
}

// 拉票/活动秘籍
function voteShateDialogBind(){
  // 关闭分享弹出框
  $("#html-template-8 .modal-close").off("click").on("click", function() {
txy committed
543
      $('#html-template-8').hide();
txy committed
544 545 546 547 548 549 550 551 552 553
  });
}

// 所有投票弹出框按钮事件绑定
function voteDialogBindFn() {
  playerHasVoteDialogBind();
  playerNoVoteDialogBind();
  visitorHasVoteDialogBind();
  visitorNoVoteDialogBind();
  voteShateDialogBind();
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
}

// 设置分享文案
function setWxShare(data) {

  var _userId = data.userId;
  var _userName = data.userName;

  wx.ready(function(){
    // 获取域名
    var _base = getBaseOrigin();
    var _settings = rules.settings;

    var shareData = {
        title: _settings.szText.shareTitile,
        imgUrl: _settings.szText.shareIcon,
        desc: _settings.szText.shareSubtitle,
        link: ""
    }

    var auth_id = getQueryString('auth_id');
    auth_id = auth_id !== null ? '&auth_id='+auth_id : '';

    // 被分享人
    if (_userId !== '') {
      shareData.title = _settings.szText.pullTitile;
      shareData.desc = _settings.szText.pullSubtitle.replace("{{姓名}}", _userName);
      shareData.link = _base + "/ACTIVITY/view/" + activityCode + "/3?activityCode="+activityCode+"&userId="+ _userId + auth_id;
    }else {
      // 分享首页
      shareData.title = _settings.szText.shareTitile;
      shareData.desc = _settings.szText.shareSubtitle;
      shareData.link = _base + "/ACTIVITY/view/" + activityCode + "/1?activityCode="+activityCode+'&bindId='+getQueryString("bindId") + auth_id;
    }

    /**
     *分享给朋友
    */
    wx.onMenuShareAppMessage({
        title: shareData.title, // 分享标题
        desc: shareData.desc, // 分享描述
        link: shareData.link, // 分享链接
        imgUrl: shareData.imgUrl, // 分享图标
        type: 'link', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
    });
    /**
     *分享到朋友圈
    */
    wx.onMenuShareTimeline({
        title: shareData.title, // 分享标题
        desc: shareData.desc, // 分享描述
        link: shareData.link, // 分享链接
        imgUrl: shareData.imgUrl, // 分享图标
        success: function () {
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
    });
  });
txy committed
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
}

// 图片压缩
function compressImage(file, callback) {

  var reader = new FileReader();
  var img = new Image();

  reader.readAsDataURL(file);
  
  // 缩放图片需要的canvas
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  img.onload = function() {
    // 图片原始尺寸
    var originWidth = this.width;
    var originHeight = this.height;
    // 最大尺寸限制
    var maxWidth = 800, 
        maxHeight = 800;

    // 目标尺寸
    var targetWidth = originWidth, 
        targetHeight = originHeight;

    // 图片尺寸超过1024x1024的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > maxWidth / maxHeight) {
          // 更宽,按照宽度限定尺寸
          targetWidth = maxWidth;
          targetHeight = Math.round(maxWidth * (originHeight / originWidth));
      } else {
          targetHeight = maxHeight;
          targetWidth = Math.round(maxHeight * (originWidth / originHeight));
      }
    }
        
    // canvas对图片进行缩放
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    // 清除画布
    context.clearRect(0, 0, targetWidth, targetHeight);
    // 图片压缩
    context.drawImage(img, 0, 0, targetWidth, targetHeight);
    // canvas转为blob并上传
    canvas.toBlob(function (blob) {
      callback && callback(blob);     
    }, file.type || 'image/png');
  };

  reader.onload = function(e) {
    img.src = e.target.result;
  };
txy committed
675
}