'use strict';
var HOST_xinli = 'https://www.xiaodongai.com/xiaodongai/xinli';
// var HOST_xinli = 'https://www.xiaodongai.com/xiaodongai/xinli_ceshi_copy';
var HOST_xinli_lb = 'https://static.xiaodongai.com/';

// const HOST= "https://test-wechat.xiaodongai.com/";
var HOST = 'https://www.xiaodongai.com/xiaodongai/kongtian/';
// var HOST = 'https://www.xiaodongai.com/xiaodongai/ceshi/';//测试库
var HOST_P = "http://static.xiaodongai.com/xiaodongai/";
var HOST_P_K = "http://static.xiaodongai.com/xiaodongai/kongtian/";
//var HOST_yiyuan="https://www.xiaodongai.com/xiaodong_yiyuan/xd_admin/public/index.php/apitest/";//互联网医院测试
var HOST_yiyuan="https://www.xiaodongai.com/xiaodong_yiyuan/xd_admin/public/index.php/api/";//互联网医院正式
var HOST_info = 'https://vivshi.com/xiaodongai/kongtian/'; // 弃用
// get请求方法
function fetchGet(url, callback) {
  var timestamp = (new Date()).valueOf();
  wx.request({
    url: url + '/time_s/' + timestamp,
    header: { 'Content-Type': 'application/json' },
    success(res) {
      callback(null, res.data)
    },
    fail(e) {
      if (e) {
        wx.showToast({
          title: '加载失败，请重新加载',
          icon: 'none',
          duration: 1000
        })
        return;
      }
      callback(e)
    }
  })
}

// post请求方法
function fetchPost(url, data, callback) {
  var timestamp = (new Date()).valueOf();
  wx.request({
    method: 'POST',
    url: url + '/time_s/' + timestamp,
    data: data,
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    success(res) {
     
      callback(null, res.data)
    },
    fail(e) {
      if (e) {
        wx.showToast({
          title: '加载失败，请重新加载',
          icon: 'none',
          duration: 1000
        })
        return;
      }
      callback(e)
    }
  })
}
// post请求方法 无时间戳
function fetchPostN(url, data, callback) {
  wx.request({
    method: 'POST',
    url: url,
    data: data,
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    success(res) {
      callback(null, res.data)
    },
    fail(e) {
      if (e) {
        wx.showToast({
          title: '加载失败，请重新加载',
          icon: 'none',
          duration: 1000
        })
        return;
      }
      callback(e)
    }
  })
}
//非空判断
function isEmpty(obj) {
  if (typeof obj == 'undefined' ||obj == 'undefined' || obj == null || obj == "") {
    return true;
  } 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('用户点击取消')
      }
    }
  });
}
function modal(msg, callback) {
  let that = this;
  wx.showModal({
    title: '警告',
    cancelText: '取消',
    confirmText: '去授权',
    content: msg,
    success: function (res) {
      if (res.confirm) {
        console.log('用户点击确定')

        if (callback) {
          callback('ok')
        }
      } else if (res.cancel) {
        if (callback) {
          callback('ok')
        }
        console.log('用户点击取消')
      }
    }
  })
}

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

function openlocation(lat, lng) {
  wx.openLocation({
    latitude: lat,
    longitude: lng,
    scale: 28
  })
}

function title(title) {
  wx.setNavigationBarTitle({
    title: title
  });
}
// 时间戳转为分钟数
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;
}
var timer;
function getOpenid(c){
  clearTimeout(timer)
  timer = setTimeout(()=>{
    wx.login({
      success: function (res) {
        // wx.setStorageSync("code", res.code)
        if (res.code) {
          var url = HOST + 'applet.php?s=Applet/getopenid';
          var data = {};
          data.code = res.code;
          fetchPost(url, data, (err, res) => {
            wx.setStorageSync('user', res);//存储openid
            c(res)
            // console.log(obj, '002')
          });
        } else {
          c(0)
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function (err) {
        c(0)
        console.log("login失败")
      }
    });
  },300)
  
}
function getLocalTime(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}
//  加载index
function getData(user,c){
  let that = this;
  let url = HOST + 'wechatIteration.php?s=Home/index';
  let data = {};
  data.openid = user.openid;
  data.unionid = user.unionid;
  fetchPost(url, data, (err, res) => {
    if(res){
      var unitid;
      wx.setStorageSync('data', res)
      if (res.unitid == null || res.unitid == 0 || res.unitid == "") {
        unitid = 'false';
        wx.setStorageSync('unitid', unitid);
      } else {
        unitid = res.unitid;
      }
      wx.setStorageSync('unitid', unitid);
      c(res);
    }else{
      c(0)
    }

  });
}
//生日计算年龄
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 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 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;  
}
//身份证号换出生日期
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;  
}
//验证身份证与姓名是否相符
function verifyIdCardAnName(name,idCard,C) {  
  var data={
    idCard:idCard,
    name:name,
    unionid:wx.getStorageSync('data').unionid
  }
  var url=HOST_yiyuan+'Idcard/checkCard';
  this.fetchPost(url,data, (err, res) => {
      C(res.code);
  })
}
module.exports = { 
  HOST_xinli: HOST_xinli,
  HOST: HOST,
  HOST_yiyuan:HOST_yiyuan,
  fetchGet: fetchGet,	//get方法
  fetchPost: fetchPost,	//post方法
  fetchPostN: fetchPostN, // post 无随机数
  alert: alert,		//alert方法
  call: call,		//一键拨号
  openlocation: openlocation,	//导航
  title: title,		//设置页面标题
  reversalTime: reversalTime,
  timestampToTimeN: timestampToTimeN,
  timestampToTime:timestampToTime,
  modal: modal,
  HOST_P: HOST_P,
  HOST_P_K: HOST_P_K,
  HOST_xinli_lb: HOST_xinli_lb,
  HOST_info: HOST_info,
  getOpenid: getOpenid,
  getLocalTime: getLocalTime,
  getData: getData,
  timeMethod: timeMethod,
  isEmpty: isEmpty,
  getAge:getAge,
  validateIdCard: validateIdCard,
  getBirthdayFromIdCard:getBirthdayFromIdCard,
  getSexFromIdCard:getSexFromIdCard,
  verifyIdCardAnName:verifyIdCardAnName,
}
