const Promise = require('./es6-promise.js');
// 保留两位小数
var filters = {
  toFix: function (value) {
    value = parseInt(value)
    return value.toFixed(2) // 此处2为保留两位小数，保留几位小数，这里写几    
  }
}
module.exports = {
  filters,
  // amapFile: require('amap-wx.js'),
  config: require('config.js'),
  // 以空格开始或结束的字符串
  trim: function (str) {
    return str.replace(/^\s+/, "").replace(/\s+$/, "");
  },
  // 所有存在空格的字符串
  spaceTrim: function (str) {
    return str.replace(/\s+/g, "")
  },
  // 通过宝贝币匹配会员等级
  getCoinLevel(coinNum) {
    let data = {};
    this.config.coin_level.forEach((el, i) => {
      if (el.min_num <= coinNum && coinNum < el.max_num) {
        data.levelName = el.levelName;
        data.index = i;
        data.level = el.level;
        data.time = el.time || 0;
      }
    });
    return data;
  },
  toMoney: function (str, s) {
    if (str === undefined) return str;

    var nums = str.toString().substr(0, 1) == '-' ? true : false,
      num = 0;
    str = str.toString().replace(/[^\d.]/g, "").split(".");
    str.length = 2, s = s || "", num = ((str[0] || 0) * 1000 / 1000).toString();
    str[1] = str[1] || 0;
    str[1] = Number("0." + str[1]).toString().substring(2, 4);
    if (str[1].length < 2) {
      for (var i = str[1].length; i < 2; i++) {
        str[1] += "0";
      }
    }
    for (var i = 0, j = Math.floor((num.length - (1 + i)) / 3); i < j; i++) {
      num = num.substring(0, num.length - (4 * i + 3)) + s + num.substring(num.length - (4 * i + 3));
    }
    str[0] = num;
    return (nums ? "-" : "") + str.join(".");
  },
  getRequestURL: function (query) {
    return this.config.apiServer + query + '.do';
  },
  // 一次性订阅信息(待完善数组) cancel————取消授权是否依旧执行
  requestMsg(tmplIds, cancel) {
    let arr = [];
    if (!this.isEmpty(tmplIds)) {
      if (Array.isArray(tmplIds)) {
        arr = tmplIds;
      }
      if (typeof tmplIds == 'string') {
        arr.push(tmplIds)
      }
    }
    return new Promise((resolve, reject) => {
      wx.requestSubscribeMessage({
        tmplIds: arr,
        success: (res) => {
          if (res[arr[0]] === 'accept') {
            resolve()
          }
          if (res[arr[0]] === "reject" && cancel) {
            resolve()
          }
        },
        fail(err) {
          reject()
        }
      })
    })
  },
  // 获取物品清单(副文本)
  getGoodstext(id) {
    let that = this;
    return new Promise((resolve, reject) => {
      that.ajax({
        func: 'ebusiness/listItems',
        data: {
          aid: id
        },
        load: false
      }, res => {
        if (res.code == 0) {
          resolve(res.data)
        }
      })
    })
  },
  // 获取物品清单(商品列表)
  getGoodsList(id) {
    let that = this;
    return new Promise((resolve, reject) => {
      that.ajax({
        func: 'ebusiness/recommend',
        data: {
          aid: id
        },
        load: false
      }, res => {
        if (res.code == 0) {
          resolve(res.data)
        }
      })
    })
  },
  // 获取阿里云图片信息
  getImageInfo(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: (result) => {
          if (result.errMsg == "getImageInfo:ok") {
            resolve(result.width + '*' + result.height)
          } else {
            reject('')
          }
        },
        fail: (res) => {
          reject('')
        },
      })
    })
  },
  // 获取物品推荐
  getGoodsRecommend(id) {
    let that = this;
    return new Promise((resolve, reject) => {
      that.ajax({
        func: 'ebusiness/checkExistItems',
        data: {
          aid: id
        },
        load: false
      }, res => {
        if (res.code == 0) {
          resolve(res.data)
        }
      })
    })
  },
  // 获取用户信息
  getUserInfo() {
    let that = this,
      loginuser = wx.getStorageSync("WXuserInfo") ? true : false;
    return new Promise(function (resolve, reject) {
      if (loginuser) {
        that.ajax({
          func: 'v2/user/info',
          load: false
        }, res => {
          if (res.code == 0) {
            resolve(res.data);
          } else {
            reject(res.reason);
          }
        });
      } else {
        reject(false);
      }
    })
  },
  // 获取用户佣金信息
  stat() {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: 'v2/user/stat',
        load: false
      }, res => {
        if (res.code == 0) {
          resolve(res.data);
        }
      });
    })
  },
  // 获取上一页地址
  getPrePageRoute() {
    let pages = getCurrentPages(); //页面对象
    let prevpage = pages[pages.length - 2]; //上一个页面对象
    return prevpage.route;
  },
  navigator: function (url) {
    let app = getApp();
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: url
      })
    } else {
      // 静默登录
      this.silentLogin().then(res => {
        wx.navigateTo({
          url: url
        })
      })
    }
  },
  isTimeLeng(val) {
    var s = val.toString();
    return s.length == 1 ? "0" + val : val;
  },
  showTips(msg, time) {
    wx.showToast({
      title: msg,
      icon: 'none',
      mask: true,
      duration: time || 2000
    });
  },
  // 对比时间是否已过期
  timeContrast(time) {
    if (!this.isEmpty(time) && time > 0) {
      let now = new Date().getTime();
      return (time - now >= 0 ? true : false);
    }
  },
  base64Encode: function (str) {
    str = this.utf16to8(str);
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out, i, len;
    var c1, c2, c3;
    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
      c1 = str.charCodeAt(i++) & 0xff;
      if (i == len) {
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt((c1 & 0x3) << 4);
        out += "==";
        break;
      }
      c2 = str.charCodeAt(i++);
      if (i == len) {
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt((c2 & 0xF) << 2);
        out += "=";
        break;
      }
      c3 = str.charCodeAt(i++);
      out += base64EncodeChars.charAt(c1 >> 2);
      out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
  },
  base64Decode(str) {
    var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1);
    var c1, c2, c3, c4;
    var i, len, out;
    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
      /* c1 */
      do {
        c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
      }
      while (i < len && c1 == -1);
      if (c1 == -1)
        break;
      /* c2 */
      do {
        c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
      }
      while (i < len && c2 == -1);
      if (c2 == -1)
        break;
      out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
      /* c3 */
      do {
        c3 = str.charCodeAt(i++) & 0xff;
        if (c3 == 61)
          return out;
        c3 = base64DecodeChars[c3];
      }
      while (i < len && c3 == -1);
      if (c3 == -1)
        break;
      out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
      /* c4 */
      do {
        c4 = str.charCodeAt(i++) & 0xff;
        if (c4 == 61)
          return out;
        c4 = base64DecodeChars[c4];
      }
      while (i < len && c4 == -1);
      if (c4 == -1)
        break;
      out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return this.utf8to16(out);
  },
  utf8to16(str) {
    var out, i, len, c;
    var char2, char3;
    out = "";
    len = str.length;
    i = 0;
    while (i < len) {
      c = str.charCodeAt(i++);
      switch (c >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
          // 0xxxxxxx
          out += str.charAt(i - 1);
          break;
        case 12:
        case 13:
          // 110x xxxx 10xx xxxx
          char2 = str.charCodeAt(i++);
          out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
          break;
        case 14:
          // 1110 xxxx10xx xxxx10xx xxxx
          char2 = str.charCodeAt(i++);
          char3 = str.charCodeAt(i++);
          out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
          break;
      }
    }
    return out;
  },
  utf16to8: function (str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        out += str.charAt(i);
      } else
        if (c > 0x07FF) {
          out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
          out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
          out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
  },
  formatDate: function (date, format, isFormat) {
    isFormat = isFormat != undefined ? isFormat : true;
    // date = new Date(date.replace(/-/g, "/"));
    date = typeof date == "string" ?
      new Date(date.replace(/-/g, "/")) :
      new Date(date);
    var format = format || "yyyy-MM-dd hh:mm:ss",
      o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),
        "S": date.getMilliseconds()
      };

    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    if (isFormat) {
      return new Date(format.replace(/-/g, "/"));
    } else {
      return format;
    }
  },
  decode: function (value, args) {
    var result = value;
    if (arguments.length > 0) {
      if (arguments.length == 1) {
        result = args;
      } else {
        for (var i = 1; i < arguments.length; i = i + 2) {
          if (arguments[i] != undefined) {
            if (arguments[i + 1] != undefined) {
              if (result == arguments[i]) {
                result = arguments[i + 1];
                break;
              }
            } else {
              result = arguments[i];
            }
          }
        }
      }
    }
    return result;
  },
  urlDecode: function (data, key) {
    if (data == null) return '';
    var t = typeof (data);
    if (t == 'string' || t == 'number' || t == 'boolean') {
      data = decodeURI(data);
    } else {
      for (var i in data) {
        data[i] = decodeURI(data[i]);
      }
    }
    return data;
  },
  toParam: function (param, key, encode) {
    if (param == null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
      paramStr += '&' + key + '=' + ((encode == null || encode) ? decodeURI(param) : param);
    } else {
      for (var i in param) {
        var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
        paramStr += this.toParam(param[i], k, encode);
      }
    }
    return paramStr;
  },
  isPhone: function (phone) {
    return typeof (phone) != "undefined" && (phone.length != 11 || !(/^1[3|4|5|6|7|8|9][0-9]{9}/.test(phone)));
  },
  delData: function (data, filed, val) {
    var newArr = new Array();
    for (var i = 0; i < data.length; i++) {
      var j = data[i];
      if (j[filed] != val) {
        newArr.push(j);
      }
    }
    return newArr;
  },
  formatUnixtimestamp: function (inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  formatMonth: function (begin, end) {
    let that = this;
    var arr = [],
      unixDb = begin - 24 * 60 * 60 * 1000,
      unixDe = end - 24 * 60 * 60 * 1000;
    for (var k = unixDb; k <= unixDe;) {
      k = k + 24 * 60 * 60 * 1000;
      var time = {
        text: that.formatDate(that.formatUnixtimestamp(k), 'MM月dd日', false),
        value: that.formatDate(that.formatUnixtimestamp(k), 'yyyy-MM-dd', false),
        active: (that.getNowFormatDate("yyyy-MM-dd") == that.formatDate(that.formatUnixtimestamp(k), 'yyyy-MM-dd', false) ? 1 : 0)
      };
      arr.push(time);
    }
    return arr;
  },
  getNowFormatDate: function (format) {
    format = format || "yyyy-MM-dd";
    return this.formatDate(this.formatUnixtimestamp(new Date().getTime()), format, false);
  },
  datedifference: function (sDate1, sDate2, compareSec) { //compareSec  ——是否比较至秒级 true-是  -false 否
    var dateSpan, tempDate, iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = compareSec ? dateSpan / 1000 : Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays;
  },
  isEmpty: function (obj) {
    var s = obj == null || obj == undefined ? "" : obj.toString().replace(/^\s+/, "").replace(/\s+$/, "");
    return s.length == 0;
  },
  isObjEmpty: function (obj) {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop))
        return false;
    }
    return true;
  },
  defaultIdcard: function (data) {
    if (typeof (data) == "undefined") {
      return "";
    }
    var self = this;
    for (var i in data) {
      data[i]['cardTypeStr'] = self.cardType(data[i]['cardType']);
      if (!self.isObjEmpty(data[i]['parent'])) {
        data[i]['parent']['cardTypeStr'] = self.cardType(data[i]['parent']['cardType']);
      }
    }
    return data;
  },
  cardType: function (cardType) {
    cardType = typeof (cardType) == "undefined" ? 0 : parseInt(cardType);
    return this.config.cardTypeArr[cardType];
  },
  identityCodeValid: function (code, str) {
    str = str.toUpperCase();
    if (parseInt(code) == 0) {
      var city = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外 "
      };
      if (!/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)) {
        return false;
      } else if (!city[str.substr(0, 2)]) {
        return false;
      } else {
        str = str.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
          ai = str[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if (parity[sum % 11] != str[17]) {
          return false;
        }
      }
      return true;
    } else {
      return !this.isEmpty(str);
    }
  },
  getSex(psidno) {
    var sexno;
    if (psidno.length == 18) {
      sexno = psidno.substring(16, 17);
    } else if (psidno.length == 15) {
      sexno = psidno.substring(14, 15);
    }
    return sexno % 2;
  },
  ages(str) {
    var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if (r == null) return "成人";
    var d = new Date(r[1], r[3] - 1, r[4]);
    if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
      var Y = new Date().getFullYear();
      var M = new Date().getMonth() + 1;
      var D = new Date().getDate();
      return Y - r[1] > 18 || (Y - r[1] == 18 && M - r[3] > 0) || (Y - r[1] == 18 && M - r[3] == 0 && D - r[4] >= 0) ? "成人" : "儿童"
    }
    return "成人";
  },
  getAge: function (strBirthday) {
    var returnAge, strBirthdayArr = strBirthday.split("-"),
      birthYear = strBirthdayArr[0],
      birthMonth = strBirthdayArr[1],
      birthDay = strBirthdayArr[2],
      d = new Date(),
      nowYear = d.getFullYear(),
      nowMonth = d.getMonth() + 1,
      nowDay = d.getDate();

    if (nowYear == birthYear) {
      returnAge = 0; //同年 则为0岁  
    } else {
      var ageDiff = nowYear - birthYear; //年之差  
      if (ageDiff > 0) {
        if (nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay; //日之差  
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          var monthDiff = nowMonth - birthMonth; //月之差  
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天  
      }
    }

    return parseInt(returnAge); //返回周岁年龄
  },
  // 渠道创建记录
  getChannelMsg(channel) {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: "user/channel/browhistory",
        data: {
          channelId: channel
        }
      }, function (res) {
        if (res.code == 0) {
          resolve(res);
        } else {
          reject(res);
        }
      });
    })
  },
  uploadFile(url, files, data = {}, isCall = false) {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: url,
        data: data
      }, (res) => {
        if (res.code == 0) {
          let oss = res.data,
            photoArrsm = '';
          if (files.indexOf('http://tmp/') != -1) {
            photoArrsm = oss.dir + files.replace('http://tmp/', "");
          }
          if (files.indexOf('wxfile://') != -1) {
            photoArrsm = oss.dir + files.replace('wxfile://', "");
          }
          let formData = {
            'key': photoArrsm,
            'policy': oss.policy,
            'OSSAccessKeyId': oss.accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'signature': oss.signature
          }
          if (isCall) formData.callback = oss.callback;
          setTimeout(() => {
            console.log(that.config.ossImgPath);
            const uploadTask = wx.uploadFile({
              url: that.config.ossImgPath,
              formData: formData,
              name: 'file',
              filePath: files,
              header: {
                'content-type': 'application/json'
              },
              method: 'post',
              success: (res) => {
                if (res.statusCode == 200) {
                  resolve({
                    code: 0,
                    uploadTask: uploadTask,
                    url: that.config.ossImgPath + photoArrsm
                  });
                } else {
                  reject({
                    code: -1,
                    reason: '上传失败，请重新上传。'
                  });
                }
              },
              fail(info) {
                reject({
                  code: -1,
                  reason: '上传失败，请重新上传。'
                });
              }
            });
          }, 1000);
        } else
          that.showTips(res.reason);
      })
    });
  },
  sendMessage: function (options, callBack) {
    console.log(options.key);
    if (typeof options != "object") return false;
    options.vid = ".code";
    var timer;
    this.ajax({
      func: "sendmcode",
      data: {
        phone: options['phone'],
        "type": options.type,
        key: options.key
      },
      load: options['load'] ? options['load'] : false,
      method: "POST",
    }, function (res) {
      if (res.code == 0) {
        btnTimer(options, function (text) {
          res.text = text;
          callBack(res);
        });
      } else {
        callBack(res);
      }
    });

    function btnTimer(options, callBack) {
      console.log(options.time);
      var i = options.time;
      timer = setInterval(function () {
        if (i == 0) {
          callBack(i);
          clearInterval(timer);
        } else {
          callBack(i);
          i--;
        }
      }, 1000);
    }
  },
  // 微信支付
  WXPay(data, aid, title, alone, method) {
    let that = this,
      app = getApp(),
      userInfo = app.globalData.userInfo;
    data.applet = '1';
    data.tradeType = 'JSAPI';
    data.openid = userInfo.socialUid;
    console.log(data);
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: "weixin/npre", //获取微信支付所需信息
        data: data,
        load: true,
        title: '请求中'
        // method:'POST'
      }, function (res) {
        if (res.code == 0) {
          let datas = res.data;
          wx.requestPayment({
            'timeStamp': datas.timestamp,
            'nonceStr': datas.nonce_str,
            'package': datas.package,
            'signType': datas.signType,
            'paySign': datas.sign,
            'success': function (result) {
              that.payResultWait(datas.orderid)
              wx.reportAnalytics('order_pay', {
                aid: aid,
                title: title,
              });
              resolve({
                orderid: datas.orderid,
                tradeChannelWeixin: res.tradeChannelWeixin,
                btype: data.btype
              });
              //CMBC --民生支付
            },
            'fail': function (result) {
              wx.showModal({
                title: '提示',
                content: '订单有5分钟的支付时间，超时后将自动取消订单，确定暂不支付？',
                confirmText: '继续支付',
                cancelText: '暂不支付',
                confirmColor: '#ee3a43',
                success: function (res) {
                  if (res.confirm) {
                    data.orderid = datas.orderid;
                    if (data.btype == 2) {
                      data.btype = 0;
                    }
                    that.WXPay(data, aid, title, alone).then((orderid) => {
                      var pages = getCurrentPages()
                      var currentPage = pages[pages.length - 2];
                      if (currentPage.route == "pages/product/activity/index" || currentPage.route == "pages/order/index/order" || currentPage.route == "pages/order/detail/index") {
                        let info = [];
                        info.push('orderid=' + orderid)
                        info.push('alone=' + alone)
                        info.push('btype=' + data.btype)
                        if (data.btype == 1) {
                          info.push('presellOpen=' + method)
                        } else if (data.btype == 2) {
                          info.push('presellStatus=' + method)
                        } else {
                          info.push('presellOpen=' + method)
                        }
                        // wx.navigateTo({
                        //   url: '/pages/order/success/index?orderid=' + orderid + '&alone=' + alone + '&presellOpen='+method+'&btype='+data.btype
                        // });
                        wx.navigateTo({
                          url: '/pages/order/success/index?' + info.join('&')
                        });
                      }
                    })
                  } else if (res.cancel) {
                    // if(!that.isEmpty(data.orderid)){
                    //   that.ajax({
                    //     func: 'order/pay/cancel',
                    //     data: { "oldOrderid": data.orderid, "orderid": datas.orderid },
                    //     load: false
                    //   }, function (res) {
                    //     reject(res);
                    //   });
                    // }else {
                    //   reject(res);
                    // }
                    var pages = getCurrentPages()
                    var currentPage = pages[pages.length - 1]
                    if (currentPage.route == "pages/product/buy/index") {
                      let info = 'orderid=' + datas.orderid + '&otype=1';
                      if (data.btype == 1) {
                        info = method == 0 ? (info + '&presellStatus=0') : (info + '&presellStatus=1')
                      } else if (data.btype == 2) {
                        info = info + '&presellStatus=' + method
                      } else if (data.btype == 0) {
                        info = info + '&presellStatus=0'
                      } else if (data.btype == 3) {
                        info = info + '&presellStatus=0'
                      }
                      wx.navigateTo({
                        url: '/pages/order/detail/index?' + info
                      })
                    }
                    if (currentPage.route == 'pages/product/balancePayment/balancePayment') {
                      let info = 'orderid=' + datas.orderid + '&otype=1' + '&presellStatus=2'
                      wx.navigateTo({
                        url: '/pages/order/detail/index?' + info
                      })
                    }
                  }
                }
              })
            }
          })
        } else {
          reject(res);
        }
      });
    });
  },
  ajax: function (options, success) {
    let app = getApp(),
      that = this;
    options.data = typeof (options.data) != "undefined" ? options.data : {};
    options.load = typeof (options.load) == "undefined" ? false : options.load;
    options.title = typeof (options.title) == "undefined" ? false : options.title;
    options.method = typeof (options.method) == "undefined" ? "GET" : options.method;
    if (options.load && options.title) {//评价相关接口调用弹窗避免重复调用
      wx.showLoading({
        title: options.title,
        mask: true
      });
    } else if (options.load) {
      wx.showLoading({
        title: '加载中…'
      });
    }
    for (let key in options.data) {
      if (options.data[key] === 'undefined') {
        options.data[key] = '';
      }
    }
    options.data['city'] = options.data['city'] || "永康" || "";
    options.data['platform'] = 1;
    // options.data['lat'] = app.globalData.city.latitude || "";
    // options.data['lng'] = app.globalData.city.longitude || "";
    options.data['rid'] = app.globalData.userInfo ? app.globalData.userInfo['rid'] : "";
    options.data['channel'] = options.data['channel'] || "applet";
    options.contentType = typeof (options.contentType) == "undefined" ? "application/json" : options.contentType;
    console.log(options.data, 7878)
    wx.request({
      url: this.getRequestURL(options.func),
      data: options.data,
      method: options.method,
      header: {
        "content-type": options.contentType
      },
      success(res) {
        options.load ? wx.hideLoading() : "";
        if (res.statusCode == 200) {
          if (res.data.code == 1004 || res.data.code == 1005) {
            wx.removeStorageSync("WXuserInfo");
            app.globalData.userInfo = null;
            if (res.data.code == 1004) {
              wx.navigateTo({
                url: '/pages/home/login'
              });
            }
            return false;
          }
          typeof (success) == "function" ? success(res.data) : "";
        } else {
          that.showTips("网络请求失败。");
          typeof (success) == "function" ? success(res) : "";
        }
      }
    });
  },
  // loadCity: function (callback, type) {
  //   var self = this;
  //   ({
  //     type: 'wgs84',
  //     success: function (res) {
  //       var myAmapFun = new self.amapFile.AMapWX({
  //         key: "4048819e3a45aa1cbac417a4e45f44aa"
  //       }); //  oldKey —— bae2697f5d1a1e5db9dd855e7cd083bf
  //       myAmapFun.getRegeo({
  //         location: res.longitude + ',' + res.latitude,
  //         success: function (data) {
  //           data[0]['regeocodeData']['addressComponent']['latitude'] = res.latitude;
  //           data[0]['regeocodeData']['addressComponent']['longitude'] = res.longitude;
  //           if (typeof (data[0]['regeocodeData']['addressComponent']['city']) == "object") {
  //             data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].join("");
  //           }
  //           data[0]['regeocodeData']['addressComponent']['city'] = self.isEmpty(data[0]['regeocodeData']['addressComponent']['city']) ? data[0]['regeocodeData']['addressComponent']['province'] : data[0]['regeocodeData']['addressComponent']['city'];
  //           data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].replace("市", "");
  //           self.businessCity().then(function (citys) {
  //             let getCity = wx.getStorageSync("city") || {};
  //             if (citys.includes(data[0]['regeocodeData']['addressComponent']['city']) || !self.isObjEmpty(getCity)) {
  //               if (!self.isObjEmpty(getCity) && type == undefined) data[0]['regeocodeData']['addressComponent'] = getCity;
  //               typeof (callback) == "function" ? callback({
  //                 code: 0,
  //                 data: data[0]['regeocodeData']['addressComponent'],
  //                 msg: "省市获取成功。"
  //               }): "";
  //             } else {
  //               typeof (callback) == "function" ? callback({
  //                 code: 2,
  //                 data: data[0]['regeocodeData']['addressComponent'],
  //                 msg: "省市获取失败。"
  //               }): "";
  //             }
  //           });
  //         },
  //       });
  //     },
  //     fail: function (info) {
  //       typeof (callback) == "function" ? callback({
  //         code: 1,
  //         data: {
  //           city: "未知城市"
  //         },
  //         msg: "省市获取失败。"
  //       }): "";
  //     }
  //   });
  // },
  // 支付成功后调用（不做回调处理）
  payResultWait(orderid) {
    let that = this;
    that.ajax({
      func: 'weixin/order/result/wait',
      data: {
        orderid: orderid
      },
      load: false
    }, function (res) { });
  },
  businessCity() {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: 'city_list',
        load: false
      }, function (res) {
        if (res.code == 0) {
          resolve(res.data.city);
        } else {
          reject();
        }
      });
    });
  },
  refreshCount() {
    let that = this,
      app = getApp();
    if (app != undefined && !that.isObjEmpty(app.globalData.userInfo)) {
      that.ajax({
        func: "user/stat_info",
        load: false
      }, function (res) {
        if (res.data) {
          let userInfo = app.globalData.userInfo;
          userInfo['membered'] = res.data.membered;
          userInfo['babyCoin'] = that.toMoney(res.data.coin, ",");
          res.data.score = Math.round(res.data.score);
          userInfo['role'] = that.userRole(res.data.score);
          userInfo['roleType'] = res.data.roleType || 'normal';
          userInfo['roleTypeDisable'] = res.data.roleTypeDisable || 0;
          userInfo['score'] = res.data.score;
          userInfo['weixin'] = res.data.weixin || 0;
          app.globalData.userInfo = userInfo;
          wx.setStorageSync("WXuserInfo", userInfo);
        }
      });
    }
  },
  userRole: function (val) {
    var that = this,
      str = that.config.userRole[0];
    for (let i = 0; i < that.config.userRole.length; i++) {
      if (parseFloat(val) >= parseFloat(that.config.userRole[i].startPoint) && (that.config.userRole[i].endPoint == undefined || parseFloat(val) <= parseFloat(that.config.userRole[i].endPoint))) {
        str = that.config.userRole[i];
      }
    }
    return str;
  },
  // 完成宝贝币任务
  finishCoinTask(taskId, onlyCoin) {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: "v2/user_coin/task/pass",
        data: {
          taskId: taskId
        },
        method: "POST",
        load: false
      }, function (res) {
        if (res.code == 0) {
          if (onlyCoin) {
            resolve(res.data)
          } else {
            let text = '恭喜你完成任务，获得' + res.data + '枚宝贝币'
            resolve(text)
          }
        } else {
          resolve(res.reason)
        }
      });
    })
  },
  // 通过小程序码进入的获取活动aid
  codeGetAid(aid) {
    let that = this;
    return new Promise(function (resolve, reject) {
      that.ajax({
        func: "v2/article/aid",
        data: {
          "aid": aid
        }
      }, function (res) {
        if (res.code == 0) {
          resolve(res)
        } else {
          reject(res)
        }
      });
    })
  },
  promise: function () {
    var that = this,
      app = getApp();
    return new Promise(function (resolve, reject) {
      // that.loadCity(function (res) {
      //   let city = app.globalData.city;
      //   if (res.code == 0) { //获取地址成功
      //     app.globalData.locationCity = res.data.city;
      //     if (!that.isObjEmpty(city) && res.data.city != city.city && app.globalData.path == 'pages/index/index') {
      //       wx.hideLoading();
      //       wx.showModal({
      //         title: "温馨提示",
      //         content: "自动定位地理位置为“" + res.data.city + "”，是否切换到“" + res.data.city + "”？",
      //         success: function (d) {
      //           if (d.confirm) {
      //             app.globalData.previous = city.city;
      //             app.globalData.city = res.data;
      //             wx.setStorageSync("city", app.globalData.city);
      //             resolve(true)
      //           } else {
      //             resolve(true)
      //           }
      //         }
      //       });
      //     } else {
      //       app.globalData.city = res.data;
      //       wx.setStorageSync("city", app.globalData.city);
      //       resolve(true)
      //     }
      //   } else if (res.code == 1 || res.code == 2) { //获取地址失败
      //     if (that.isObjEmpty(city) || res.code == 2) { //全局地址为空
      //       var e = getCurrentPages(),
      //         url = (e.length <= 0 ? "/pages/index/index" : "/" + (e[e.length - 1].route));
      //       reject('reject');
      //       app.globalData.city = {};
      //       wx.removeStorageSync("city");
      //       wx.redirectTo({
      //         url: '/pages/city/list?query=selectCity&url=' + url
      //       });
      //     } else { //全局地址city['city']存在
      //       resolve(true)
      //     }
      //   }
      that.refreshCount();
      // });
    })
  },
  // 静默登录
  silentLogin() {
    let that = this;
    let app = getApp();
    return new Promise(function (resolve, reject) {
      wx.login({
        success: res => {
          let it = {};
          it.version = "applet_v1.0.0";
          it.code = res.code;
          it.target = 'challengerhome';
          that.ajax({
            func: "applet_login",
            data: it
          }, function (data) {
            if (data.code == 0) {
              // 第一次登录未注册
              if (data.data.firstLogin == 1) {
                wx.navigateTo({
                  url: '/pages/home/login',
                });
                reject()
              } else {
                data.data.role = that.userRole(Math.round(data.data.score));
                // 强制退出登录
                data.data.VERSION = 9
                wx.setStorageSync("WXuserInfo", data.data);
                app.globalData.userInfo = data.data
                resolve()
              }
            } else {
              that.showTips(data.reason);
            }
          });
        }
      });
    })
  }

}