//app.js
App({
	// 接口地址
	api:{
    index: "",//接口地址
	},
  // 外部链接地址
  webapi: {},
  // 全局变量https://www.lanyanmei.com
  globalData: {
    domain: 'https://shop7.thinkp2p.cn',//请求主域名
    key: 'S4DFA4FASR9SD4FS6ADSP',//请求key
    actionurl: "/index.php/Wxsmall/",//请求目录
    invite_key: '',//推荐人key
    HCshopid: 0,//用户手动选择的门店id
    HCtemp: 1,//0-由当前经纬度定位出来的临时门店id 1-由收货地址或者手动切换匹配的门店id
    is_sign:0,//今日是否已经签到
    location_n:'',//当前定位位置
    send: 0,//匹配地址的来源 1同城 2快递
    temp_idcode: 0,//匹配地址的来源 1同城 2快递
    catch_search:[],
    lshop_id:0, // 小店id    
    mid:0,
    QQMap_key: '273BZ-CXS6J-TLAFZ-KFOFD-Y5WJT-6QBUI',//QQ地图KEY
    is_shop_id: 0,
  },
  HCgetExtConfig:function(cb){
    if (wx.getExtConfig) {
      wx.getExtConfig({
        success: function (res) {
          typeof cb == "function" && cb(res.extConfig);
        }
      })
    }
  },
  saveformid: function (formid) {//保存formid
    if (!formid) return;
    var action = 'c=Ajax&a=formid';
    var data = new Object;
    data.formid = formid;
    this.ajaxRequest(action, 'POST', data, function (ret) { }, true);
  },
  dologin: function (data, cb) {
    var that = this;
    var action = 'c=Login&a=dologin';
    that.ajaxRequest(action, 'POST', data, function (ret) {
      if (ret.status) {
        typeof cb == "function" && cb(ret);
      } else {
        var msg = !ret.msg ? '登录超时,请重试(001)' : ret.msg;
        that.HCtoast(msg, 2000, 'none');
      }
    }, false);
  },
  getQQmapkey: function () {
    var key = this.HCgetStorage("setQQmapkey");
    if (!key) key = this.globalData.QQMap_key;
    return key;
  },
  setQQmapkey: function (data) {
    if (!data) return false;
    if (data.QQMap_key) {
      if (!this.globalData.QQMap_key || this.globalData.QQMap_key != data.QQMap_key) {
        this.globalData.QQMap_key = data.QQMap_key;
        this.HCsetStorage("setQQmapkey", this.globalData.QQMap_key);
      }
    }
    return true;
  },

  // 更换底部导航
  setTabBarItem:function(){
    var that = this;
    var lshop_id = that.globalData.lshop_id;
    // if(lshop_id!=0 && lshop_id!=false) return;
    if(lshop_id!=0 && lshop_id!=false && lshop_id!='false'){
      wx.setTabBarItem({
        index: 1,
        text: '店铺精选',
        iconPath: 'images/jingx.png',
        selectedIconPath: "images/jingx_on.png",
      })
    }else{
      wx.setTabBarItem({
        index: 1,
        text: '升级权益',
        iconPath: 'images/jins.png',
        selectedIconPath: "images/jins_on.png",
      })
    }
  },

  // 用户授权获取用户信息
  getUserInfo: function (cb, is_catch) {
    var that = this;
    if (that.globalData.userInfo) {
      if ((that.globalData.userInfo.nickname || that.globalData.userInfo.nickname != ' ') && that.globalData.userInfo.username) {
        that.globalData.userInfo.nickname = that.globalData.userInfo.username;
      }
      if (that.globalData.userInfo.nickname && that.globalData.userInfo.nickname != ' ') {
        that.hideLoading();
        that.HCstopPullDownRefresh();
        that.HChideNavigationBarLoading();
        that.setQQmapkey(that.globalData.userInfo);
        typeof cb == "function" && cb(that.globalData.userInfo); return;
      }
    }
    if (that.globalData.userInfo) {
      that.get_member_info(function (ret) { typeof cb == "function" && cb(ret); });
      that.hideLoading(); return;
    }
    wx.login({
      success: function (ret) {
        var code = ret.code;
        var data = new Object;
        data.js_code = code;
        data.invite_key = that.globalData.invite_key;
        data.lshop_id = that.globalData.lshop_id;
        that.dologin(data, function (ret) {
          if (!ret.data) ret.data = [];
          if (!ret.data.member_info) ret.data.member_info = [];
          var info = ret.data.member_info;
          if (info) {
            that.globalData.userInfo = info;
            that.globalData.HCtoken = ret.data.key;//当前会员登录标识
            that.globalData.init_invite_key = ret.data.invite_key;//当前会员邀请码
            that.globalData.lshop_id = ret.data.lshop_id;
            if (info.nickname == '' || info.nickname == ' ') {
              that.get_member_info(function (ret) {
                that.globalData.userInfo = ret;
                that.setQQmapkey(that.globalData.userInfo);
                typeof cb == "function" && cb(ret);
              }); return;
            }
            that.setQQmapkey(that.globalData.userInfo);
            typeof cb == "function" && cb(info);
          } else {
            that.get_member_info(function (ret) { typeof cb == "function" && cb(ret); });
          }
        });
        that.hideLoading();
      }, fail: function () {
        var msg = '登录超时,请重试(002)';
        that.HCtoast(msg, 2000, 'none');
      }
    })
  },
  get_member_info: function (cb) {
    var that = this;
    var user_info = that.globalData.userInfo;
    wx.checkSession({
      success() {
        if (wx.getUserProfile) {
          var profile_Users = that.HCgetStorage('profile_Users');
          if (profile_Users) {
            that.HCsetStorage('profile_Users', '');
            var data = new Object;
            data = profile_Users;
            data.is_new = 1;
            data.id = user_info.id;
            data.is_true = 1;
            data.invite_key = that.globalData.invite_key;
            data.iv = that.HCgetStorage('profile_iv');
            data.encryptedData = that.HCgetStorage('profile_encryptedData');
            data.session_key = user_info.wxsmall_session_key;
            that.dologin(data, function (ret) {
              that.globalData.HCtoken = ret.data.key;//当前会员登录标识
              that.globalData.init_invite_key = ret.data.invite_key;//当前会员邀请码
              that.globalData.userInfo = ret.data.member_info
              typeof cb == "function" && cb(ret.data.member_info)
            });
          } else {
            typeof cb == "function" && cb(user_info);
          }
        }else{
          wx.getUserInfo({
            withCredentials: true,
            success: function (res) {
              var data = new Object;
              data = res.userInfo;
              data.is_new = 1;
              data.id = user_info.id;
              data.is_true = 1;
              data.invite_key = that.globalData.invite_key;
              data.iv = res.iv;
              data.encryptedData = res.encryptedData;
              data.session_key = user_info.wxsmall_session_key;
              that.dologin(data, function (ret) {
                that.globalData.HCtoken = ret.data.key;//当前会员登录标识
                that.globalData.init_invite_key = ret.data.invite_key;//当前会员邀请码
                that.globalData.userInfo = ret.data.member_info
                typeof cb == "function" && cb(ret.data.member_info)
              });
            }, fail: function (ret) {
              //console.log(ret);
              typeof cb == "function" && cb(user_info);
            }
          })
        }
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        wx.login({
          success: function (ret) {
            var code = ret.code;
            if (wx.getUserProfile){
              var profile_Users = that.HCgetStorage('profile_Users');
              if (profile_Users){
                that.HCsetStorage('profile_Users','');
                var data = new Object;
                data = profile_Users;
                data.id = user_info.id;
                data.is_new = 1;
                data.js_code = code;
                data.invite_key = that.globalData.invite_key;
                data.iv = that.HCgetStorage('profile_iv');
                data.encryptedData = that.HCgetStorage('profile_encryptedData');
                //console.log(data);
                that.dologin(data, function (ret) {
                  that.globalData.HCtoken = ret.data.key;//当前会员登录标识
                  that.globalData.init_invite_key = ret.data.invite_key;//当前会员邀请码
                  that.globalData.userInfo = ret.data.member_info
                  typeof cb == "function" && cb(ret.data.member_info);
                });
              }else{
                typeof cb == "function" && cb(user_info);
              }
            }else{
              wx.getUserInfo({
                withCredentials: true,
                success: function (res) {
                  var data = new Object;
                  data = res.userInfo;
                  data.id = user_info.id;
                  data.is_new = 1;
                  data.js_code = code;
                  data.invite_key = that.globalData.invite_key;
                  data.iv = res.iv;
                  data.encryptedData = res.encryptedData;
                  //console.log(data);
                  that.dologin(data, function (ret) {
                    that.globalData.HCtoken = ret.data.key;//当前会员登录标识
                    that.globalData.init_invite_key = ret.data.invite_key;//当前会员邀请码
                    that.globalData.userInfo = ret.data.member_info
                    typeof cb == "function" && cb(ret.data.member_info);
                  });
                }, fail: function (ret) {
                  //console.log(ret);
                  typeof cb == "function" && cb(user_info);
                }
              })
            }
          }, fail: function () {
            var msg = '登录超时,请重试(003)';
            that.HCtoast(msg, 2000, 'none');
          }
        })
      }
    })
  },
  // 检查当前api是否兼容
  checkIuse: function(checkFunc,callback){
    //使用${API}.${method}.${param}.${options}或者${component}.${attribute}.${option}方式来调用
    var checkarr = new Array;
    var checkcode = true;
    if (Object.prototype.toString.call(checkFunc) === '[object String]'){
      checkarr.push(checkFunc);  
    } else if (Object.prototype.toString.call(checkFunc) === '[object Array]'){
      checkarr = checkFunc;
    }
    if (wx.canIUse) {
      for (var i in checkarr){
        if (!wx.canIUse(checkarr[i])) {
          checkcode = false;
          break;
        }
      }
    } else {
      checkcode = false;
    }
    if (!checkcode){
      this.HCerror('提示', '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。');
    }
    callback(checkcode);
  },
  HCerror: function (title, contnet, showCancel, cb, confirmText, cancelText){
    if (typeof (showCancel) == "undefined") showCancel = true;
    wx.showModal({
      title: title,
      content: contnet,
      showCancel: showCancel,
      confirmText: confirmText ? confirmText:'确定',
      cancelText: cancelText ?cancelText:'取消',
      success: function (res) {
        typeof cb == "function" && cb(res)
      }
    })
  },
  // 提示框（一般用来提示成功）
  HCtoast: function (message,time,icon){
    if (typeof (time) == "undefined") time = 3000;
    if(!icon)icon='success';
    wx.showToast({
      title: message,
      icon: icon,
      mask: true,
      duration: time
    });
  },
  // 提示框（兼容模式）
  showLoading: function (message,time){
    if (wx.showLoading) {
      wx.showLoading({
        title: message,
        mask: true
      });
    } else {
      wx.showToast({
        title: message,
        icon: 'loading',
        mask: true,
        duration: 20000
      });
    }
    if(typeof(time)=="undefined")return;
    if (time>0){
      var self = this;
      setTimeout(function(){
        self.hideLoading();
      }, time);
    }
  },
  // 隐藏提示框（兼容模式）
  hideLoading: function () {
    if (wx.hideLoading) {
      wx.hideLoading();
    } else {
      wx.hideToast();
    }
  },
  HCcheckSession: function(cb){
    var self = this;
    wx.checkSession({
      success: function () {//登录未过期
        typeof cb == "function" && cb(true);
      },
      fail: function () {//登录已过期
        self.getUserInfo(function (ret) {
          
            typeof cb == "function" && cb(true);
          
        },true);
      }
    })
  },
  // ajax请求
  ajaxRequest: function (action, method, data, callBack,logincode) {
    var self = this;
    var domain = self.globalData.domain; 
    var appid = self.globalData.appid; 
    if (domain=='' || appid==0){
      self.HCgetExtConfig(function (ret) {
      //ret.attr = 665;
        if (ret && ret.attr && ret.attr) {
          self.globalData.domain = domain;
          self.globalData.appid = ret.attr;
          if (logincode) {//是否携带登录信息
            self.HCcheckSession(function () {
              self.doneajaxRequest(action, method, data, function (ret) {
                callBack(ret);
              }, true);
            });
          } else {
            self.doneajaxRequest(action, method, data, function (ret) {
              callBack(ret);
            });
          }
        }
      });
    }else{
      if (logincode) {//是否携带登录信息
        self.HCcheckSession(function () {
          self.doneajaxRequest(action, method, data, function (ret) {
            callBack(ret);
          }, true);
        });
      } else {
        self.doneajaxRequest(action, method, data, function (ret) {
          callBack(ret);
        });
      }
    }
  },
  doneajaxRequest: function (action, method, data, callBack, logincode) {
    var self = this;
    var auto_hide_toast = true;//ajax返回后自动隐藏弹窗
    var accountInfo = wx.getAccountInfoSync();
    //console.log(accountInfo);
    if (method == 'GET' || method == 'get') {
      if (logincode) {//是否携带登录信息
        data = data + '&HCtoken=' + encodeURIComponent(self.globalData.HCtoken);
      }
      if (self.globalData.HCshopid > 0) {//门店系统自带参数
        data = data + '&HCshopid=' + self.globalData.HCshopid + '&HCtemp=' + self.globalData.HCtemp;
      }
      if(self.globalData.lshop_id > 0){// 小店id
        data = data + '&lshop_id='+self.globalData.lshop_id;
      }
      data = data + '&extappid=' + accountInfo.miniProgram.appId + '&morecode=SHOP';
      if (data) {
        var s = data.split("&");
        var newaction = new Object;
        for (var i = 0; i < s.length; i++) {
          var d = s[i].split("=");
          if (d[0] && d[0] == 'no_auto_hide_toast' && d[1]) {
            auto_hide_toast = false; break;
          }
        }
      }
      var headerchar = 'application/json';
    } else if (method == 'POST' || method == 'post') {
      if (logincode) {//是否携带登录信息
        data.HCtoken = self.globalData.HCtoken;
      }
      if (self.globalData.HCshopid > 0) {//门店系统自带参数
        data.HCshopid = self.globalData.HCshopid;
        data.HCtemp = self.globalData.HCtemp;
      }
      if(self.globalData.lshop_id > 0){
        data.lshop_id = self.globalData.lshop_id;
      }
      data.extappid = accountInfo.miniProgram.appId;
      data.morecode = "SHOP";
      if (data && data['no_auto_hide_toast'] && data['no_auto_hide_toast']) {
        auto_hide_toast = false;
      }
      var headerchar = 'application/x-www-form-urlencoded';
    } else {
      self.HCerror('提示', '请选用post或者get方式请求'); return;
    }
    if (typeof (action) == 'string') {
      var s = action.split("&");
      var newaction = '';
      for (var i = 0; i < s.length; i++) {
        var d = s[i].split("=");
        if (d[0] == 'c' || d[0] == 'a') {
          newaction += d[1] + '/';
        }
      }
    }
    if (!newaction) {
      self.HCerror('提示', '请求控制器或方法不正确'); return;
      return;
    }
    var url = this.globalData.domain + this.globalData.actionurl + newaction;
    if (method == 'GET' || method == 'get') {
      url = url + '?' + data;
      data = {};
    }
    var now = Date.now();
    var appKey = this.SHA1(action + now + this.globalData.key) + "." + now;
    wx.request({
      url: url,
      data: data,
      header: {
        'content-type': headerchar,
        "X-AppKey": appKey
      },
      method: method,
      success: function (res) {
        // console.log(res);
        var runstart = true;
        if (res.data.status == 3 && res.data.code == 'reLogin') {//重新拉取会员授权信息
          self.getUserInfo(function () {
            self.doneajaxRequest(action, method, data, function (ret) {
              callBack(ret);
            }, logincode);
          }, true);
          return;
        } else if (res.data.status == 3 && res.data.code == 'errorLogin') {
          self.HCerror('提示', '账号登录出现异常', false);
          runstart = false;
        } else if (res.data.HCshop && res.data.HCshop.code == 'bind_shop_success') {
          if (res.data.HCshop.bind_shop_id) {
            //成功绑定当前会员可配送的门店
            self.globalData.HCshopid = res.data.HCshop.bind_shop_id;
            self.globalData.HCtemp = 1;
          }
        } else if (res.data.HCshop && res.data.HCshop.code == 'bind_shop_error') {
          //当前会员无可用的收货地址，无法完成门店匹配
          var thissetdata = new Object;
          if (!auto_hide_toast) {
            thissetdata['no_auto_hide_toast'] = true;
          }
          self.HCsetHCshopid(function () {
            callBack(res.data);
          }, thissetdata);
          runstart = false;
        }
        if (auto_hide_toast) {
          self.hideLoading();
          self.HCstopPullDownRefresh();
          self.HChideNavigationBarLoading();
        }
        if (runstart) {
          callBack(res.data);
        }
      },
      fail: function (res) {
        // console.log(res);//调用失败
      }
    })
  },
  upload_file: function (action, filePath, name, formData, cb){
    if (typeof (action) == 'string') {
      var s = action.split("&");
      var newaction = '';
      for (var i = 0; i < s.length; i++) {
        var d = s[i].split("=");
        if (d[0] == 'c' || d[0] == 'a') {
          newaction += d[1] + '/';
        }
      }
    }
    var now = Date.now();
    var appKey = this.SHA1(action + now + this.globalData.key) + "." + now;
    wx.uploadFile({
      url: this.globalData.domain + this.globalData.actionurl + newaction,
      filePath: filePath,
      name: name,
      header: {
        'content-type': 'multipart/form-data',
        "X-AppKey": appKey
      },
      formData: formData, // HTTP 请求中其他额外的 form data
      success: function (res) {
        //console.log(res);
        var data = JSON.parse(res.data);
        if (res.statusCode == 200 && data && data.status==1) {
          typeof cb == "function" && cb(res.data);
        }
      },
      fail: function (res) {
        // console.log(res);
      }
    })
  },
  HCaddimg: function(cb){
    var self = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            self.HCchooseWxImage('album',cb)
          } else if (res.tapIndex == 1) {
            self.HCchooseWxImage('camera',cb)
          }
        }
      }
    })
  },
  HCchooseWxImage: function (code,cb) {
    var self = this;
    wx.chooseImage({
      count:1,
      sizeType: ['original', 'compressed'],
      sourceType: [code],
      success: function (res) {
        //console.log(res);
        var _this = res;
        var action = 'c=Ajax&a=upload';
        var data = new Object;
        self.upload_file(action, res.tempFilePaths[0], 'pic', data, function (res) {
          var result = JSON.parse(res);
          typeof cb == "function" && cb(result, _this)
          //console.log(res);
        });
      }
    })
  },

  HCremoveStorage: function (key) {
    //本地缓存中指定的 key
    return wx.removeStorageSync(key);
  },
  HCsetStorage: function (key, val) {
    //写入缓存
    wx.setStorage({
      key: key,
      data: val
    })
  },
  HCgetStorage: function (key, cb) {
    //读取缓存
    if (typeof cb == "function") {
      wx.getStorage({
        key: key,
        success: function (res) {
          typeof cb == "function" && cb(res.data);
        },
        fail: function (res) {
          typeof cb == "function" && cb('');
        }
      })
    } else {
      return wx.getStorageSync(key);
    }
  },
  HCcache: function (name, data, expires_in) {
    if (!name) return;
    if (!expires_in) expires_in = 60 * 60 * 2;//默认缓存时间1天    
    var timestamp = parseInt(Date.parse(new Date()) / 1000);
    if (!data) {//获取缓存
      var cache = wx.getStorageSync(name);//小程序
      if (!cache) return ''; var content = '';
      if (cache.time >= timestamp && cache.content) {//判断缓存有效期
        content = cache.content;
      } return content;
    } else {//存储缓存        
      var cachetime = timestamp + expires_in;
      var cache = { 'time': cachetime, 'content': data };
      return wx.setStorageSync(name, cache);
    }
  },
  HCclearStorage: function(){
    //清除缓存
    wx.clearStorage();
  },
  //操作非tabBar页面
  HCnavigateTo:function(url){
    //保存当前页面，并打开新页面【不能超过5层】url:'test?id=1&name=2'
    wx.navigateTo({
      url: url
    })
  },
  //操作非tabBar页面
  HCopenwebview: function (code) {
    var self = this;
    self.checkIuse('web-view',function(ret){
      if (ret){
        if (code) {
          self.HCnavigateTo('/pages/webview/webview?weburl=' + code);
        } else {
          app.HCerror('提示', '缺少必要参数', false);
        }
      }
    })
  },
  HCnavigateBack: function () {
    //关闭当前页面，返回到上一页
    wx.navigateBack();
  },
  HCredirectTo: function (url) {
    //关闭当前页面，并打开新页面 url:'test?id=1&name=2'
    wx.redirectTo({
      url: url
    })
  },
  HCreLaunch: function (url){
    //关闭所有页面，打开到应用内的某个页面 url:'test?id=1&name=2'
    this.checkIuse('reLaunch',function(){
      //兼容处理
      wx.reLaunch({
        url: url
      })
    });
  },
  //操作tabBar页面
  HCswitchTab: function (url){
    //跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
    wx.switchTab({
      url: url
    })
  },
  //预览图片组
  HCpreviewImage: function(arr){
    var urlarr = new Array;
    if (Object.prototype.toString.call(arr) === '[object Array]'){
      urlarr = arr;
    } else if (Object.prototype.toString.call(arr) === '[object Object]'){
      var newarr = Object.keys(arr);
      var len = newarr.length;
      for (var i = 0; i < len; i++) {
        urlarr.push(arr[newarr[i]]);
      }
    } else if (Object.prototype.toString.call(arr) === '[object String]') {
      urlarr.push(arr);
    } else {
      this.HCerror('提示','请传入正确的图片路径');return;
    }
    wx.previewImage({
      urls: urlarr // 需要预览的图片http链接列表
    })
  },
  HCgetSystemInfo:function(cb){
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res);
      }
    })
  },
  HCsetNavigationBarTitle:function(title){
    wx.setNavigationBarTitle({ title: title })
  },
  //获取定位信息
  HCgetlocation: function (cb) {
    var that = this;
    wx.getLocation({
      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标  
      success: function (res) {
        if (res) {
          typeof cb == "function" && cb(res);
        } else {
          that.HCauthorize(1, function (ret) {
            if (ret) {
              that.HCgetlocation(cb);
            } else {
              typeof cb == "function" && cb(false);
            }
          });
        }
      }, fail: function (res) {
        that.HCauthorize(1, function (ret) {
          if (ret) {
            that.HCgetlocation(cb);
          } else {
            typeof cb == "function" && cb(false);
          }
        });
      }
    })
  },
  //打开地图导航
  HCviewlocation: function (data) {
    var latitude = data.ypoint;
    var longitude = data.xpoint;
    var name = data.name;
    var address = data.address;
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: name,
      address: address,
      scale: 18
    })
  },
  //操作其他栈页面的值
  HCchangeData:function(step,data,cb){
    var pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象
      if (step>0){
        var prePage = pages[pages.length - (1 + step)];
        prePage.changeData(data)
        typeof cb == "function" && cb(true);
      }
    }
  },
  //0109
  addListener: function (callback) {
    this.callback = callback;
  },
  setChangedData: function (data) {
    this.data = data;
    if (this.callback != null) {
      this.callback(data);
    }
  },
  //end
  //拨打电话
  HCmakePhoneCall:function(phone,cb){
    if(phone){
      wx.makePhoneCall({
        phoneNumber: phone,
        success: function (res) {
          //console.log(res)
          typeof cb == "function" && cb(res);
        }
      })
    }
  },
  //在当前页面显示导航条加载动画。
  HCshowNavigationBarLoading:function(){
    wx.showNavigationBarLoading()
  },
  //在当前页面显示导航条加载动画。
  HChideNavigationBarLoading:function(){
    wx.hideNavigationBarLoading()
  },
  //停止下拉刷新
  HCstopPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  //领取微信卡券
  HCaddCard: function (cardList,cb){
    this.checkIuse('addCard',function(){
      wx.addCard({
        cardList: cardList,
        success: function (res) {
          // console.log(res.cardList) // 卡券添加结果
          typeof cb == "function" && cb(res);
        },
        complete:function(res){
          // console.log(res);
        }
      })
    });
  },
  //打开微信卡券
  HCopenCard: function (cardList, cb){
    this.checkIuse('openCard', function () {
      wx.openCard({
        cardList: cardList,
        success: function (res) {
          typeof cb == "function" && cb(res);
        }
      })
    });
  },
  //微信授权验证
  HCauthorize:function(code,cb){
    //scope 数组
    var auth = [
      //'scope.userInfo',//
      'scope.userLocation',//对应接口:wx.getLocation, wx.chooseLocation 描述:地理位置
      //'scope.address',//对应接口:wx.chooseAddress 描述:通讯地址
      'scope.invoiceTitle',//对应接口:wx.chooseInvoiceTitle 描述:发票抬头
      'scope.werun',//对应接口:wx.getWeRunData 描述:微信运动步数
      'scope.record',//对应接口:wx.startRecord 描述:录音功能
      'scope.writePhotosAlbum',//对应接口:wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum 描述:保存到相册
      'scope.camera'// 描述:摄像头
    ];
    var self = this;
    if (auth[code]){
      var checkarr = ['getSetting', 'authorize','openSetting'];
      self.checkIuse(checkarr,function(ret){
        wx.getSetting({
          success(res) {
            if (!res.authSetting[auth[code]]) {
              wx.authorize({
                scope: auth[code],
                success(res) {
                  // 用户已经同意小程序使用录该权限
                  typeof cb == "function" && cb(true);
                  return;
                }, 
                fail(res){
                  self.HCerror('温馨提示', '当前页面需要授权后才可访问', true, function (ret) {
                    if (ret.confirm){
                      wx.openSetting({
                        success: (res) => {
                          if (res.authSetting[auth[code]]) {
                            typeof cb == "function" && cb(true);
                          }else{
                            typeof cb == "function" && cb(false);//此处可写成无限调取权限循环
                          }
                        }
                      })
                    }
                  },'授权','不授权');
                }
              })
            }else{
              typeof cb == "function" && cb(true);
            }
          }
        })
      });
    }else{
      var res = new Object;
      res.status = 0;
      res.msg = '无法找到对应权限';
      typeof cb == "function" && cb(res);
      return;
    }
  },
  HCrequestPayment:function(param,cb){
    if (param){
      var result = new Object;
      wx.requestPayment({
        'timeStamp': param.timeStamp.toString(),
        'nonceStr': param.nonceStr,
        'package': param.package,
        'signType': param.signType,
        'paySign': param.paySign,
        'success': function (res) {
          //console.log(res);
          if (res.errMsg =='requestPayment:ok'){
            result.status = 1;
            typeof cb == "function" && cb(result);
          }
          
        }
      })
    }
  },
  HCnavigateToMiniProgram:function(data,cb){
    wx.navigateToMiniProgram({
      appId: 'wxeb490c6f9b154ef9', //固定为此 appid，不可改动
      extraData: data, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
      success: function (ret) {
        typeof cb == "function" && cb(ret);
      },
      fail: function (ret) {
        typeof cb == "function" && cb(ret);
      }
    })
  },
  //根据当前定位信息来获取配送门店
  HCsetHCshopid: function (cb,data) {
    var self = this;
    self.HCgetlocation(function(res){
      self.showLoading('加载中...');
      var action = 'c=Login&a=setshopid';
      var param = new Object;
      param.xpoint = res.longitude;
      param.ypoint = res.latitude;
      if (data){
        for (var i in data){
          param[i] = data[i];
        }
      }
      self.ajaxRequest(action, 'POST', param, function (ret) {
        // console.log(ret);
        if (ret.bind_shop_id){
          self.globalData.HCshopid = ret.bind_shop_id;
          self.globalData.send = ret.send;
        }
        typeof cb == "function" && cb(true);
      }, true);
    });
  },
  // url跳转
  jumtop_open_poster: function (urldata) {
    var self = this;
    if (!urldata) return false;
    var type = urldata.type;
    if (type == '') return false;
    switch (type) {
      case 'GoodsCategory':
        var cateid = urldata.id ? urldata.id : 0;
        self.globalData.catid = cateid;
        self.HCswitchTab('/pages/takeout/index/index');
        break;
      case 'Shops':
        self.HCnavigateTo('/pages/nearby/nearby');
        break;
      case 'Coupons':
        self.HCnavigateTo('/pages/coupon/list/list');
        break;
      case 'Goods':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/takeout/cont/cont?id=' + id);
        break;
      case 'OrderInfo':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/userinfo/order/index?class=0');
        break;
      case 'Member':
        var id = urldata.id ? urldata.id : 0;
        self.HCswitchTab('/pages/userinfo/index/index');
        break;
      case 'ArticleCat':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/article/list/list?id=' + id);
        break;
      case 'Article':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/article/cont/cont?id=' + id);
        break;
      case 'PromotAct':
        var id = urldata.id ? urldata.id : 0;
        if(id>0){
          self.HCnavigateTo('/pages/activity/cont/cont?id='+id);
        }else{
          self.HCnavigateTo('/pages/activity/list/list');
        }
        break;
      case 'PromotSale':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/activity/cont_sale/cont_sale?id=' + id);
        break;
      case 'HotGoods':
        var id = 1;
        self.globalData.screen_list = id;
        self.HCswitchTab('/pages/takeout/index/index');
        break;
      case 'NewGoods':
        var id = 2;
        self.globalData.screen_list = id;
        self.HCswitchTab('/pages/takeout/index/index');
        break;
      case 'BestGoods':
        var id = 6;
        self.globalData.screen_list = id;
        self.HCswitchTab('/pages/takeout/index/index');
        break;
      
      case 'FightGroup':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/spellgroup/pages/index/index');
        break;
      case 'MemberSign':
        var id = urldata.id ? urldata.id : 0;
        self.HCnavigateTo('/pages/userinfo/member_sign/index');
        break;
      default:
        return false;
    }
    return false;
  },
  SHA1: function (msg) {
    // 字符串加密成 hex 字符串
    function rotate_left(n, s) {
      var t4 = (n << s) | (n >>> (32 - s));
      return t4;
    };
    function lsb_hex(val) {
      var str = "";
      var i;
      var vh;
      var vl;
      for (i = 0; i <= 6; i += 2) {
        vh = (val >>> (i * 4 + 4)) & 0x0f;
        vl = (val >>> (i * 4)) & 0x0f;
        str += vh.toString(16) + vl.toString(16);
      }
      return str;
    };
    function cvt_hex(val) {
      var str = "";
      var i;
      var v;
      for (i = 7; i >= 0; i--) {
        v = (val >>> (i * 4)) & 0x0f;
        str += v.toString(16);
      }
      return str;
    };
    function Utf8Encode(string) {
      string = string.replace(/\r\n/g, "\n");
      var utftext = "";
      for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
          utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        } else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }
      }
      return utftext;
    };
    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;
    msg = Utf8Encode(msg);
    var msg_len = msg.length;
    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
      j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
      word_array.push(j);
    }
    switch (msg_len % 4) {
      case 0:
        i = 0x080000000;
        break;
      case 1:
        i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
        break;
      case 2:
        i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
        break;
      case 3:
        i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
        break;
    }
    word_array.push(i);
    while ((word_array.length % 16) != 14)
      word_array.push(0);
    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3) & 0x0ffffffff);
    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
      for (i = 0; i < 16; i++)
        W[i] = word_array[blockstart + i];
      for (i = 16; i <= 79; i++)
        W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
      A = H0;
      B = H1;
      C = H2;
      D = H3;
      E = H4;
      for (i = 0; i <= 19; i++) {
        temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
        E = D;
        D = C;
        C = rotate_left(B, 30);
        B = A;
        A = temp;
      }
      for (i = 20; i <= 39; i++) {
        temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
        E = D;
        D = C;
        C = rotate_left(B, 30);
        B = A;
        A = temp;
      }
      for (i = 40; i <= 59; i++) {
        temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
        E = D;
        D = C;
        C = rotate_left(B, 30);
        B = A;
        A = temp;
      }
      for (i = 60; i <= 79; i++) {
        temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
        E = D;
        D = C;
        C = rotate_left(B, 30);
        B = A;
        A = temp;
      }
      H0 = (H0 + A) & 0x0ffffffff;
      H1 = (H1 + B) & 0x0ffffffff;
      H2 = (H2 + C) & 0x0ffffffff;
      H3 = (H3 + D) & 0x0ffffffff;
      H4 = (H4 + E) & 0x0ffffffff;
    }
    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
    return temp.toLowerCase();
  }
})