common.js 28.5 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 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
/*
 * APICloud JavaScript Library
 * Copyright (c) 2019 wuyingjie
 */
var HOST = 'http://iotapps.uccc.cc:9026';

var IOT_HOST = 'http://iot.uccc.cc:9090/luodian_server'

var IOT_HOST_TEST = 'http://20.20.20.103:5006'

var ERR_MSG = '服务请求失败';

//枚举产品类型分类
function enumProductType(model) {
  switch (model) {
    case '1':
      return '智能短路灭弧器'
    case '2':
      return '在线监测装置'
    case '3':
      return '智慧空开'
    case '4':
      return '故障电弧探测器'
    default:
    break;
  }
}

function filterDeviceName(storename, imei) {
  let res;
  if (storename === '') {
     res = imei
  }else {
    res = storename
  }
  return res
}

function cacheImg(u) {
  let path = ''
  // 缓存图片
  let pic_url_ =  $api.getStorage(u)
  console.log(u + " ---->>>  " + pic_url_);
  if (!pic_url_) {
    api.imageCache({
        url: u
    }, function(ret, err) {
        let url = ret.url;
        $api.setStorage(u, url);
        path = url
    });
  }else {
    path = pic_url_
  }
  //--------
  
  
  return path
}

//产品类型根据model分组
// function groupBymodelForProduct(list) {
//   var groupList = [{name: '智能短路灭弧器', data: []},
//                    {name: '在线监测装置', data: []},
//                    {name: '智慧空开', data: []},
//                    {name: '故障电弧探测器', data: []}
//                   ]
                  
//   for (let i = 0; i < list.length; i++) {
//     const element = list[i];
//     const typeCn_ = enumProductType(element.model)
//     for (let j = 0; j < groupList.length; j++) {
//       const element2 = groupList[j];
//       if (typeCn_ === element2.name) {
//         groupList[j].data.push(element)
//       }
//     }
    
//   }
//   return groupList
// }

function returnInputDialogJSON() {
  const dialogOption = {
      keyboardType: 'default',
      texts: {
          title: '提示: 您是否要继续该操作?',
          placeholder: '需输入设备密码进行该操作',
          leftBtnTitle: '取消',
          rightBtnTitle: '确定'
      },
      animation: true,
      styles: {
          bg: '#fff',
          corner: 1,
          w: 260,
          h: 180,
          title: {
              h: 50,
              alignment: 'center',
              size: 14,
              color: '#F26161',
              marginT:25,
          },
          input: {
              h: 20,
              marginT:15,
              marginLeft: 15,
              marginRight:15,
              textSize: 14,
              textColor: '#000',
              corner: 2,               
              borderColor:'#AEB8CE',
              borderWidth:1
          },
          dividingLine: {
              width: 0,
              color: '#696969'
          },
          left: {
              bg: 'rgba(0,0,0,0)',
              color: '#007FFF',
              size: 12,
              // h: 40,                //(可选项) 数字类型;右边按钮的高度;默认:40
              // w:60,                   //(可选项) 数字类型;左边按钮的宽度;默认:提示框的宽度的一半
              // marginB:10,            //(可选项) 数字类型;左边按离底部的边距;默认:0
              // corner:5,              //(可选项) 数字类型;左边按钮的圆角;默认:0
              widhtBorder:1,         //(可选项) 数字类型;左边按钮的边宽;默认:0
              normalBorderColor:'#F0F5FF', //(可选项) 数字类型;左边按钮的边宽颜色;默认:'rgba(0,0,0,0)'
              activeBorderColor:'#0000CD', //(可选项) 数字类型;左边按钮的高亮状态下边宽颜色;默认:'rgba(0,0,0,0)'
              activeColor:'#006400', //(可选项) 数字类型;左边按钮的高亮状态下标题颜色;默认:'rgba(0,0,0,0)'
              activeBg:'#6B8E23'   //(可选项) 数字类型;左边按钮的高亮状态下背景颜色;默认:'rgba(0,0,0,0)'
          },
          right: {
              bg: 'rgba(0,0,0,0)',
              color: '#007FFF',
              size: 12,
                      // h: 40,                //(可选项) 数字类型;右边按钮的高度;默认:40
              // w:60,                   //(可选项) 数字类型;右边按钮的宽度;默认:提示框的宽度的一半
              // marginB:10,            //(可选项) 数字类型;右边按离底部的边距;默认:0
              // corner:5,              //(可选项) 数字类型;右边按钮的圆角;默认:0
              widhtBorder:1,         //(可选项) 数字类型;右边按钮的边宽;默认:0
              normalBorderColor:'#F0F5FF', //(可选项) 数字类型;右边按钮的边宽颜色;默认:'rgba(0,0,0,0)'
              activeBorderColor:'#0000CD', //(可选项) 数字类型;右边按钮的高亮状态下边宽颜色;默认:'rgba(0,0,0,0)'
              activeColor:'#006400', //(可选项) 数字类型;右边按钮的高亮状态下标题颜色;默认:'rgba(0,0,0,0)'
              activeBg:'#6B8E23'   //(可选项) 数字类型;右边按钮的高亮状态下背景颜色;默认:'rgba(0,0,0,0)'
          }
      }
  }

  return dialogOption;
}

//验证手机格式
function checkPhone(inputed_phone) {
  var phonereg = /^1\d{10}$/;
  if (inputed_phone == "" || !phonereg.test(inputed_phone)) {
      return false;
  } else {
    return true;
  }
}

function repairTypeHtml(text) {
  var dom;
  dom  = '<div class="aui-col aui-col-span-12 margin-15" style="height: 2.5rem;" tapmode onclick="chooseType(\'' + text + '\');">';
  dom +=    '<div class="repair-type-btn">' + text + '</div>';
  dom += '</div>'
  return dom;
}

function setStatusBg(color) {
  api.setStatusBarStyle({
    style:  color
  });

}

function addAlert(content) {
  var dialogBox = api.require('dialogBox');
  dialogBox.alert({
      texts: {
          title: '提示',
          content: content,
          leftBtnTitle: '好的',
      },
      styles: {
          bg: '#fff',
          w: 300,
          corner:6,
          title: {
              marginT: 20,
              icon: '',
              iconSize: 40,
              titleSize: 18,
              titleColor: '#5B7FF8'
          },
          content: {
              color: '#000',
              size: 14
          },
          left: {
              marginB: 7,
              marginL: 85,
              w: 130,
              h: 35,
              corner: 10,
              bg: '#5B7FF8',
              color: '#FFFFFF',
              size: 12
          },
      }
  }, function(ret) {
      if (ret.eventType == 'left') {
          var dialogBox = api.require('dialogBox');
          dialogBox.close({
              dialogName: 'alert'
          });
      }
  });
}

function trim_nulls(data) {
  var y;
  for (var x in data) {
      y = data[x];
      if (y instanceof Object) y = trim_nulls(y);
      if (y === "null" || y === null || y === "" || typeof y === "undefined" || (y instanceof Object && Object.keys(y).length == 0)) {
          delete data[x];
      }
  }
  return data;
}

function timeFormater(y,m,d) {
  var year = y;
  if (m < 10) {
    var month = '0' + m;
  }else {
    var month = m;
  }
  if (d < 10) {
    var day = '0' + d;
  }else {
    var day = d;
  }
  var ret =  year + '-' + month + '-' + day;
  return ret;
}

function handleFormatTY500Alert(json) {
  let list = []
  let date2 = new Date(json.createdAt);

  let time = date2.toLocaleString();
  for(var p in json){
    let typeCn = alarmTypeList(p)
    if (typeCn != null && json[p] === "1") {
      list.push({
        type: typeCn,
        time: time
      })
      
      // eval('list.push({"' + typeCn + '": "' + time + '"})')
    }
  }
  console.log(JSON.stringify(list));
  return list
}

function alarmTypeList(value) {
  switch (value) {
    case 'all':
      return '全部报警';
      break;
    case 'over_current_warning':
      return '过载报警';
      break;
    case 'short_curent_warning':
      return '短路报警';
      break;
    case 'rest_current_warning':
      return '漏电报警';
      break;
    case 'over_high_voltage_warning':
      return '过压报警';
      break;
    case 'over_low_voltage_warning':
      return '欠压报警';
      break;
    case 'over_line_temp_warning':
      return '线路超温';
      break;
    case 'over_temp1_warning':
      return '内部超温';
      break;
    case 'fan_error':
      return '风扇异常';
      break;
    case 'IGBT_error':
      return '驱动异常';
      break;
    case 'param_error':
      return '参数异常';
      break;
    case 'sign_error':
      return '信号异常';
      break;
    default:
      return null;  
  }
}

function formatOperateTime(param) {
  var param_ = '20' + param;
  var _param_ = '';
  var timeSpl = param_.split('');
  for (var i = 0; i < timeSpl.length; i++) {
    if (i == 3) {
        timeSpl[i] = timeSpl[i]+'-';
    }else if (i == 5) {
      timeSpl[i] = timeSpl[i]+'-';
    }else if (i == 7) {
      timeSpl[i] = timeSpl[i]+' ';
    }else if (i == 9) {
      timeSpl[i] = timeSpl[i]+':';
    }else if (i == 11) {
      timeSpl[i] = timeSpl[i]+':';
    }
    _param_ += timeSpl[i];
  }
  return _param_;
}

function operationUnit(value,param) {
    switch (value) {
        case '&S1+':
            var format_param = formatOperateTime(param);
            return format_param;
            break;
        case '&S2+':
            return param + ' A';
            break;
        case '&S3+':
            return param + ' s';
            break;
        case '&S4+':
            return param + ' A';
            break;
        case '&S5+':
            return param + ' mA';
            break;
        case '&S6+':
            return param + ' V';
            break;
        case '&S7+':
            return param + ' V';
            break;
        case '&S8+':
            return param + ' ℃';
            break;
    }
}

function operationList(value,param) {
    switch (value) {
        case '&S1+':
            return '设置设备时间'
            break;
        case '&S2+':
            return '设置过载电流动作值';
            break;
        case '&S3+':
            return '设置过载时间动作值';
            break;
        case '&S4+':
            return '设置短路电流动作值';
            break;
        case '&S5+':
            return '设置漏电电流动作值';
            break;
        case '&S6+':
            return '设置过压报警动作值';
            break;
        case '&S7+':
            return '设置欠压报警动作值';
            break;
        case '&S8+':
            return '设置超温报警动作值';
            break;
        case '&S9+':
            if (param == '2') {
              return '远程控制-静音';
            }else if (param == '4') {
              return '远程控制-分闸';
            }else if (param == '8') {
              return '远程控制-自检';
            }else if (param == '16') {
              return '远程控制-复位';
            }
            return '远程控制';
            break;
    }
}
function monthAgo(month,no) {
    var date1 = new Date();
    date1.setMonth(parseInt(month)-no);
    var year1=date1.getFullYear(); 
    var month1=date1.getMonth()+1;
    month1 =(month1<10 ? "0"+month1:month1); 
    sDate = (year1.toString()+'-'+month1.toString());
    return sDate;
}
function timeList(type, time) {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    day = year + "-" + (month < 10 ? ("0" + month) : month) + "-" + (day < 10 ? ("0" + day) : day);
    var timeArrary = [];
    if (type == 'month') {
        timeArrary = [{
            status: (time == monthAgo(month,1)) ? 'selected' : 'normal',
            text: monthAgo(month,1)
        }, {
            status: (time == monthAgo(month,2)) ? 'selected' : 'normal',
            text: monthAgo(month,2)
        }, {
            status: (time == monthAgo(month,3)) ? 'selected' : 'normal',
            text: monthAgo(month,3)
        }, {
            status: (time == monthAgo(month,4)) ? 'selected' : 'normal',
            text: monthAgo(month,4)
        }, {
            status: (time == monthAgo(month,5)) ? 'selected' : 'normal',
            text: monthAgo(month,5)
        }, ]
    } else if (type == 'year') {
        timeArrary = [{
            status: (time == year) ? 'selected' : 'normal',
            text: year
        }, {
            status: (time == parseInt(year) - 1) ? 'selected' : 'normal',
            text: parseInt(year) - 1
        }, {
            status: (time == parseInt(year) - 2) ? 'selected' : 'normal',
            text: parseInt(year) - 2
        }, {
            status: (time == parseInt(year) - 3) ? 'selected' : 'normal',
            text: parseInt(year) - 3
        }, {
            status: (time == parseInt(year) - 4) ? 'selected' : 'normal',
            text: parseInt(year) - 4
        }, ]
    } else if (type == 'day') {
        timeArrary = [{
            status: 'selected',
            text: day
        }]
    }
    return timeArrary;
}

function closeWin() {
    api.closeWin({});
}

function initHeaderH() {
    $api.setStorage('SYSTEMTYPE', api.systemType);
    $api.setStorage('SYSTEMVERSION', api.systemVersion);
    $api.setStorage('FULLSCREEN', api.fullScreen);
    $api.setStorage('IOS7STATUSBARAPPEARANCE', api.iOS7StatusBarAppearance);
    $api.setStorage('SAFEAREATOP', api.safeArea.top);
    $api.setStorage('SAFEAREABOTTOM', api.safeArea.bottom);
}

function fixIos7Bar_API(el) {
    if (!$api.isElement(el)) {
        return;
    }
    var strDM = $api.getStorage('SYSTEMTYPE');
    if(!strDM){
      //避免未经过常量初始化的情况
      initHeaderH();
      strDM = $api.getStorage('SYSTEMTYPE');
    }
    if (strDM == 'ios') {
        var strSV = $api.getStorage('SYSTEMVERSION');
        var numSV = parseInt(strSV, 10);
        var fullScreen = $api.getStorage('FULLSCREEN');
        var iOS7StatusBarAppearance = $api.getStorage('IOS7STATUSBARAPPEARANCE');
        if (numSV >= 7 && fullScreen == 'false' && iOS7StatusBarAppearance) {
            el.style.paddingTop = $api.getStorage('SAFEAREATOP')+'px';
        }
    }
}

function fixStatusBar_API(el) {
    if (!$api.isElement(el)) {
        //console.warn('$api.fixStatusBar Function need el param, el param must be DOM Element');
        return;
    }
    var sysType = $api.getStorage('SYSTEMTYPE');
    if (sysType == 'ios') {
        fixIos7Bar_API(el);
    } else if (sysType == 'android') {
        var ver = $api.getStorage('SYSTEMVERSION');
        ver = parseFloat(ver);
        if (ver >= 4.4) {
            var marginTop = $api.getStorage('SAFEAREATOP');
            if(!marginTop){
              initHeaderH();
              marginTop = $api.getStorage('SAFEAREATOP');
            }
            el.style.paddingTop = marginTop+'px';
        }
    }
}
(function(window) {

})(window);

function openCanner(isEmpty) {
    api.openWin({
        name: 'scanner',
        url: '../utils/scanner.html',
        bgColor: 'rgba(0,0,0,0)',
        pageParam: {
            "isEmpty": isEmpty
        }
    });

    return false;
    //以下代码为之前版本,经修改之后暂做保存,此处直接renturn
    var FNScanner = api.require('FNScanner');
    FNScanner.openScanner({
        autorotation: true,
        isAlbum: true,
        hintText: '请扫一扫设备上的二维码获取设备编号'
    }, function(ret, err) {
        if (ret) {
            if (ret.eventType == 'cancel') {
                if (isEmpty) {
                    api.alert({
                        title: '添加设备',
                        msg: '暂无设备,请先添加设备...',
                    }, function(ret, err){
                        if( ret ){
                             openCanner(isEmpty);
                        }
                    });

                }
            } else if (ret.eventType == 'success') {
                var md5Reg = /^[a-f0-9]{32}$/;
                if (md5Reg.test(ret.content)) {
                    api.openWin({ slidBackEnabled:false,
                        name: 'perfectInfo',
                        url: 'perfectInfo.html',
                        pageParam: {
                            "code": ret.content,
                            "isEmpty": isEmpty
                        }
                    });
                } else {
                    api.alert({
                        title: '请扫描正确的设备二维码',
                        msg: '当前设备二维码不正确',
                    }, function(ret, err) {
                        openCanner(isEmpty);
                    });


                }

            }

        } else {
            //alert(JSON.stringify(err));
        }
    });
}

function check() {
  app_remain = 86400000 * 364 //1年时间少1天这里
  var now = new Date();
  $logintime = $api.getStorage('login_time');
  $now = now.getTime();
  if ($now - $logintime > app_remain) { //登陆已过期
    var ajpush = api.require("ajpush");
    clearPush(ajpush, function(){
      $api.clearStorage();
      api.openWin({
          name: 'login',
          url: 'widget://html/login/login_win.html',
          slidBackEnabled:false,
          reload: true,
          bounces: false,
      });
      // api.openFrame({
      //     historyGestureEnabled:false,
      //     reload: true,
      //     name: 'login',
      //     url: 'widget://html/login/login_win.html',
      //     rect: {
      //         x: 0,
      //         y: 0,
      //         w: 'auto',
      //         h: 'auto'
      //     },
      //     allowEdit:true
      // });
      return false;
    })
  }else{
    var token = $api.getStorage('userToken');
    if (!token) {  //没有登陆过
      // api.openFrame({ historyGestureEnabled:false,
      //     reload: true,
      //     name: 'login',
      //     url: 'widget://html/login/login_win.html',
      //     rect: {
      //         x: 0,
      //         y: 0,
      //         w: 'auto',
      //         h: 'auto'
      //     },
      //     allowEdit:true
      // });

      api.openWin({
          name: 'login',
          url: 'widget://html/login/login_win.html',
          slidBackEnabled:false,
          reload: true,
          bounces: false,
      });
      return false;
    }
  }
    return true;

    //登陆完之后的操作
    //   api.openWin({ slidBackEnabled:false,
    //   name: 'index_public',
    //   url: '../../page/public/index_public.html',
    //   rect: {
    //           x: 0,
    //           y: 0,
    //           w: 'auto',
    //           h: 'auto'
    //   },
    //   pageParam: {
    //           name: 'test'
    //    }
    // });
    //
    // api.closeFrame({
    //      name:'login'
    // });
    //
}

function ajaxCodeCheck(code, msg, def) {
    if (parseInt(code / 10000) == 5) {
        return msg;
    }
    return def;
}

function choseDevice() {
  api.openWin({
      name: 'choseDevice',
      url: 'choseDevice.html',
      bgColor: 'rgba(0,0,0,0)'
  });
  return false;
}

function noData(obj,topval) {
    var topValue = topval;
    var dom;
    $api.html(obj, '<div style="top:' + topValue + 'rem;" class="no-data"><img src="../../image/img-nullInfo.png" /><p style="font-size:16px;font-weight:500;color:rgba(55,57,78,1);">这里还没有内容</p><p>先去别的地方看看吧~</p></div>');
}

function loadingData(obj,topval) {
    var topValue = topval;
    $api.html(obj, '<div style="top:' + topValue + 'rem;" class="no-data loading-data"><img src="../../image/loading_more.gif" /><p>加载中…</p></div>');
}

function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  var date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, function(result, key){
    var value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

function initPush(){
  var ajpush = api.require('ajpush');
  var strDM = $api.getStorage('SYSTEMTYPE');
  if(strDM=='android'){
    ajpush.init(function(ret) {
      if(ret && ret.status ==1){
        initAndListenPush(ajpush, true);
      }
    })
  }else{
    initAndListenPush(ajpush, true);
  }
}

function initAndListenPush(ajpush, needListen){
  var registrationId = $api.getStorage('registrationId');
  if(!registrationId){

    ajpush.getRegistrationId(function(ret) {
        if(ret && ret.id){
          var registrationId = ret.id;
          //上报reg id
          var token = $api.getStorage('userToken');
          var user_id = $api.getStorage('userID');
          var postData = {
              user_id: user_id,
              reg_id: registrationId
          }
          if(!needListen){
            postData = {
                user_id: user_id
            }
          }
          $.ajax({
              url: HOST + '/iot_api/v1/app/async_reg',
              type: 'POST',
              dataType: 'json',
              headers: {
                  'Content-Type': 'application/json;charset=utf-8',
                  'token': token
              },
              data: JSON.stringify(postData),
              success: function(ret) {
                  if (ret) {
                      if (ret.code == 0) {
                          $api.setStorage('registrationId', registrationId);
                          if(needListen){
                            api.addEventListener({name:'appintent'}, function(ret,err) {
                              notify(ret);
                          })
                          }
                      }
                  }
              },
              error: function() {

              }
          });
        }

    });
  }else{
    if(needListen){
      ajpush.setListener(
          function(ret) {
            notify(ret);
          }
      );
      if (api.systemType == 'android') {
        api.addEventListener({name:'appintent'}, function(ret,err) {
          notify(ret);
        });
      }else {
        api.addEventListener({
            name: 'noticeclicked'
        }, function(ret, err){
            if( ret ){
              notify(ret);
            }
        });
      }


    }else{
      var token = $api.getStorage('userToken');
      var user_id = $api.getStorage('userID');
      var postData = {
          user_id: user_id,
          reg_id: registrationId
      }
      if(!needListen){
        postData = {
            user_id: user_id
        }
      }
      $.ajax({
          url: HOST + '/iot_api/v1/app/async_reg',
          type: 'POST',
          dataType: 'json',
          headers:{
              'Content-Type':'application/json;charset=utf-8',
              'token': token
          },
          data: JSON.stringify(postData),
          success: function(ret) {
            if (ret.code == 0) {
              $api.setStorage('registrationId', registrationId);
              if(needListen){
                api.addEventListener({name:'appintent'}, function(ret,err) {
                  notify(ret);
              })
              }
            }
          },
          error: function() {
            api.toast({msg: ERR_MSG,duration: 2000,location: 'bottom'});
          }
      });
      // $.ajax({
      //     url: HOST + '/iot_api/v1/app/async_reg',
      //     type: 'POST',
      //     dataType: 'json',
      //     headers: {
      //         'Content-Type': 'application/json;charset=utf-8',
      //         'token': token
      //     },
      //     data: JSON.stringify(postData),
      //     success: function(ret) {

      //     },
      //     error: function() {
      //
      //     }
      // });
    }
  }


}

function notify(info){
  var extra;
  if (api.systemType == 'android') {  //Android app后台状态
    extra = info.appParam.ajpush.extra;
  }else if (api.systemType == 'ios' && info.extra) { //ios app前台状态
    extra = info.extra;
  }else if (api.systemType == 'ios' && info.value.extra) {
    extra = info.value.extra; //ios app后台状态
  }
  switch (extra.type) {
    case "warning":
      //设备告警
      var current = extra.imei;
      if(current && current != ''){
          //弹窗告警
          api.alert({
              title: extra.remark,
              msg: '编号:' + current,
              buttons: ["查看报警 >"]
          }, function(ret, err){
              if( ret ){
                //index切换为1,进入所有报警页面
                 console.log('~~~');
                 var NVTabBar = api.require('NVTabBar');
                 NVTabBar.setSelect({
                     index: 1,
                     selected: true,
                 });

                 api.openFrame({
                     name:  'alarmIndex',
                     url: './alarm/alarm.html',
                     reload: true,
                     rect: {
                         x: 0,
                         y: 0,
                         w: api.winWidth,
                         h: api.winHeight-49-$api.getStorage('indexFooterH')
                     },
                     bgColor: '#f4f6f9',
                     reload: true
                 });
                 //查询该用户下的所有未处理报警总数
                 var userId = $api.getStorage('userID');
                 var token = $api.getStorage('userToken');
                 $.ajax({
                     url: HOST + '/iot_api/v1/app/get_unsloved_warning_count?user_id='+userId,
                     type: 'GET',
                     dataType: 'json',
                     headers: {
                         'Content-Type': 'application/json;charset=utf-8',
                         'token': token
                     },
                     success: function(ret) {
                       if (ret.code == 0 && ret.data > 0) {
                         NVTabBar.setBadge({
                             index: 1,
                             badge: ret.data
                         });
                       }else {
                         api.toast({
                             msg: '获取所有报警总数失败'
                         });
                       }
                     },
                     error: function() {
                       api.toast({msg: ERR_MSG,duration: 2000,location: 'bottom'});
                     }
                 });
                 //---
              }
          });
      }
      break;
    default:

  }
}

function clearPush(ajpush, func){
  var registrationId = $api.getStorage('registrationId');
  if(!registrationId){
    ajpush.getRegistrationId(function(ret) {
        if(ret && ret.id){
          var registrationId = ret.id;
          //同步reg id
          var token = $api.getStorage('userToken');
          $.ajax({
              url: HOST + '/iot_api/v1/app/async_rm_reg',
              type: 'POST',
              dataType: 'json',
              headers: {
                  'Content-Type': 'application/json;charset=utf-8',
                  'token': token
              },
              data: JSON.stringify({
                  reg_id: registrationId
              }),
              success: function(ret) {
                  if (ret) {
                      if (ret.code == 0) {
                          //$api.setStorage('registrationId', registrationId);
                      }
                  }
              },
              error: function() {

              },
              complete:function() {
                ajpush.removeListener();
                if(func){
                  func();
                }
              }
          });
        }

    });
  }else{
    var token = $api.getStorage('userToken');
    $.ajax({
        url: HOST + '/iot_api/v1/app/async_rm_reg',
        type: 'POST',
        dataType: 'json',
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'token': token
        },
        data: JSON.stringify({
            reg_id: registrationId
        }),
        success: function(ret) {
            if (ret) {
                if (ret.code == 0) {
                    //$api.setStorage('registrationId', registrationId);
                }
            }
        },
        error: function() {

        },
        complete:function() {
          ajpush.removeListener();
          if(func){
            func();
          }
        }
    });
  }
  console.log('remove');
  ajpush.removeListener();

}