// const { baseUrl } = require('./env.js').prod; // 正式
const { baseUrl } = require('./env.js').test; // 测试

// token
let Authorization = "";
const jsonType = {"content-type":"application/json"}
const urlencodeType = {"content-type":"application/x-www-form-urlencoded"}

// 错误类型
let statusCode = {
  '1': "请求数据失败",
  "400": "参数列表错误",
  "401": "请先登录",
  "403": "禁止访问",
  "404": "资源，服务未找到",
  "405": "错误请求方法",
  "409": "冲突",
  "413": "上传文件太大",
  "500": "服务器错误",
  "1000": "账户已在别处登录"
}

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, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
};

// 封装wx.request

function _show_error(error_code) {
  wx.showToast({
    "title": statusCode[error_code],
    "icon": "error",
    "duration": 1500
  });
}

// 
function request(url,data={},method="GET", header=urlencodeType, isToken=true) {

  if(isToken) {
    try {
      var value = wx.getStorageSync('token')
      if (value) {
        const resData = JSON.parse(value);
        Authorization = resData.token;
      }
    } catch (e) {
      Authorization = "";
    }
  }
  // 拼接地址
  let fullurl = `${baseUrl}${url}`
  //返回异步操作成功的结果和返回异步操作失败的结果
  wx.showLoading({
    title: '加载中',
  });
  return new Promise((resolve,reject)=>{
      wx.request({
        url: fullurl,
        method,
        data,
        header:Object.assign({
          "content-type":"application/x-www-form-urlencoded",
          "appid": "wx08f94a3e90881910",
          "Authorization": isToken ? Authorization : undefined
        }, header),
        success(res){
          // console.log("接口：",fullurl, res)
          wx.hideLoading();
          if(res.statusCode !== 200 ) {
            wx.showToast({
              "title": "请求错误",
              "icon": "error",
              "duration": 1500
            });
            return;
          }
          if(res.data.code===0){
            resolve(res.data.data);
          } else if(res.data.code === 401) {
            // token过期
            try {
              // 删除过期token
              wx.removeStorageSync('token');
            } catch (e) {
              console.log("可能没有这个缓存")
            };
            // getCurrentPages()[0].login();
            // request(url,data,method,header,isToken);
          } else{
            _show_error(res.data.code)
          }
        },
        fail: (err) => {
          _show_error("1");
          wx.hideLoading();
        }
      })
  })
}

function isCN(str) {
  if (/^[\u3220-\uFA29]+$/.test(str)) {
    return true;
  } else {
    return false;
  }
}


module.exports = {
  formatTime,
  request,
  formatNumber,
  isCN,
  urlencodeType,
  jsonType
}
