import {getWxConfig} from '@/api/course'
import wx from 'jweixin-module';
// AppToken_JZCourse 九州
// AppToken_JinZCourse 金正
// AppToken_MYCourse 木易华康、易诊通、宏珍\四幅堂
// AppToken_HDTCourse 宏德堂
// AppToken_RTCourse 润天

export const TOKEN_KEY = 'AppToken_MYCourse'; // token 信息
const CONFIG_KEY = 'QXT_MAGMT_CONFIG_KEY'; // 系统配置
const USER_KEY = 'QXT_MAGMT_USER_KEY'; // 账号信息
const SITE_BASE_URL_KEY = 'SITE_BASE_URL_KEY'; // 链接信息
const SIP_ACCOUNT_KEY = 'SIP_ACCOUNT_KEY'; // 链接信息

function userDefaults(key) {
	let ret = '';
	ret = uni.getStorageSync(key);
	if (!ret) {
		ret = '{}';
	}
	let obj = JSON.parse(ret);
	return obj;
}

/**
 * 获取当前登录用户的令牌信息
 * @return {Object} 登录令牌信息
 */
function getUserToken() {
	let usertoken = userDefaults(TOKEN_KEY);
	return usertoken;
};


/**
 * 添加当前登录用户的令牌信息
 * @param {Object} tokenInfo 令牌信息
 */
function setUserToken(tokenInfo) {
	let tokens = getUserToken()
	let newToken = Object.assign(tokens, tokenInfo); //  只有在登陆是才能获取签名、实名状态，刷新token时只会返回token，不能直接得到状态，这里只调整覆盖原来的token
	uni.setStorageSync(TOKEN_KEY, JSON.stringify(newToken));
};


export function parseText(txt,len) {
	if(txt.length>len){
		var text=txt.substr(0,len)+"..."
		return text;
	}
	return txt;
}

export function parseIDCardInfo(idCard) {
  // 正则表达式匹配身份证号格式
  var reg = /^\d{17}[\dXx]$/;
  
  if (reg.test(idCard)) {
    // 提取出生日期
    var birthday = idCard.substring(6, 14);
    var year = birthday.substring(0, 4);
    var month = birthday.substring(4, 6);
    var day = birthday.substring(6, 8);
    
    // 计算年龄
    var currentYear = new Date().getFullYear();
    var age = currentYear - parseInt(year);
    
    // 提取性别
    var genderCode = parseInt(idCard.charAt(16));
    var gender = genderCode % 2 === 0 ? "女" : "男";
    
    return {
      birthday: year + "-" + month + "-" + day,
      age: age,
      gender: gender
    };
  }
  
  return null; // 身份证号格式不正确
}

export function isEmpty(obj) {
	if (obj == "undefined" || obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}


 /**
  * 是否登录
  * @return {Boolean} true 登录 false 未登录
  */
 
 
export function  isLogin() {
	let obj=uni.getStorageSync(TOKEN_KEY);
	return !!obj;
}

 


export function logout() {
	uni.setStorageSync(TOKEN_KEY,null);
}


var toast=function(msg) {
	
    // #ifdef APP-PLUS
	    uni.showToast({title: msg,icon: 'none',duration:2000,position:'bottom'});
	// #endif

	// #ifdef H5
	    uni.showToast({ title: msg,icon: 'none',duration:2000});
	// #endif
	
}

export function getDictLabelName(dicts,dictValue) {
	if(dictValue==null){
		return "";
	}
	var name="";
	dicts.forEach(function(item, index, array) {
		 if(dictValue.toString()==item.dictValue.toString())
		 {
			 name=item.dictLabel
		 }
	});
	return name;
}

export function getStoreDictByName(key,dictValue) {
	if(dictValue==null || dictValue==-1){
		return "请选择";
	}
	var dicts = uni.getStorageSync(key);
	var dict=JSON.parse(dicts);
	var name="";
	dict.forEach(function(item, index, array) {
		 if(dictValue.toString()==item.dictValue.toString()){
			 name=item.dictLabel
		 }
	});
	return name;
}


var getStoreIndexByName= function(key,dictValue) {
	if(dictValue==null || dictValue==-1){
		return [0];
	}
	var dicts = uni.getStorageSync(key);
	var dict=JSON.parse(dicts);
	var defIndexs=[0];
	dict.forEach(function(item, index, array) {
		 if(dictValue.toString()==item.dictValue.toString()){
			 defIndexs=[index];
		 }
	});
	return defIndexs;
}


var getStorageByKey=function(key){
	let storageObj=uni.getStorageSync(key);
	var dataArr=[];
	if(!!storageObj){
		dataArr=JSON.parse(storageObj);  
	}
	return dataArr;
}

var getStorageNamesByKey=function(key){
		let storageObj=uni.getStorageSync(key);
		if(!!storageObj){
			var tempArr=JSON.parse(storageObj);  
			var valueArr=[];
			tempArr.forEach(function(item, index, array) {
				valueArr.push(item.dictLabel);
			});
			return valueArr;  
		}
}


var getDict= function(key) {
	var dicts = uni.getStorageSync('dicts');
	dicts=JSON.parse(dicts);
	var dict=dicts[key]
	return dict;
}

var photosToArr= function(photoUrl) {
	 var photos=[];
	 if(photoUrl!=null&&photoUrl!=''){
		 photos=photoUrl.split(',');
	 }
	 return photos
}

var dateFormat=function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

var getProvider = service => {
  return new Promise((resolve, reject) => {
    // 获取当前环境的服务商
    uni.getProvider({
      service: service || 'oauth',
      success: function (res) {
        // 此处可以排除h5
        if (res.provider) {
          resolve(res.provider[0])
        }
      },
      fail() {
        reject('获取环境服务商失败')
      },
    })
  }).catch(error => {
    console.log('167', error)
  })
}

export function parsePhone(mobile) {
    var str = mobile.substr(0,3)+"****"+mobile.substr(7);
    return str;
}


export function getAge(strBirthday){       
     var returnAge,
    	strBirthdayArr=strBirthday.split("-"),
     	birthYear = strBirthdayArr[0],
     	birthMonth = strBirthdayArr[1],
     	birthDay = strBirthdayArr[2],  
    	d = new Date(),
     	nowYear = d.getFullYear(),
     	nowMonth = d.getMonth() + 1,
     	nowDay = d.getDate();   
     if(nowYear == birthYear){
         returnAge = 0;//同年 则为0周岁
     }
     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;//返回周岁年龄
 }
 
 
 const urlToObj = function(url) {
   let obj = {}
   let str = url.slice(url.indexOf('?') + 1)
   let arr = str.split('&')
   for (let j = arr.length, i = 0; i < j; i++) {
     let arr_temp = arr[i].split('=')
     obj[arr_temp[0]] = arr_temp[1]
   }
   return obj
 }
 
 


/**
 * 判断是否为空对象
 * @param {Object} 时间字符串
 */
var isNullObj=function(obj) {
	let isNull=(JSON.stringify(obj) == "{}");
	return isNull;
}



var arrContainsVal=function(arr,val){
	var isContains=false;
	for (var i = 0; i < arr.length; i++) { 
	    if (arr[i] == val) {
			isContains= true;
			break;
		}
	} 
	return isContains;
}

var arrIndexOf = function(arr,val) { 
      var isContains = this.arrContainsVal(arr,val); 
      if (isContains) { 
           return arr.indexOf(val);
      } else{
		  return -1;
	  }
}


export function navBack() {
	uni.navigateBack({
		animationType: 'pop-out',
		animationDuration: 200
	});
}

export function  navTo(url) {
	uni.navigateTo({
		url: url
	});
}


var loginNavTo=function(url){
	if(isLogin()){
		uni.navigateTo({
			url: url
		});
	}else{
		this.$showLoginPage();
	}
}

var loginCallBack=function(callBack){
	if(isLogin()){
		callBack();
	}else{
		this.$showLoginPage();
	}
}



 /**
  * 获取用户信息
  * 
  */
 export function getUserInfo(){
	let userInfo=uni.getStorageSync('userInfo');
	userInfo=JSON.parse(userInfo);
    return userInfo;
 };

export function parseIdCard(idCard) {
    var str = idCard.substr(0,4)+"****"+idCard.substr(8);
    return str;
}

 /**
  * 随机字符串
  * 
  */
export function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

 /**
  * 初始化sdk配置
  * 
  */
export function initJssdk(callback,url) {
	let param ={
		url: encodeURIComponent(url)
	}
	uni.showLoading({
		  title: '加载中'
	});
	getWxConfig(param).then(res => {
		uni.hideLoading();
		if (res.code == 200) {
			wx.config({
				debug: false,
				appId: res.data.appId,
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: ['requestMerchantTransfer']
			});
			if(callback) {
				callback(res.data)
			}
		}
	}).catch(err=>{
		uni.hideLoading();
	})
}