
import store from '../../store'
const _config = {
	baseUrl: "http://www.lychwl.com.cn"
}
// 提示
const msg = (title, duration = 3000, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
	setTimeout(function() {
		uni.hideToast();
	}, duration)
}
//等待框
function showLoading(title='请稍候..', mask=false){
	// 弹出系统等待对话框
	// #ifdef APP-PLUS
	_loading = plus.nativeUI.showWaiting( title, {
		width: '76px',
		height: '76px',
		size: '12px',
		modal: mask,
		back: 'none', //安卓截获返回键 none:截获不做响应 close:截获后关闭等待框 none:不截获
		loading: {
			type: 'snow'
		}
	});
	setTimeout(()=>{
		hideLoading();
	}, 10000)
	
	return _loading;
	// #endif
	// #ifndef APP-PLUS
	uni.showLoading({
		title,
		mask
	})
	// #endif
}
function inAction(fn, that, timeout = 2000){
	if(that['in' + fn]){
		return true
	}
	that['in' + fn] = true;
	setTimeout(()=>{
		that['in' + fn] = false;
	}, timeout)
	return false;
}
// 返回上一页
const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}


// 上传图片--注按需要对res处理 JSON.parse()
function  uploadImg(formData){
	return new Promise((resolve,reject)=>{
		uni.chooseImage({
			count:1,
			success(chooseImageRes){
				// resolve(chooseImageRes.tempFilePaths[0]);
				const tempFilePaths = chooseImageRes.tempFilePaths[0];
				let token = uni.getStorageSync("token")
				uni.showLoading();
				uni.uploadFile({
					url:_config.consoleBaseUrl+'api/common/upload',
					filePath: tempFilePaths,
					name: 'file',
					formData:formData,
					header: {
						'token':token,
					},
					success:(res)=>{
						resolve(res.data);
					},
					fail:(err)=>{
						msg('上传失败');
						reject();
					},
					complete:()=> {
						uni.hideLoading();
					},
				})
			},
			fail(err){
				// msg('打开相册失败');
				reject(err)
			}
		})
	})
}

// 深拷贝
const deepCopy = (p, c) => {
	var c = c || {};
	for (var i in p) {
		if (typeof p[i] === "object") {
			c[i] = (p[i].constructor === Array) ? [] : {};
			deepCopy(p[i], c[i])
		} else {
			c[i] = p[i]
		}
	}
	return c;
}

function request(url, data, options, method="POST") {
	options = Object.assign({showLoading: false,loadingText: '加载中',loadingMask: false}, options);
	
	const header = {
	 	'Content-Type': 'application/x-www-form-urlencoded'
	};
	const token = uni.getStorageSync('token') || '';
	if(token && typeof token == "string"){
		data={...data,token};
	}
	let params = {
		 url: _config.consoleBaseUrl + url,
		//url,
		data,
		method,
		header,
	}
	return new Promise((resolve, reject) => {
		options.showLoading && showLoading(options.loadingText, options.loadingMask);
		params.complete = (response) => {
			options.showLoading && hideLoading();	
			if (response.statusCode === 200) {
				 if(response.data.code != 1){
					msg(response.data.msg);
					reject();
				}else{
					resolve(response.data);
				}
			}else if(response.statusCode === 401){
				msg("401，开发中。。。")
				reject();
			}else{
				msg('网络繁忙 ' + response.statusCode, 1500, true);
				reject();
			}
		}
		uni.request(params);
	})
}

function get(url, data={}, options={}) {
	return request(url, data, options, 'GET');
}
function post(url, data={}, options={}) {
	return request(url, data, options, 'POST');
}


// 处理时间
const handleStrLength=(num)=> {
	return String(num).length < 2 ? '0' + num : num;
}
const handleDatetime=(date)=> {
	let m = handleStrLength(date.getMonth() + 1);
	let d = handleStrLength(date.getDate());
	let h = handleStrLength(date.getHours());
	let mm = handleStrLength(date.getMinutes());
	let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm;
	return dateStr;
}
const getCurTime=()=> {
	let date = new Date();
	return  handleDatetime(date);
}
const getEndTime=()=> {
	let date = new Date();
	date.setFullYear(date.getFullYear() + 1);
	return handleDatetime(date);
}


function match(str, type, showMsg=true){
	let exp = '';
	
	switch(type){
		case 'mobile':
			if(str === ''){
				showMsg && msg('请填写手机号码');
				return false;
			}
			exp = /(^1[3|4|5|6|7|8|9][0-9]{9}$)/; //手机号
			if(!exp.test(str)){
				showMsg && msg('手机号码格式不正确');
				return false;
			}
			break;
		case 'pwd':
			if(str === ''){
				showMsg && msg('请填写密码');
				return false;
			}
		case 'code':
				if(str === ''){
					showMsg && msg('请填写验证码');
					return false;
				}
				if(!/^[0-9]+$/.test(str)){
					showMsg && msg('验证码不正确');
					return false;
				}
			break;
	}
	return true;
}
///**详情页处理富文本 details仅是变化替换部分a.replace(/<text>(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */
const replaceDetail = (details = '') => {
	//newContent仅是details替换后内容;
  let newContent = details.replace(/<img[^>]*>/gi, function (match, capture) { //去除三标签
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
  return newContent;
}

export default {
	    _config,
		msg,
		prePage,
		get,
		post,
		deepCopy,
		inAction,
		replaceDetail,
		getCurTime,
		getEndTime,
		match,
		uploadImg,
	};