var baseurl = "https://weijinxiao.aclass.baca-ai.com/api/"
var resourceurl = ""
var imgurl = "/image/"
var baseImgUrl = baseurl + "file/getimg?fileUrl="

function query(url, data, callback, type, notoken) {
  var token = wx.getStorageSync("token")
  if (token || notoken) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: (url.startsWith("http") ? '' : baseurl) + url,
      data: data,
      dataType: 'json',
      success: function(d) {
        wx.hideLoading();
        if (d.statusCode === 200) {
          callback(d.data);
        } else if (d.statusCode === 401) {
          wx.showToast({
            title: '登录状态过期',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'none',
            duration: 2000
          })
        }

      },
      method: type == undefined ? "GET" : type,
      header: {
        'token': token
      }
    })
  } else {
    wx.showToast({
      title: '请登录',
      icon: 'none',
      duration: 2000
    })
  }

}

function checklogin(callback) {
  var token = wx.getStorageSync("token")
  if (token) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: baseurl + 'userinfo/wxapi/findbyid',
      data: {
        id: 0
      },
      dataType: 'json',
      success: function(d) {
        wx.hideLoading();
        if (d.statusCode === 401) {
          wxlogin(callback)
        } else {
          callback();
        }

      },
      method: "GET",
      header: {
        'token': token
      }
    })
  } else {
    wx.setStorageSync('userinfo', '')
    wx.showToast({
      title: '请登录',
      icon: 'none',
      duration: 2000
    })
  }
}

function wxlogin(callback) {
  wx.login({
    success: function(res) {
      if (res.code) {
        console.log(res.code);
        query(
          "/cuser/wxapi/getopenid", {
            code: res.code
          },
          function(da) {
            if (da.code === 10000) {
              if (da.registed) {
                wx.setStorageSync("token", da.token)
                wx.setStorageSync("userinfo", da.userinfo)
                callback()
              } else {
                wx.setStorageSync('userinfo', '')
                wx.showToast({
                  title: '请登录',
                  icon: 'none',
                  duration: 2000
                })
              }
            } else {
              wx.showToast({
                title: '登录失败',
                icon: 'none',
                duration: 2000
              })
            }
          }, "get", 1
        )
      } else {
        wx.showToast({
          title: '登录失败',
          icon: 'none',
          duration: 2000
        })
        console.log('获取用户登录态失败！' + res.errMsg)
      }
    }
  })
}


const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}
const formatShortTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
}
const formatTimeAndWeek = date => {
  var show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':') + " " + show_day[date.getDay()]
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function isChinese(temp) {
  if (escape(temp).indexOf("%u") < 0) {
    return false;
  } else {
    return true;
  }

}




function initopenid(callback) {
  var openid = wx.getStorageSync('openid');
  if (openid == "" || openid == undefined) {
    wx.login({
      success: function(res) {
        if (res.code) {
          console.log(res.code);
          query(
            "/cuser/wxapi/getopenid", {
              code: res.code
            },
            function(da) {
              if (da.result == "1") {
                wx.setStorageSync("openid", da.openid)
                callback(da.openid);
              } else {
                wx.showToast({
                  title: '登录失败',
                  icon: 'none',
                  duration: 2000
                })
              }
            }, "get", 1
          )

        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'none',
            duration: 2000
          })
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  } else {
    callback(openid)
  }
}

function saveUserInfo(openid, userinfo, callback) {
  query("/cuser/wxcheckcuser", {
    openId: openid
  }, function(d) {
    if (d.code == 10001) {
      query("/cuser/wxcreatecuser", {
        openId: openid,
        nickName: userinfo.nickName,
        city: userinfo.city,
        province: userinfo.province,
        gender: userinfo.gender,
        avatarUrl: userinfo.avatarUrl
      }, function(d) {
        if (d.code == 10000) {
          if (typeof callback == "function") {
            callback(d.cuser);
          }
        }
      }, "POST")
    } else {
      if (typeof callback == "function") {
        callback(d.data);
      }
    }
  });
}

function showToast(str, time) {
  wx.showToast({
    title: str,
    icon: 'none',
    duration: time == undefined ? 2000 : time,
    mask: true
  })
}

function checkPhone(phone) {
  if (!(/^1(3|4|5|7|8|9)\d{9}$/.test(phone))) {
    return false;
  }
  return true;
}

function checknullstr(map) {
  for (var key in map) {
    if (map[key] == null) {
      delete map[key];
    }

  }
  return map;
}




function isCardID(sId) {
  var iSum = 0;
  var info = "";
  if (!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
  sId = sId.replace(/x$/i, "a");
  if (aCity[parseInt(sId.substr(0, 2))] == null) return "你的身份证地区非法";
  var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
  var d = new Date(sBirthday.replace(/-/g, "/"));
  if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return "身份证上的出生日期非法";
  for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
  if (iSum % 11 != 1) return "你输入的身份证号非法";
  //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
  return true;
}


function toRad(d) {
  return d * Math.PI / 180;
}

function getDisance(lat1, lng1, lat2, lng2) {
  var dis = 0;
  var radLat1 = toRad(lat1);
  var radLat2 = toRad(lat2);
  var deltaLat = radLat1 - radLat2;
  var deltaLng = toRad(lng1) - toRad(lng2);
  var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
  return dis * 6378137;
}

function checkABC(string) {
  var p = /[A-Z]/i;
  return p.test(string);
}

function PointNum(obj) {
  obj = obj.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  obj = obj.replace(/^\./g, ""); //验证第一个字符是数字
  obj = obj.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
  obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
  obj = obj.replace(/^[0]+/, "");
  return obj;
}

function getPayWay(callback) {
  query('userSetting/wxapi/getMySetting', {}, function(res) {
    if (res.code === 10000) {
      res = res.data
      var py = []
      if (res.payWay1) {
        py.push({
          key: 1,
          name: res.payWay1
        })
      }
      if (res.payWay2) {
        py.push({
          key: 2,
          name: res.payWay2
        })
      }
      if (res.payWay3) {
        py.push({
          key: 3,
          name: res.payWay3
        })
      }
      if (res.payWay4) {
        py.push({
          key: 4,
          name: res.payWay4
        })
      }
      if (res.payWay5) {
        py.push({
          key: 5,
          name: res.payWay5
        })
      }
      if (res.payWay6) {
        py.push({
          key: 6,
          name: res.payWay6
        })
      }
      if (res.payWay7) {
        py.push({
          key: 7,
          name: res.payWay7
        })
      }
      if (res.payWay8) {
        py.push({
          key: 8,
          name: res.payWay8
        })
      }
      if (callback) {
        callback(py)
      }
    }
  })
}
module.exports = {
  formatTime: formatTime,
  isChinese: isChinese,
  baseurl: baseurl,
  query: query,
  resourceurl: resourceurl,
  initopenid: initopenid,
  saveUserInfo: saveUserInfo,
  showToast: showToast,
  checkPhone: checkPhone,
  checknullstr: checknullstr,
  isCardID: isCardID,
  getDisance: getDisance,
  formatTimeAndWeek: formatTimeAndWeek,
  formatShortTime: formatShortTime,
  imgurl: imgurl,
  checkABC: checkABC,
  baseImgUrl: baseImgUrl,
  checklogin: checklogin,
  PointNum: PointNum,
  getPayWay: getPayWay
}