import {getBaseURL} from '@/request/http.js'

export function uploadImg(path)
{
	return new Promise ((resolve,reject)=>
	{
		let token = uni.getStorageSync('token')
		uni.uploadFile({
			url: getBaseURL()+'/file-upload',
			filePath: path,
			name: 'file',
			header:{
				'Authorization':token?('Bearer '+token):''
			},
			success: (res) => {
				console.log(res)
				var result = JSON.parse(res.data);//返回的结果，可能不同项目结果不一样
				resolve(result.url)
			},
			fail: (error) => {
				console.log('上传失败'+error.errMsg)
				reject()
			}
		});
	})
}

export async function uploadImgs(paths, success)
{
	for (let path of paths) {
		try {
			const uploadData = await uploadImg(path)
			success(uploadData)
		} catch (e) {
			//TODO handle the exception
			console.log(e)
			uni.showToast({
				title: e || '上传失败',
				icon: 'error'
			})
			break
		}
	}
}

export function accDiv(arg1,arg2){   
	 var t1=0,t2=0,r1,r2;   
	 try{t1=arg1.toString().split(".")[1].length}catch(e){}   
	 try{t2=arg2.toString().split(".")[1].length}catch(e){}    
	 r1=Number(arg1.toString().replace(".",""))   
	 r2=Number(arg2.toString().replace(".",""))  
	 return accMul((r1/r2),Math.pow(10,t2-t1));     
 }   
//乘法  
export function accMul(arg1,arg2)   
{   
	var m=0,s1=arg1.toString(),s2=arg2.toString();   
	try{m+=s1.split(".")[1].length}catch(e){}   
	try{m+=s2.split(".")[1].length}catch(e){}   
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)   
}   

//加法   
export function accAdd(arg1,arg2){   
	var r1,r2,m;   
	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}   
	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}   
	m=Math.pow(10,Math.max(r1,r2))   
	return (arg1*m+arg2*m)/m   
}   

//减法   
export function accSub(arg1,arg2){  
    var r1,r2,m,n;  
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  
    m=Math.pow(10,Math.max(r1,r2));  
    n=(r1>=r2)?r1:r2;  
    return ((arg1*m-arg2*m)/m).toFixed(n);  
}  

function isEmptyStr(str)
{
	return (!str || 0 === str.length);
}
function isNotaNumber(str)
{
	// return isNaN(str);
	return true
}

export function maskPhoneNumber(phoneNumber) {
  return phoneNumber.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
}


function getCurrentTimeStr()
{
	let date = new Date()
	let month = date.getMonth()+1
	let day = date.getDate()
	let hour = date.getHours()
	let minute = date.getMinutes()
	
	return month+'月'+day+'日'+hour+':'+(minute<10?('0'+minute):minute)
}

function getChineseTimeStrBySecond(s)
{
	if (s<0) {
		s = 0-s
	}
	let day = parseInt(s/(24*60*60))
	let hour = parseInt(s%(24*60*60)/(60*60))
	let minute = parseInt(s/60)%60
	let second = s%60
	
	return (day>0?(day+'天'):'')+(hour>0?(hour+'小时'):'')+minute+'分'+second+'秒'
}

function getTimeStrBySecond(s)
{
	if (s<0) {
		s = 0-s
	}
	let hour = parseInt(s/(60*60))
	let minute = parseInt(s/60)%60
	let second = s%60
	
	return (hour<10?('0'+hour):hour)+':'+(minute<10?('0'+minute):minute)+':'+(second<10?('0'+second):second)
}

function getChineseTimeStrByHour(h)
{
	if (!h) return
	if (h<0) {
		h = 0-h
	}
	let day = parseInt(h/24)
	let hour = parseInt(h%24)
	console.log(day,hour)
	return (day>0?(day+'天'):'')+(hour>0?(hour+'小时'):'')
}

/**
 * 获取涨幅字符串
 * @param {Object} r
 */
export function getRateStr(r)
{
	if (!r) return
	r = String(r)
	if(r.indexOf('-')>-1)
	{
		r = r.substr(1,r.length-1)
		return parseFloat(r).toFixed(2)
	}else
	{
		if(parseFloat(r)==0)
		{
			return 0.00
		}else
			return parseFloat(r).toFixed(2)
	}
}

/**
 * 获取涨跌幅字符串
 * @param {Object} r
 */
export function getChgRateStr(r)
{
	if (!r) return
	r = String(r)
	if(r.indexOf('-')>-1)
	{
		r = r.substr(1,r.length-1)
		return '-'+parseFloat(r).toFixed(2)
	}else
	{
		if(parseFloat(r)==0)
		{
			return 0.00
		}else
			return '+'+parseFloat(r).toFixed(2)
	}
}

/**
 * 获取涨幅字符串是涨还是跌 true为跌false为涨
 * @param {Object} r
 */
export function getRateUpOrDown(r)
{
	if (!r) return
	return String(r).indexOf('-')>-1
}

/**
 * 获取本地时间
 * @param {Object} time
 */
export function getLocaleTime(time)
{
	if(time.indexOf('T')==-1)
	{
		time = time.replace(/-/g,'/')
	}
	let date = new Date(time)
	let year = date.getFullYear()
	let month = date.getMonth()+1
	let day = date.getDate()
	let hour = date.getHours()
	let minute = date.getMinutes()
	
	return year+'-'+(month<10?('0'+month):month)+'-'+(day<10?('0'+day):day)+' '+(hour<10?('0'+hour):hour)+':'+(minute<10?('0'+minute):minute)
}

/**
 * 获取本地时分
 * @param {Object} time
 */
export function getLocaleHourMinute(time)
{
	if(time.indexOf('T')==-1)
	{
		time = time.replace(/-/g,'/')
	}
	let date = new Date(time)
	let hour = date.getHours()
	let minute = date.getMinutes()
	
	return (hour<10?('0'+hour):hour)+':'+(minute<10?('0'+minute):minute)
}

/**
 * 获取本地月日时分
 * @param {Object} time
 */
export function getLocaleMonthDayHourMinte(time)
{
	if(time.indexOf('T')==-1)
	{
		time = time.replace(/-/g,'/')
	}
	let date = new Date(time)
	let month = date.getMonth()+1
	let day = date.getDate()
	let hour = date.getHours()
	let minute = date.getMinutes()
	
	return (month<10?('0'+month):month)+'-'+(day<10?('0'+day):day)+' '+(hour<10?('0'+hour):hour)+':'+(minute<10?('0'+minute):minute)
}

/**
 * 获取本地日期
 * @param {Object} time
 */
export function getLocalDate(time)
{
	if(time.indexOf('T')==-1)
	{
		time = time.replace(/-/g,'/')
	}
	let date = new Date(time)
	let year = date.getFullYear()
	let month = date.getMonth()+1
	let day = date.getDate()
	
	return year+'-'+(month<10?('0'+month):month)+'-'+(day<10?('0'+day):day)
}

/**
 * 替换
 * @param {Object} time
 */
export function replaceAnswerLabel(text) 
{
	return text.replace('<answer>','').replace('</answer>','')
}

/**
 * 身份证号校验
 */
export function checkIdCard (cardNum)
{
    cardNum = cardNum.replace(/(^\s*)|(\s*$)/g,"")
    if (cardNum.length==15) {
        return isValidateBirthBy15IdCard(cardNum)
    }else if(cardNum.length==18)
    {
        var idCard = cardNum.split("")
        if (isValidateBirthBy18IdCard(cardNum)&&isValidateCodeBy18IdCard(idCard)) {
            return true
        }else 
            return false
    }else 
        return false
}
function isValidateCodeBy18IdCard(cardNum)
{
    var wi = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1]    //加权因子
    var valideCode = [1,0,10,9,8,7,6,5,4,3,2]
    var sum = 0
    if (cardNum[17].toLowerCase() == 'x') {
        cardNum[17] = 10    //将最后位的x替换成10
    }
    for (let i = 0; i < 17; i++) {
        sum+= wi[i] * cardNum[i]
    }
    var valCodePosition = sum%11
    if (cardNum[17] == valideCode[valCodePosition]) {
        return true
    }else
        return false
}
/**
 * 验证18位身份证号中的生日是否为有效生日
 * @param {*} cardNum 
 */
function isValidateBirthBy18IdCard (cardNum)
{
    var year = cardNum.substring(6,10)
    var month = cardNum.substring(10,12)
    var day = cardNum.substring(12,14)
    var tempDate = new Date(year,parseFloat(month)-1,parseFloat(day))
    //这里用getFullYear获取年份
    if (tempDate.getFullYear()!=parseFloat(year)||
        tempDate.getMonth()!=(parseFloat(month)-1)||
        tempDate.getDate()!=parseFloat(day)) {
        return false
    }else 
        return true
}

/**
 * 验证15位身份证号中的生日是否为有效生日
 * @param {*} cardNum 
 */
function isValidateBirthBy15IdCard (cardNum)
{
    var year = cardNum.substring(6,8)
    var month = cardNum.substring(8,10)
    var day = cardNum.substring(10,12)
    var tempDate = new Date(year,parseFloat(month)-1,parseFloat(day))
    //这里用getFullYear获取年份
    if (tempDate.getFullYear()!=parseFloat(year)||
        tempDate.getMonth()!=(parseFloat(month)-1)||
        tempDate.getDate()!=parseFloat(day)) {
        return false
    }else 
        return true
}
