
//login
var API_LOGIN = "store/cashier/login";
const app = getApp()
//返回的数据都为code、data的形式

function login({ baseUrl, name, password, callback }) {
  var loginRequest = createCommonRequest();
  loginRequest.username = name;
  loginRequest.password = password;
  loginRequest.loginType = "1";
  console.log("login request==>" + JSON.stringify(loginRequest));
  var loginResponse = { code: {}, data: {} };
  my.request({
    url: baseUrl + API_LOGIN,
    method: 'POST',
    dataType: 'json',
    timeout: 30000,
    data: loginRequest,
    success: (res) => {
      console.log("login success==>" + JSON.stringify(res.data));
      if (callback != null) {

        if (res.data.success != true) {
          loginResponse.code = -1;
          //重置data内容
          loginResponse.data = res.data.errorMsg;
        } else {
          loginResponse.code = 0;
          loginResponse.data = res.data.data;
        }

        callback(loginResponse);
      }
    },
    fail: (res) => {
      console.log("login fail==>" + JSON.stringify(res));
      if (callback != null) {
        loginResponse.code = -1;
        loginResponse.data = decodeErrorMessage(res.error);
        callback(loginResponse);
      }
    }
  });
}


function createCommonRequest() {
  var commonRequest = {
  };
  commonRequest.appId = app.globalData.appId;
  //token 设置到公共请求体
  if (app.globalData.localAccountInfo != null) {
    commonRequest.token = app.globalData.localAccountInfo.token;
  }
  if (app.globalData.sn == null || app.globalData.sn == "") {
    commonRequest.deviceNo = "unknow";
  } else {
    commonRequest.deviceNo = app.globalData.sn;
  }
  commonRequest.batchNo = "";
  commonRequest.timestamp = timestampToTime();
  commonRequest.format = "JSON";
  commonRequest.charset = "utf-8";
  commonRequest.signType = "RSA2";
  commonRequest.version = "1.0";
  commonRequest.sign = "qt-pos";

  return commonRequest;
}


function timestampToTime() {
  var date = new Date();
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}

function decodeErrorMessage(error) {
  if (error == null) {
    return "请求失败";
  }
  switch (error) {
    case "11": return "无权跨域";
    case "12": return "网络出错";
    case "13": return "请求超时";
    case "14": return "解码失败";
    case "19": return "HTTP错误";
    case "20": return "请求已被停止/服务端限流";
  }
  return "请求失败";
}

module.exports.login = login;
module.exports.createCommonRequest = createCommonRequest;
module.exports.decodeErrorMessage = decodeErrorMessage;