const md5 = require('./md5.js');
const urlsDef = require('./urls.js');
const accessHeader = {
  accessKey: '',
  appId: ''
};

const notWxApiPath = urlsDef.urls.baseUrl + '/schoolbaby/api/';
const apiPath = urlsDef.urls.baseUrl + '/schoolbaby/api/wx/';


function fun_date(num) {
  var date1 = new Date();
  //今天时间
  var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate()
  var date2 = new Date(date1);
  date2.setDate(date1.getDate() + num);
  //num是正数表示之后的时间,num负数表示之前的时间,0表示今天
  var month = date2.getMonth() + 1
  if (month < 10) {
    month = "0" + month
  }
  var date = date2.getDate()
  if (date < 10) {
    date = "0" + date
  }
  var time2 = date2.getFullYear() + "-" + (month) + "-" + date;
  return time2;
}

function fun_week(datestr) {
  var weekArray = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
  var week = weekArray[new Date(datestr).getDay()];
  return week;
}


//经纬度算距离
function distance(la1, lo1, la2, lo2) {
  var La1 = la1 * Math.PI / 180.0;
  var La2 = la2 * Math.PI / 180.0;
  var La3 = La1 - La2;
  var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(2);
  return s;
}

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(':')
}

function curTime() {
  const date = new 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(':')
}

function validDay(val) {
  var todayDate = new Date()
  var today = todayDate.getFullYear() + '/' + (todayDate.getMonth() + 1) + '/' + todayDate.getDate()
  var date = new Date(today);
  date.setDate(date.getDate() + val);
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return year + '-' + month + '-' + day;
}

//相隔天数
function getDayBetween(sDate1, sDate2) {
  //Date.parse() 解析一个日期时间字符串,并返回1970/1/1 午夜距离该日期时间的毫秒数
  var time1 = Date.parse(new Date(sDate1.substring(0, 10)));
  var time2 = Date.parse(new Date(sDate2.substring(0, 10)));
  var nDays = parseInt((time1 - time2) / 1000 / 3600 / 24);
  return nDays;
}

//相隔小时
function validHour(s1, s2) {
  s1 = new Date(s1.replace(/-/g, '/'));
  s2 = new Date(s2.replace(/-/g, '/'));
  var ms = s1.getTime() - s2.getTime();
  var hours = (ms / 1000 / 60 / 60).toFixed(1);
  return hours;
}

//相隔分钟
function validMinutes(startTime, endTime) {
  //定义两个变量time1,time2分别保存开始和结束时间
  var time1 = startTime;
  var time2 = endTime;

  //截取字符串,得到日期部分,用split把字符串分隔成数组
  var begin1 = time1.substr(0, 10).split("/");
  var end1 = time2.substr(0, 10).split("/");

  //将拆分的数组重新组合,并实例成化新的日期对象
  var date1 = new Date(begin1[1] + '/' + begin1[2] + '/' + begin1[0]);
  var date2 = new Date(end1[1] + '/' + end1[2] + '/' + end1[0]);

  //得到两个日期之间的差值m,以分钟为单位
  //Math.abs(date2-date1)计算出以毫秒为单位的差值
  //Math.abs(date2-date1)/1000得到以秒为单位的差值
  //Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
  var m = parseInt((date2 - date1) / 1000 / 60);

  //小时数和分钟数相加得到总的分钟数
  //time1.substr(11,2)截取字符串得到时间的小时数
  //parseInt(time1.substr(11,2))*60把小时数转化成为分钟
  var min1 = parseInt(time1.substr(11, 2)) * 60 + parseInt(time1.substr(14, 2));
  var min2 = parseInt(time2.substr(11, 2)) * 60 + parseInt(time2.substr(14, 2));

  //两个分钟数相减得到时间部分的差值,以分钟为单位
  var n = min1 - min2;

  //将日期和时间两个部分计算出来的差值相加,即得到两个时间相减后的分钟数
  var minutes = m + n;
  return minutes
}

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

function getAccessKey(ticket) {
  return md5.md5(accessHeader.accessKey + '@' + ticket)
}

function getHeaders() {
  // console.log('accessHeader : ' + JSON.stringify(accessHeader));
  let ticket = new Date().getTime();
  // 将key作为密钥,根据accessKey 生成 加密的 accessKey(暂未实现)
  return {
    'Access-Ticket': ticket,
    'Access-Key': getAccessKey(ticket),
    'Access-AppId': accessHeader.appId,
    'SSO-TOKEN': wx.getStorageSync('sso-token')
  }
}

function setAccessHeader(accessKey, appId) {
  accessHeader.appId = appId;
  accessHeader.accessKey = accessKey;
}

function apiPost(url, params, contentType) {
  return new Promise((resolve, reject) => {
    let headers = getHeaders();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    if (contentType) {
      headers['Content-Type'] = contentType;
    }
    wx.request({
      url: url,
      header: headers,
      data: params,
      method: 'POST',
      success: res => {
        if (res.success > 1 || typeof res.version != undefined) {
          resolve(res.data)
        } else {
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '加载失败,请重试',
                icon: 'none'
              })
            },
          })
        }
      },
      faild: res => {
        // reject(res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: res.errMsg,
            })
          },
        })
      }
    })
  }).catch(err => {
    console.log(err)
  })
}

function doPost(url, params) {
  return new Promise((resolve, reject) => {
    let headers = getHeaders();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    wx.request({
      url: apiPath + url,
      header: headers,
      data: params,
      method: 'POST',
      success: res => {
        if (res.success > 1 || typeof res.version != undefined) {
          resolve(res.data)
        } else {
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '加载失败,请重试',
                icon: 'none'
              })
            },
          })
        }
      },
      faild: res => {
        // reject(res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: res.errMsg,
            })
          },
        })
      }
    })
  }).catch(err => {
    console.log(err)
  })
}

function notWxPost(url, params) {
  return new Promise((resolve, reject) => {
    let headers = getHeaders();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    wx.request({
      url: notWxApiPath + url,
      header: headers,
      data: params,
      method: 'POST',
      success: res => {
        if (res.success > 1 || typeof res.version != undefined) {
          resolve(res.data)
        } else {
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '加载失败,请重试',
                icon: 'none'
              })
            },
          })
        }
      },
      faild: res => {
        // reject(res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: res.errMsg,
            })
          },
        })
      }
    })
  }).catch(err => {
    console.log(err)
  })
}


module.exports = {
  formatTime: formatTime,
  doPost: doPost,
  notWxPost: notWxPost,
  validDay: validDay,
  validMinutes: validMinutes,
  getDayBetween: getDayBetween,
  validHour: validHour,
  curTime: curTime,
  setAccessHeader: setAccessHeader,
  distance: distance,
  apiPost: apiPost,
  fun_date: fun_date,
  fun_week: fun_week

}