const Service = require("./service.js");

function stripTags(str, r_str = "") {
  //去掉所有的html标记
  return str.replace(/<[^>]+>/g, r_str);
}
//photo
function imageUtil(e) {
  var imageSize = {};
  var originalWidth = e.detail.width; //图片原始宽 
  var originalHeight = e.detail.height; //图片原始高 
  var originalScale = originalHeight / originalWidth; //图片高宽比 
  // console.log('originalWidth: ' + originalWidth)
  // console.log('originalHeight: ' + originalHeight)
  //获取屏幕宽高 
  wx.getSystemInfo({
    success: function (res) {
      var windowWidth = res.windowWidth;
      var windowHeight = res.windowHeight;
      var windowscale = windowHeight / windowWidth; //屏幕高宽比 
      // console.log('windowWidth: ' + windowWidth)
      // console.log('windowHeight: ' + windowHeight)
      if (originalScale < windowscale) { //图片高宽比小于屏幕高宽比 
        //图片缩放后的宽为屏幕宽 
        imageSize.imageWidth = windowWidth;
        imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
      } else { //图片高宽比大于屏幕高宽比 
        //图片缩放后的高为屏幕高 
        imageSize.imageHeight = windowHeight;
        imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
      }

    }
  })
  // console.log('缩放后的宽: ' + imageSize.imageWidth)
  // console.log('缩放后的高: ' + imageSize.imageHeight)
  return imageSize;
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

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

function getLoc(callback) {
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      callback(res)
    }
  })
}

function stripTags(str, r_str = "") {
  //去掉所有的html标记
  return str.replace(/<[^>]+>/g, r_str);
}

function Base64() {

  // private property  
  let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  // public method for encoding  
  this.encode = function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = _utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
  }

  // public method for decoding  
  this.decode = function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i++));
      enc2 = _keyStr.indexOf(input.charAt(i++));
      enc3 = _keyStr.indexOf(input.charAt(i++));
      enc4 = _keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = _utf8_decode(output);
    return output;
  }

  // private method for UTF-8 encoding  
  var _utf8_encode = function (string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }
    return utftext;
  }

  // private method for UTF-8 decoding  
  var _utf8_decode = function (utftext) {
    var string = "";
    let i = 0;
    let c = 0;
    let c1 = 0;
    let c2 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }

  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}
//非空判断
function isEmpty(obj) {
  if (!obj || obj == "undefined" || obj == null || obj == 'null' || obj == "") {
    return true;
  } else {
    return false;
  }
}
// 时间戳转为分钟数
function reversalTime(e) {
  let a = parseInt(e / 1000);
  let hour = (a / 3600 >= 1) ? parseInt(a / 3600) : 0;
  let minute = ((a % 3600) / 60 >= 1) ? parseInt((a % 3600) / 60) : 0;
  let second = ((a % 3600) % 60 > 0) ? ((a % 3600) % 60) : 0;
  let str = hour + ':' + minute + ':' + second;
  return str;
}
// 时间戳转日期
function timestampToTime(timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes();
  D = D < 10 ? '0' + D : D;
  m = m < 10 ? '0' + m : m;
  return Y + M + D;
}
// 时间戳转日期
function timestampToTimeN(timestamp) {
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes();
  D = D < 10 ? '0' + D : D;
  m = m < 10 ? '0' + m : m;
  return Y + M + D;
}
// 将时间戳转为时间
function timeMethod(timestamp) {
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes();
  D = D < 10 ? '0' + D : D;
  m = m < 10 ? '0' + m : m;
  return Y + M + D + h + m;
}
/**
 * 时间戳转换为刚刚、N分钟前、今天几点几分、昨天几点几分等表示法
 * @param {时间戳} timestamp 
 */
function timestampFormat(timestamp) {
  function zeroize(num) {
    return (String(num).length == 1 ? '0' : '') + num;
  }
  var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

  var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
  var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

  var Y = tmDate.getFullYear(),
    m = tmDate.getMonth() + 1,
    d = tmDate.getDate();
  var H = tmDate.getHours(),
    i = tmDate.getMinutes(),
    s = tmDate.getSeconds();

  if (timestampDiff < 60) { // 一分钟以内
    return "刚刚";
  } else if (timestampDiff < 3600) { // 一小时前之内
    return Math.floor(timestampDiff / 60) + "分钟前";
  } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
    // return '今天' + zeroize(H) + ':' + zeroize(i);
    return zeroize(H) + ':' + zeroize(i);
  } else {
    var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
    if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
      return '昨天 ' + zeroize(H) + ':' + zeroize(i);
    } else if (curDate.getFullYear() == Y) {
      return zeroize(m) + '/' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
    } else {
      return Y + '/' + zeroize(m) + '/' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
    }
  }
}
/**
 * IM聊天转换时间戳
 * @param {时间戳} timestamp 
 */
function timestampIM(timestamp) {
  function zeroize(num) {
    return (String(num).length == 1 ? '0' : '') + num;
  }
  var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  // var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

  var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
  var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

  var Y = tmDate.getFullYear(),
    m = tmDate.getMonth() + 1,
    d = tmDate.getDate();
  var H = tmDate.getHours(),
    i = tmDate.getMinutes(),
    s = tmDate.getSeconds();
  if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
    // return '今天' + zeroize(H) + ':' + zeroize(i);
    return zeroize(H) + ':' + zeroize(i);
  } else {
    var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
    if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
      return '昨天 ' + zeroize(H) + ':' + zeroize(i);
    } else if (curDate.getFullYear() == Y) {
      return zeroize(m) + '-' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
    } else {
      return Y + '-' + zeroize(m) + '-' + zeroize(d) + ' ' + zeroize(H) + ':' + zeroize(i);
    }
  }
}
/**
 * 秒数转换时间
 * @param {Int} value 
 */
function formatSeconds(value) {
  var theTime = parseInt(value); // 秒
  var middle = 0; // 分
  var hour = 0; // 小时

  if (theTime > 60) {
    middle = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (middle > 60) {
      hour = parseInt(middle / 60);
      middle = parseInt(middle % 60);
    }
  }
  if (theTime < 10) {
    theTime = '0' + theTime;
  }
  if (middle < 10) {
    middle = '0' + middle;
  }
  if (hour < 10) {
    hour = '0' + hour;
  }
  var result = hour + ":" + middle + ":" + theTime;
  return result;
}
//生日计算年龄
function getAge(strBirthday) {
  var returnAge = '';
  var strBirthdayArr = strBirthday.split("-");
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if (nowYear == birthYear) {
    returnAge = '1';
  } 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 returnAge; //返回周岁年龄+月份
}

function call(linktel) {
  wx.makePhoneCall({
    phoneNumber: linktel
  })
}

function isUnionid() {

}
/**
 *身份验证 
 * @param {string} idCard 身份证号码 
 */
function validateIdCard(idCard) {
  //15位和18位身份证号码的正则表达式
  var regIdCard = /^(^[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])$)$/;
  //如果通过该验证，说明身份证格式正确，但准确性还需计算
  if (regIdCard.test(idCard)) {
    if (idCard.length == 18) {
      var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
      var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
      var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
      for (var i = 0; i < 17; i++) {
        idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
      }
      var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
      var idCardLast = idCard.substring(17); //得到最后一位身份证号码

      //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
      if (idCardMod == 2) {
        if (idCardLast == "X" || idCardLast == "x") {
          return true;
        } else {
          return false;
        }
      } else {
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if (idCardLast == idCardY[idCardMod]) {
          return true;
        } else {
          return false;
        }
      }
    }
  } else {
    return false;
  }
}

function alert(msg, callback) {
  wx.showModal({
    content: msg,
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        if (callback) {
          callback('ok')
        }
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  });
}
/**
 * 身份证号换出生日期
 * @param {string} idCard 身份证号码 
 */
function getBirthdayFromIdCard(idCard) {
  var birthday = "";
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6);
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }
  return birthday;
}
/**
 * 身份证号换出生日期
 * @param {string} idCard 身份证号码
 */
function getSexFromIdCard(idCard) {
  var sex = "0";
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      if (parseInt(idCard.substr(14, 1)) % 2 == 1) {
        sex = '0';
        //是男则执行代码 ...
      } else {
        sex = '1';
        //是女则执行代码 ...
      }

    } else if (idCard.length == 18) {
      if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
        sex = '0';
        //是男则执行代码 ...
      } else {
        sex = '1';
        //是女则执行代码 ...
      }
    }
  }
  return sex;
}
/**
 * 验证身份证与姓名是否相符
 * @param {string} name 姓名 
 * @param {string} idCard 身份证 
 * @param {callback} C 回调函数
 */
function verifyIdCardAnName(name, idCard, C) {
  var data = {
    idCard: idCard,
    name: name,
    unionid: wx.getStorageSync('data').unionid
  }
  Service.checkCard(data).then((res) => {
    C(res.code);
  })
}
// 对象深拷贝函数
function deepClone(initalObj) {
  var obj = {};
  obj = JSON.parse(JSON.stringify(initalObj));
  return obj;
}

function getTitle(code) {
  let arr = ['', '住院医师', '主治医师', '副主任医师', '主任医师', '国家心理治疗师', '国家二级心理咨询师', '国家三级心理咨询师']
  return arr[code];
}
/**
 * 防抖动函数
 * @param {function} func 实际要执行的函数
 * @param {interval} delay 延迟时间，也就是阈值，单位是毫秒（ms）
 * @param {boolean} immediate  是否立即执行
 * @return {function}  返回一个“去弹跳”了的函数
 */
// function debouce(func, delay, immediate) {
//   let timer = 0;
//   return function () {
//     var context = this; //闭包取当前函数this
//     let timestamp = Date.parse(new Date());//时间戳
//     console.log("timestamp",timestamp);
//     console.log("timer",timer);
//     if((timestamp-timer)>=delay){
//       console.log('delay',timestamp-timer,delay)
//       console.log("11111111");
//       func.apply(context, arguments);
//     }
//     timer=timestamp;
//   }
// }
function debouce(func, delay, immediate) {
  let timer;
  return function () {
    var context = this; //闭包取当前函数this
    if (timer) clearTimeout(timer);
    if (immediate) {
      console.log()
      var doNow = !timer;
      //每一次都重新设置timer，就是要保证每一次执行的至少delay秒后才可以执行
      timer = setTimeout(function () {
        timer = null;
      }, delay);
      //根据距离上次触发操作的时间是否到达delay来决定是否要现在执行函数

      //立即执行
      if (doNow) {
        //封装实参的对象arguments
        func.apply(context, arguments);
      }
    } else {
      timer = setTimeout(function () {
        func.apply(context, arguments);
      }, delay);
    }
  }
}
/**
 * 节流函数
 * @param {function} fn 实际要执行的函数
 * @param {interval} interval 间隔时间，如果interval不传，则默认300ms
 */
function throttle(fn, interval) {
  var enterTime = 0; //触发的时间
  var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
  return function () {
    var context = this; //闭包取当前函数this
    var backTime = new Date(); //第一次函数return即触发的时间
    if (backTime - enterTime >= gapTime) {
      //封装实参的对象arguments
      fn.apply(context, arguments);
      enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  };
}

module.exports = {
  formatTime: formatTime,
  getLoc: getLoc,
  stripTags: stripTags,
  imageUtil: imageUtil,
  Base64: Base64,
  formatLocation: formatLocation,
  isEmpty: isEmpty, //非空判断
  reversalTime: reversalTime, // 时间戳转为分钟数    hour:minute:second
  timestampToTime: timestampToTime, // 时间戳转日期  13位  YYYY-MM-DD
  timestampToTimeN: timestampToTimeN, // 时间戳转日期  10位  YYYY-MM-DD
  timestampFormat: timestampFormat, //时间戳转换为刚刚、N分钟前、今天几点几分、昨天几点几分等表示法
  timestampIM: timestampIM, //IM时间戳转换
  timeMethod: timeMethod, //将时间戳转为时间 YYYY-MM-DD hh:mm
  getAge: getAge, //生日计算年龄
  isUnionid: isUnionid, //判断unionid
  call: call, //一键拨号
  validateIdCard: validateIdCard, //身份证号验证
  alert: alert, //alert方法
  deepClone: deepClone, //数组或对象深拷贝
  getBirthdayFromIdCard: getBirthdayFromIdCard, //身份证号换出生日期
  getSexFromIdCard: getSexFromIdCard, //身份证号换出生日期
  verifyIdCardAnName: verifyIdCardAnName, //验证身份证与姓名是否相符
  getTitle: getTitle, //获取医生title
  debouce: debouce, //防抖动函数
  throttle: throttle, //节流函数
  formatSeconds: formatSeconds, //秒数转换时间
}