app.js 19.1 KB
Newer Older
D
Devil 已提交
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
App({
  data: {
    // 用户登录缓存key
    cache_user_login_key: "cache_user_login_key",
    
    // 用户信息缓存key
    cache_user_info_key: "cache_shop_user_info_key",

    // 用户站点信息缓存key
    cache_user_merchant_key: "cache_shop_user_merchant_key",

    // 设备信息缓存key
    cache_system_info_key: "cache_shop_system_info_key",

    // 用户地址选择缓存key
    cache_buy_user_address_select_key: "cache_buy_user_address_select_key",

    // 启动参数缓存key
    cache_launch_info_key: "cache_shop_launch_info_key",

    // 默认用户头像
    default_user_head_src: "/images/default-user.png",

    // 成功圆形提示图片
    default_round_success_icon: "/images/default-round-success-icon.png",

    // 错误圆形提示图片
    default_round_error_icon: "/images/default-round-error-icon.png",

    // tabbar页面
    tabbar_pages: [
D
devil 已提交
32 33 34 35
      "/pages/index/index",
      "/pages/goods-category/goods-category",
      "/pages/cart/cart",
      "/pages/user/user",
D
Devil 已提交
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
    ],

    // 页面标题
    common_pages_title: {
      "goods_search": "商品搜索",
      "goods_detail": "商品详情",
      "goods_attribute": "属性",
      "user_address": "我的地址",
      "user_address_save_add": "新增地址",
      "user_address_save_edit": "编辑地址",
      "buy": "订单确认",
      "user_order": "我的订单",
      "user_order_detail": "订单详情",
      "user_favor": "我的收藏",
      "answer_form": "留言",
      "answer_list": "问答",
      "user_answer_list": "我的留言",
      "user": "用户中心",
      "goods_category": "分类",
      "cart": "购物车",
      "message": "消息",
      "user_integral": "我的积分",
      "user_goods_browse": "我的足迹",
      "goods_comment": "商品评论",
      "user_orderaftersale": "退款/售后",
      "user_orderaftersale_detail": "订单售后",
      "user_order_comments": "订单评论",
      "coupon": "领劵中心",
      "user_coupon": "优惠劵",
D
devil_gong 已提交
65
      "extraction_address": "自提地址",
D
Devil 已提交
66 67 68 69
    },

    // 请求地址
    request_url: "{{request_url}}",
D
devil 已提交
70 71
    // request_url: 'http://shopxo.com/',
    // request_url: 'https://dev.shopxo.net/',
D
Devil 已提交
72 73 74 75

    // 基础信息
    application_title: "{{application_title}}",
    application_describe: "{{application_describe}}",
D
devil 已提交
76 77 78

    // 价格符号
    price_symbol: "{{price_symbol}}"
D
Devil 已提交
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
  },

  /**
   * 小程序初始化
   */
  onLaunch(options) {
    // 启动参数处理
    options = this.launch_params_handle(options);

    // 设置设备信息
    this.set_system_info();

    // 缓存启动参数
    tt.setStorage({
      key: this.data.cache_launch_info_key,
      data: options
    });
  },

  /**
   * 启动参数处理
   */
  launch_params_handle(params) {
    // 启动参数处理
    if ((params.query || null) != null) {
      params = params.query;
    }
    if ((params.scene || null) != null) {
      params = this.url_params_to_json(decodeURIComponent(params.scene));
    }
    return params;
  },

  /**
   * 获取设备信息
   */
  get_system_info() {
    let system_info = tt.getStorageSync(this.data.cache_system_info_key) || null;
    if (system_info == null) {
      return this.set_system_info();
    }
    return system_info;
  },

  /**
   * 设置设备信息
   */
  set_system_info() {
    var system_info = tt.getSystemInfoSync();
    tt.setStorage({
      key: this.data.cache_system_info_key,
      data: system_info
    });
    return system_info;
  },

  /**
   * 请求地址生成
D
devil 已提交
137 138 139 140
   * a              方法
   * c              控制器
   * plugins        插件标记(传参则表示为插件请求)
   * params         url请求参数
D
Devil 已提交
141
   */
D
devil 已提交
142
  get_request_url(a, c, plugins, params) {
D
Devil 已提交
143 144
    a = a || "index";
    c = c || "index";
D
devil 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157

    // 是否插件请求
    var plugins_params = "";
    if ((plugins || null) != null)
    {
      plugins_params = "&pluginsname=" + plugins + "&pluginscontrol=" + c + "&pluginsaction=" + a;

      // 走api统一插件调用控制器
      c = "plugins"
      a = "index"
    }

    // 参数处理
D
Devil 已提交
158 159 160 161
    params = params || "";
    if (params != "" && params.substr(0, 1) != "&") {
      params = "&" + params;
    }
D
devil 已提交
162 163

    // 用户信息
D
Devil 已提交
164 165
    var user = this.get_user_cache_info();
    var token = (user == false) ? '' : user.token || '';
D
devil 已提交
166 167
    return this.data.request_url +
      "index.php?s=/api/" + c + "/" + a + plugins_params+
D
devil 已提交
168
      "&application=app&application_client_type=toutiao" +
D
Devil 已提交
169 170 171
      "&token=" +
      token +
      "&ajax=ajax" +
D
devil 已提交
172
      params;
D
Devil 已提交
173 174
  },

D
devil_gong 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  /**
   * 获取用户信息,信息不存在则唤醒授权
   * object     回调操作对象
   * method     回调操作对象的函数
   * return     有用户数据直接返回, 则回调调用者
   */
  get_user_info(object, method) {
    var user = this.get_user_cache_info();
    if (user == false) {
      // 唤醒用户授权
      this.user_login(object, method);

      return false;
    } else {
      return user;
    }
  },

D
Devil 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
  /**
   * 从缓存获取用户信息
   */
  get_user_cache_info() {
    let user = tt.getStorageSync(this.data.cache_user_info_key) || null;
    if (user == null) {
      return false;
    }
    return user;
  },

  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   */
D
Devil 已提交
209
  user_auth_login(object, method) {
D
Devil 已提交
210 211 212 213 214 215 216
    tt.showLoading({ title: "授权中..." });
    var self = this;
    tt.checkSession({
      success: function () {
        var openid = tt.getStorageSync(self.data.cache_user_login_key) || null;
        if (openid == null)
        {
D
Devil 已提交
217
          self.user_login(object, method);
D
Devil 已提交
218
        } else {
D
Devil 已提交
219
          self.get_user_login_info(object, method, openid);
D
Devil 已提交
220 221 222
        }
      },
      fail: function () {
D
Devil 已提交
223
        self.user_login(object, method);
D
Devil 已提交
224 225 226 227 228 229 230 231 232
      }
    });
  },

  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   */
D
Devil 已提交
233
  user_login(object, method) {
D
devil_gong 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    var openid = tt.getStorageSync(this.data.cache_user_login_key) || null;
    if (openid == null)
    {
      var self = this;
      // 加载loding
      tt.showLoading({ title: "授权中..." });

      tt.login({
        success: (res) => {
          if (res.code) {
            tt.request({
              url: self.get_request_url('toutiaouserauth', 'user'),
              method: 'POST',
              data: { authcode: res.code, anonymous_code: res.anonymousCode },
              dataType: 'json',
              header: { 'content-type': 'application/x-www-form-urlencoded' },
              success: (res) => {
D
Devil 已提交
251
                tt.hideLoading();
D
devil_gong 已提交
252 253
                if (res.data.code == 0) {
                  var data = res.data.data;
D
devil 已提交
254
                    if ((data.is_user_exist || 0) == 1) {
D
devil_gong 已提交
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
                      tt.setStorage({
                        key: self.data.cache_user_info_key,
                        data: data,
                        success: (res) => {
                          if (typeof object === 'object' && (method || null) != null) {
                            object[method]();
                          }
                        },
                        fail: () => {
                          self.showToast('用户信息缓存失败');
                        }
                      });
                    } else {
                      tt.setStorage({
                        key: self.data.cache_user_login_key,
                        data: data.openid
                      });
                      self.login_to_auth();
                    }
                } else {
                  self.showToast(res.data.msg);
                }
              },
              fail: () => {
                tt.hideLoading();
                self.showToast('服务器请求出错');
              },
            });
          }
        },
        fail: (e) => {
          tt.hideLoading();
          self.showToast('授权失败');
        }
      });
    } else {
      this.login_to_auth();
    }
  },

  /**
   * 跳转到登录页面授权
   */
  login_to_auth() {
    tt.showModal({
      title: '温馨提示',
      content: '授权用户信息',
      confirmText: '确认',
      cancelText: '暂不',
      success: (result) => {
        if (result.confirm) {
          tt.navigateTo({
            url: "/pages/login/login"
D
Devil 已提交
308 309 310 311 312 313 314 315 316 317 318 319
          });
        }
      }
    });
  },

  /**
   * 获取用户授权信息
   * object     回调操作对象
   * method     回调操作对象的函数
   * openid     用户openid
   */
D
Devil 已提交
320 321
  get_user_login_info(object, method, openid) {
    var self = this;
D
Devil 已提交
322 323
    tt.getUserInfo({
      success (res) {
D
Devil 已提交
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
        // 邀请人参数
        var params = tt.getStorageSync(self.data.cache_launch_info_key) || null;
        var referrer = (params == null) ? 0 : (params.referrer || 0);

        // 远程处理用户数据
        tt.request({
          url: self.get_request_url('toutiaouserinfo', 'user'),
          method: 'POST',
          data: {
            "userinfo": res.rawData,
            "openid": openid,
            "referrer": referrer
          },
          dataType: 'json',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: (res) => {
            tt.hideLoading();
            if (res.data.code == 0) {
              tt.setStorage({
                key: self.data.cache_user_info_key,
                data: res.data.data,
                success: (res) => {
                  if (typeof object === 'object' && (method || null) != null) {
                    object[method]();
                  }
                },
                fail: () => {
                  self.showToast('用户信息缓存失败');
                }
              });
            } else {
              self.showToast(res.data.msg);
            }
          },
          fail: () => {
            tt.hideLoading();
            self.showToast('服务器请求出错');
          },
        });
D
Devil 已提交
363 364 365 366 367
      },
      fail (res) {
        app.showToast("获取用户授权信息失败");
      }
    });
D
Devil 已提交
368 369 370 371 372
  },

  /**
   * 字段数据校验
   * data           待校验的数据, 一维json对象
D
devil_gong 已提交
373
   * validation     待校验的字段, 格式 [{fields: 'mobile', msg: '请填写手机号码', is_can_zero: 1(是否可以为0)}, ...]
D
Devil 已提交
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
  */
  fields_check(data, validation) {
    for (var i in validation) {
      var temp_value = data[validation[i]["fields"]];
      var temp_is_can_zero = validation[i]["is_can_zero"] || null;

      if ((temp_value == undefined || temp_value.length == 0 || temp_value == -1) || (temp_is_can_zero == null && temp_value == 0)
      ) {
        this.showToast(validation[i]['msg']);
        return false;
      }
    }
    return true;
  },

  /**
   * 获取当前时间戳
   */
  get_timestamp() {
    return parseInt(new Date().getTime() / 1000);
  },

  /**
   * 获取日期
   * format       日期格式(默认 yyyy-MM-dd h:m:s)
   * timestamp    时间戳(默认当前时间戳)
   */
  get_date(format, timestamp) {
    var d = new Date((timestamp || this.get_timestamp()) * 1000);
    var date = {
      "M+": d.getMonth() + 1,
      "d+": d.getDate(),
      "h+": d.getHours(),
      "m+": d.getMinutes(),
      "s+": d.getSeconds(),
      "q+": Math.floor((d.getMonth() + 3) / 3),
      "S+": d.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
    }
    return format;
  },

  /**
   * 获取对象、数组的长度、元素个数
   * obj      要计算长度的元素(object、array、string)
   */
  get_length(obj) {
    var obj_type = typeof obj;
    if (obj_type == "string") {
      return obj.length;
    } else if (obj_type == "object") {
      var obj_len = 0;
      for (var i in obj) {
        obj_len++;
      }
      return obj_len;
    }
    return false;
  },

  /**
   * 价格保留两位小数
   * price      价格保留两位小数
   */
  price_two_decimal(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
      return 0;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
      pos_decimal = s_x.length;
      s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
      s_x += '0';
    }
    return s_x;
  },

  /**
   * 当前地址是否存在tabbar中
   */
  is_tabbar_pages(url) {
    if (url.indexOf("?") == -1)
    {
D
devil 已提交
469
      var value = url;
D
Devil 已提交
470 471
    } else {
      var temp_str = url.split("?");
D
devil 已提交
472
      var value = temp_str[0];
D
Devil 已提交
473
    }
D
devil 已提交
474
    if ((value || null) == null)
D
Devil 已提交
475 476 477 478 479 480 481
    {
      return false;
    }

    var temp_tabbar_pages = this.data.tabbar_pages;
    for (var i in temp_tabbar_pages)
    {
D
devil 已提交
482
      if (temp_tabbar_pages[i] == value)
D
Devil 已提交
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
      {
        return true;
      }
    }
    return false;
  },

  /**
   * 事件操作
   */
  operation_event(e) {
    var value = e.currentTarget.dataset.value || null;
    var type = parseInt(e.currentTarget.dataset.type);
    if (value != null) {
      switch (type) {
        // web
        case 0:
          tt.navigateTo({ url: '/pages/web-view/web-view?url=' + encodeURIComponent(value) });
          break;

        // 内部页面
        case 1:
          if (this.is_tabbar_pages(value))
          {
            tt.switchTab({ url: value });
          } else {
            tt.navigateTo({ url: value });
          }
          break;

        // 跳转到外部小程序
        case 2:
          tt.navigateToMiniProgram({ appId: value });
          break;

        // 跳转到地图查看位置
        case 3:
          var values = value.split('|');
          if (values.length != 4) {
            this.showToast('事件值格式有误');
            return false;
          }

          tt.openLocation({
            name: values[0],
            address: values[1],
529 530
            longitude: parseFloat(values[2]),
            latitude: parseFloat(values[3])
D
Devil 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
          });
          break;

        // 拨打电话
        case 4:
          tt.makePhoneCall({ phoneNumber: value });
          break;
      }
    }
  },

  /**
   * 默认弱提示方法
   * msg    [string]  提示信息
   * status [string]  状态 默认error [正确success, 错误error]
   */
  showToast(msg, status)
  {
    if ((status || 'error') == 'success')
    {
      tt.showToast({
        title: msg,
D
Devil 已提交
553
        icon: 'success',
D
Devil 已提交
554 555 556 557 558
        duration: 3000
      });
    } else {
      tt.showToast({
        title: msg,
D
Devil 已提交
559
        icon: 'none',
D
Devil 已提交
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
        duration: 3000
      });
    }
  },

  /**
   * 是否需要登录
   * 是否需要绑定手机号码
   */
  user_is_need_login(user) {
    // 用户信息是否正确
    if (user == false)
    {
      return true;
    }

    // 是否需要绑定手机号码
    if ((user.is_mandatory_bind_mobile || 0) == 1)
    {
      if ((user.mobile || null) == null)
      {
        return true;
      }
    }
    
    return false;
  },

  /**
   * url参数转json对象
   */
  url_params_to_json(url_params) {
    var json = new Object();
    if ((url_params || null) != null)
    {
      var arr = url_params.split('&');
      for(var i = 0; i<arr.length; i++) {
      var temp = arr[i].split('=');
        json[temp[0]] = temp[1]
      }
    }
    return json;
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
  },

  // 文件上传权限获取
  file_upload_authorize(object, method, params) {
    var self = this;
    tt.getSetting({
      success(res) {
        if (!res.authSetting['scope.camera']) {
          tt.authorize({
            scope: 'scope.camera',
            success (res) {
              tt.authorize({
                scope: 'scope.camera',
                success (res) {
                  if (typeof object === 'object' && (method || null) != null) {
                    object[method](params);
                  }
                },
                fail (res) {
                  tt.openSetting();
                  self.showToast('请同意相册授权');
                }
              });
            },
            fail (res) {
              tt.openSetting();
              self.showToast('请同意相机授权');
            }
          });
        } else {
          if(!res.authSetting['scope.album'])
          {
            if(res.authSetting['scope.album'] == undefined)
            {
              tt.authorize({
                scope: 'scope.camera',
                success (res) {
                  if (typeof object === 'object' && (method || null) != null) {
                    object[method](params);
                  }
                },
                fail (res) {
                  tt.openSetting();
                  self.showToast('请同意相册授权');
                }
              });
            } else {
              tt.openSetting();
              self.showToast('请同意相册授权');
            }
          } else {
            if (typeof object === 'object' && (method || null) != null) {
              object[method](params);
            }
          }
        }
      },
      fail: (e) => {
        self.showToast("授权校验失败");
      }
    });
  },
D
Devil 已提交
664

D
devil_gong 已提交
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
  // 位置权限获取
  location_authorize(object, method, params) {
    var self = this;
    tt.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          tt.authorize({
            scope: 'scope.userLocation',
            success (res) {
              if (typeof object === 'object' && (method || null) != null) {
                object[method](params);
              }
            },
            fail (res) {
              tt.openSetting();
              self.showToast('请同意地理位置授权');
            }
          });
        } else {
          if (typeof object === 'object' && (method || null) != null) {
            object[method](params);
          }
        }
      },
      fail: (e) => {
        self.showToast("授权校验失败");
      }
    });
  },

D
devil_gong 已提交
695 696 697 698 699 700 701
  // 拨打电话
  call_tel(value) {
    if ((value || null) != null) {
      tt.makePhoneCall({ phoneNumber: value });
    }
  },

D
devil_gong 已提交
702 703 704 705 706 707
  /**
   * 登录校验
   * object     回调操作对象
   * method     回调操作对象的函数
   */
  is_login_check(res, object, method) {
D
devil_gong 已提交
708 709 710
    if(res.code == -400)
    {
      tt.clearStorage();
D
devil_gong 已提交
711
      this.get_user_info(object, method);
D
devil_gong 已提交
712 713 714 715 716
      return false;
    }
    return true;
  },

D
devil 已提交
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
  /**
   * 设置导航reddot
   * index     tabBar 的哪一项,从左边算起(0开始)
   * type      0 移出, 1 添加 (默认 0 移出)
   */
  set_tab_bar_reddot(index, type) {
    if (index !== undefined && index !== null)
    {
      if ((type || 0) == 0)
      {
        tt.hideTabBarRedDot({ index: Number(index) });
      } else {
        tt.showTabBarRedDot({ index: Number(index) });
      }
    }
  },

  /**
   * 设置导航车badge
   * index     tabBar 的哪一项,从左边算起(0开始)
   * type      0 移出, 1 添加 (默认 0 移出)
   * value     显示的文本,超过 4 个字符则显示成 ...(type参数为1的情况下有效)
   */
  set_tab_bar_badge(index, type, value) {
    if (index !== undefined && index !== null)
    {
      if ((type || 0) == 0) {
        tt.removeTabBarBadge({ index: Number(index) });
      } else {
        tt.setTabBarBadge({ index: Number(index), "text": value.toString() });
      }
    }
  },

D
Devil 已提交
751
});