const core = require("./core.js"),
	config = require("../config/config.js")

/** 处理邀请好友赠送积分入口 */
function initFriendTask() {
	let optionL = uni.getStorageSync("appLaunchOptions");
	if (typeof optionL.query == "undefined" || !optionL.query) {
		return;
	}
	let option = optionL.query;

	if (typeof option.scene != "undefined" && option.scene) {
		option = option.scene;
	}
	if (typeof option == "string") {
		option = decodeURIComponent(option);
		option = core.str2Obj(option);
	}
	/** 推荐新好友机制 */
	if (typeof option.mid != "undefined" && option.mid) {
		let tempMidData = getApp().globalData.getCache("usermid");
		if (typeof tempMidData != "undefined" && tempMidData) {
			tempMidData["mid"] = option.mid;
		} else {
			tempMidData = {
				mid: option.mid,
				merchid: "",
			};
		}
		getApp().globalData.setCache("usermid", tempMidData)
	}
	/** end推荐新好友机制 */
}
// H5 login
function getH5Login(openid_wx, mobile) {
	return new Promise(function(success, fail) {
		getApp().globalData.request({
			s: 'Member_LoginH5.getUserLogin',
			openid_wx: openid_wx,
			mobile: mobile,
		}).then(synLoginRes => {
			// 登录成功,保存用户userInfo
			if (synLoginRes.data.data) {
				success(synLoginRes.data.data);
			} else {
				fail(synLoginRes);
			}
		});
	});
}

function loadJS(url, callback) {
	var script = document.createElement('script'),
		fn = callback || function() {};
	script.type = 'text/javascript';
	//IE
	if (script.readyState) {
		script.onreadystatechange = function() {
			if (script.readyState == 'loaded' || script.readyState == 'complete') {
				script.onreadystatechange = null;
				fn();
			}
		};
	} else {
		//其他浏览器
		script.onload = function() {
			fn();
		};
	}
	script.src = url;
	document.getElementsByTagName('head')[0].appendChild(script);
}

function formatTime(e) {
	var n = e.getFullYear(),
		o = e.getMonth() + 1,
		r = e.getDate(),
		u = e.getHours(),
		i = e.getMinutes(),
		g = e.getSeconds();
	return [n, o, r].map(t).join("/") + " " + [u, i, g].map(t).join(":");
}

function getFourCate() {
	return new Promise(success => {
		let setting = uni.getStorageSync('setting');
		// 获取首页四个分类名字图片
		getApp().globalData.request({
				s: "Shop_Credit_CreditShop.getFourCate"
			})
			.then(res => {
				let category = res.data.data;
				setting['fourCateList'] = category;
				uni.setStorageSync('setting', setting);
			});
	});
}

function appApiLog(param) {
	let data = {
		str: JSON.stringify(param)
	}
	request({
		s: "Sys_Index.applog",
		data: data,
	})
}

/**
 * 发起请求
 * @function 公共请求方式统一使用 uni.showLoading,由于是异步请求,hideLoading会全局关闭过往请求,为了防止被交叉关闭loading,特殊业务请用showToast
 */
function request(param, methods = "post", payComHideLoading = false) {
	return new Promise((successReturn) => {
		if (!param) {
			return
		}
		let userInfo = uni.getStorageSync("userInfo")
		if (typeof param["openid"] == "undefined" && !param["openid"]) {
			param["openid"] = userInfo.openid
		}
		param["userid"] = userInfo.id
		let midData = getApp().globalData.getCache("usermid")
		if (midData.mid) {
			param["mid"] = midData.mid
		}
		uni.request({
			method: methods ? methods : "post",
			url: "https://" + config.api_hostname + config.api_dir + param["s"],
			data: param,
			timeout: getApp().globalData.config.timeout,
			success: function(res) {
				if (res && res.data && res.data.ret && res.data.ret == 200) {
					successReturn(res)
				} else {
					successReturn(false)
					errorDo(param, res)
				}
			},
			fail: function(error) {
				successReturn(false)
				errorDo(param, error)
			},
			complete: function() {
				if (payComHideLoading) {
					uni.hideLoading()
				}
			},
		});
	});

	function errorDo(param, error) {
		let data = {};
		data["param"] = param;
		data["error"] = error;
		appApiLog(data)
		let errMsg = "网络开小差啦! 是否重试?"
		if (error.data.msg) {
			errMsg = error.data.msg
		}
		uni.showModal({
			title: "提示",
			content: errMsg,
			confirmText: "重试",
			success: function(res) {
				if (res.confirm) {
					request(param, methods)
				}
			},
		});
	}
}

function setStorage(storage, key, value) {
	return new Promise(function(success) {
		let old = uni.getStorageSync(storage);
		if (typeof(old) == 'undefined' || old === '') {
			old = {};
		}
		old[key] = value;
		uni.setStorage({
			key: storage,
			data: old,
			success: function() {
				success(true);
			},
		});
	});
}

// H5 获取页面地址
function getQueryVariable(variable, url) {
	var query = '';
	if (url) {
		query = url;
	} else {
		query = window.location.href.split('?')[1];
	}
	if (!query) {
		return false;
	}
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return (false);
}

/**
 * @param forceUpdate 强制重新uni.login登录更新缓存
 * @returns 
 */
function loginByCode(forceUpdate = false, payComHideLoading = false) {
	return new Promise(function(success) {
		//#ifdef MP-WEIXIN 	
		// 如果是朋友圈分享
		if (wx.getLaunchOptionsSync().scene == 1154) {
			success({
				error: 0,
				openid: 'ovJcw5ao__ysZvNn5tnzKpFzGjoM',
				isclose: 0
			});
			return;
		}
		//#endif 
		let userInfo = uni.getStorageSync('userInfo');
		if (!forceUpdate && userInfo && typeof(userInfo.openid) != 'undefined' && userInfo.openid) {
			success(userInfo)
			// 已经调用过uni.login 直接获取用户信息
			getApp().globalData.request({
				s: 'Member_Index.getUserInfo',
				usermid: getApp().globalData.getCache("usermid") ? getApp().globalData
					.getCache("usermid")
					.mid : '',
				openid: userInfo.openid
			}, null, payComHideLoading).then(login => {
				if (login.data.data && login.data.data.openid) {
					uni.setStorage({
						key: 'userInfo',
						data: login.data.data,
						success() {
							all_need_openid_fun()
							success(login.data.data)
							getUpWxUid()
							return
						}
					})
				} else {
					loginRefreshUserInfo()
				}
			})
		} else {
			loginRefreshUserInfo()
		}

		function loginRefreshUserInfo() {
			uni.showLoading({
				title: "登录中123..."
			})
			// #ifdef MP-WEIXIN||MP-ALIPAY
			uni.login({
				success: function(login) {
					uni.hideLoading()
					//#ifdef MP-WEIXIN 	
					getApp().globalData.request({
						s: 'Member_LoginWx.getUserLogin',
						platform: 'MP-WEIXIN',
						usermid: getApp().globalData.getCache("usermid") ? getApp()
							.globalData
							.getCache("usermid")
							.mid : '',
						code: login.code
					}).then(login => {
						if (login.data.data && login.data.data.openid) {
							uni.setStorage({
								key: 'userInfo',
								data: login.data.data,
								success() {
									all_need_openid_fun();
									success(login.data.data)
									return
								}
							})
						}
					})
					//#endif 

					//#ifdef MP-ALIPAY
					getApp().globalData.request({
						s: 'Member_LoginAlipay.getUserLogin',
						platform: 'MP-ALIPAY',
						usermid: getApp().globalData.getCache("usermid") ? getApp()
							.globalData
							.getCache("usermid")
							.mid : '',
						code: login.code
					}).then(synLoginRes => {
						// 登录成功,保存用户userInfo
						if (synLoginRes.data.data) {
							uni.setStorage({
								key: 'userInfo',
								data: synLoginRes.data.data,
								success: function() {
									all_need_openid_fun()
									success(synLoginRes.data.data)
									return
								}
							})
						}
					})
					//#endif
				}
			})
			// #endif
			//#ifdef H5
			let h5userAgent = window.navigator.userAgent.toLowerCase()
			let loginAlipayByH5 = getApp().globalData.util.getQueryVariable('auth_code')
			if (h5userAgent.indexOf("micromessenger") > -1) { //微信公众号

			} else if (h5userAgent.indexOf("alipayclient") > -1 && loginAlipayByH5) { //支付宝生活号				
				getApp().globalData.request({
					s: 'Member_LoginAlipay.getUserLogin',
					h5login: "yes",
					platform: 'MP-ALIPAY',
					code: loginAlipayByH5
				}).then(synLoginRes => {
					uni.hideLoading()
					// 登录成功,保存用户userInfo
					if (synLoginRes.data.data) {
						uni.setStorage({
							key: 'userInfo',
							data: synLoginRes.data.data,
							success: function() {
								all_need_openid_fun()
								success(synLoginRes.data.data)
								return
							}
						})
					}
				})
			}
			// #endif
		}

		function all_need_openid_fun() {
			setTimeout(function() {
				initFriendTask();
			}, 300);
		}
	});
}

/** 微信获取/更新unionid */
function getUpWxUid() {
	let userLoginRes = uni.getStorageSync('userInfo')
	//#ifdef MP-WEIXIN 	
	// 如果没有微信uid,获取更新
	if (typeof userLoginRes.unionid == "undefined" || !userLoginRes.unionid) {
		uni.login({
			success: function(login) {
				getApp().globalData.request({
					s: 'Member_LoginWx.getUnionid',
					code: login.code
				}).then(res => {
					if (res.data.data && res.data.data.unionid) {
						userLoginRes = uni.getStorageSync('userInfo')
						userLoginRes["unionid"] = res.data.data.unionid
						uni.setStorageSync("userInfo", userLoginRes)
					}
				})
			}
		})
	}
	//#endif 
}

/**
 * 数字转整数 如 100000 转为10万
 * @param {需要转化的数} num 
 * @param {需要保留的小数位数} point 
 */
function tranNumber(num, point = 2) {
	if (num < 1) {
		return parseFloat(num).toFixed(2);
	}
	let numStr = parseInt(num);
	numStr = numStr + '';
	// 十万以内直接返回 
	if (numStr.length < 6) {
		return numStr;
	}
	//大于8位数是亿
	else if (numStr.length > 8) {
		let decimal = numStr.substring(numStr.length - 8, numStr.length - 8 + point);
		return parseFloat(parseInt(num / 100000000) + '.' + decimal) + '亿';
	}
	//大于6位数是十万 (以10W分割 10W以下全部显示)
	else if (numStr.length > 5) {
		let decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point)
		return parseFloat(parseInt(num / 10000) + '.' + decimal) + '万';
	}
}
//获取当前环境
function getCurrentSys() {
	return new Promise(function(success) {
		let current_platform = '';
		//#ifdef APP-PLUS
		current_platform = "APP-PLUS";
		//#endif 
		//#ifdef H5
		current_platform = "H5";
		//#endif 
		//#ifdef MP-WEIXIN
		current_platform = "MP-WEIXIN";
		//#endif 
		//#ifdef MP-ALIPAY
		current_platform = "MP-ALIPAY";
		//#endif 
		//#ifdef APP-BAIDU
		current_platform = "APP-BAIDU";
		//#endif 
		//#ifdef APP-TOUTIAO
		current_platform = "APP-TOUTIAO";
		//#endif 
		//#ifdef APP-QQ
		current_platform = "APP-QQ";
		//#endif 
		setStorage('setting', 'current_platform', current_platform).then(suc => {
			success(current_platform);
		});
	});
}


// 设置分销商上级
function setUpCommision(mid) {
	console.log(mid)
	// 如果有分销
	if (mid) {
		// 设置agentid , 分销上级
		getApp().globalData.request({
			s: 'Member_Member.setUpAgentID',
			mid: mid,
			userid: uni.getStorageSync('userInfo').id
		}).then(res => {
			console.log("设置分销商上级", res)
		});
	}
}


// 保留两位小数,向下取整
function numberFloor(num) {
	if (num == 0) {
		return 0
	}
	if (num < 0) {
		return Number(`-${numberFloor(Math.abs(num))}`)
	}
	if (!(/(^[1-9]\d*$)/.test(num))) { // 先判断是否为整数
		return Number(num.toString().match(/^\d+(?:\.\d{0,2})?/))
	}
	return num
}

// 保留两位小数 向上取整
function numberCeil(num, fix) {
	if (num == 0) {
		return 0
	}
	// num为原数字，fix是保留的小数位数
	let result = '0'
	if (Number(num) && fix > 0) { // 简单的做个判断
		fix = +fix || 2
		num = num + ''
		if (/e/.test(num)) { // 如果是包含e字符的数字直接返回
			result = num
		} else if (!/\./.test(num)) { // 如果没有小数点
			result = num + `.${Array(fix + 1).join('0')}`
		} else { // 如果有小数点
			num = num + `${Array(fix + 1).join('0')}`
			let reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
			let floorStr = reg.exec(num)[0]
			if (+floorStr >= +num) {
				result = floorStr
			} else {
				let floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
				let point = /\./.test(floorNumber + '') ? '' : '.'
				let floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
				result = reg.exec(floorStr2)[0]
			}
		}
	}
	return result
}

function orc(type, fileUrl) {
	if (!fileUrl || !type) {
		return
	}
	uni.showToast({
		duration: 1000 * 15,
		title: '识别中',
		icon: "loading"
	})
	return new Promise(success => {
		request({
			s: "App.Tools_OcrDo.Main",
			fileUrl: fileUrl,
			type: type
		}).then(res => {
			uni.hideToast()
			success(res)
		})
	})
}

// 获取H5下 是什么平台
function getH5Platform() {
	// #ifdef H5
	let h5userAgent = window.navigator.userAgent.toLowerCase()
	if (h5userAgent.indexOf("micromessenger") > -1) { //微信公众号
		return "H5-WEIXIN"
	} else if (h5userAgent.indexOf("alipayclient") > -1) { //支付宝生活号	
		return "H5-ALIPAY";	
	}
	// #endif
	return "OTHER"
}

function getLocalFilePath(path) {
    if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
        return path
    }
    if (path.indexOf('file://') === 0) {
        return path
    }
    if (path.indexOf('/storage/emulated/0/') === 0) {
        return path
    }
    if (path.indexOf('/') === 0) {
        var localFilePath = plus.io.convertAbsoluteFileSystem(path)
        if (localFilePath !== path) {
            return localFilePath
        } else {
            path = path.substr(1)
        }
    }
    return '_www/' + path
}
// 图片转base64
function pathToBase64(path) {
    return new Promise(function(resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            if (typeof FileReader === 'function') {
                var xhr = new XMLHttpRequest()
                xhr.open('GET', path, true)
                xhr.responseType = 'blob'
                xhr.onload = function() {
                    if (this.status === 200) {
                        let fileReader = new FileReader()
                        fileReader.onload = function(e) {
                            resolve(e.target.result)
                        }
                        fileReader.onerror = reject
                        fileReader.readAsDataURL(this.response)
                    }
                }
                xhr.onerror = reject
                xhr.send()
                return
            }
            var canvas = document.createElement('canvas')
            var c2x = canvas.getContext('2d')
            var img = new Image
            img.onload = function() {
                canvas.width = img.width
                canvas.height = img.height
                c2x.drawImage(img, 0, 0)
                resolve(canvas.toDataURL())
                canvas.height = canvas.width = 0
            }
            img.onerror = reject
            img.src = path
            return
        }
        if (typeof plus === 'object') {
            plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
                entry.file(function(file) {
                    var fileReader = new plus.io.FileReader()
                    fileReader.onload = function(data) {
                        resolve(data.target.result)
                    }
                    fileReader.onerror = function(error) {
                        reject(error)
                    }
                    fileReader.readAsDataURL(file)
                }, function(error) {
                    reject(error)
                })
            }, function(error) {
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            wx.getFileSystemManager().readFile({
                filePath: path,
                encoding: 'base64',
                success: function(res) {
                    resolve('data:image/png;base64,' + res.data)
                },
                fail: function(error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}
// base64转图片
function base64ToPath(base64, extName) {
    return new Promise(function(resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            base64 = base64.split(',')
            var type = base64[0].match(/:(.*?);/)[1]
            var str = atob(base64[1])
            var n = str.length
            var array = new Uint8Array(n)
            while (n--) {
                array[n] = str.charCodeAt(n)
            }
            return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
        }
		var fileName;
		if (!extName) {
			extName = base64.match(/data\:\S+\/(\S+);/)
			if (extName) {
			    extName = extName[1]
			} else {
			    reject(new Error('base64 error'))
			}
			fileName = Date.now() + '.' + extName;
		} else {
			fileName = Date.now() + extName;
		}
        if (typeof plus === 'object') {
            var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
            bitmap.loadBase64Data(base64, function() {
                var filePath = '_doc/uniapp_temp/' + fileName
                bitmap.save(filePath, {}, function() {
                    bitmap.clear()
                    resolve(filePath)
                }, function(error) {
                    bitmap.clear()
                    reject(error)
                })
            }, function(error) {
                bitmap.clear()
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            var filePath = wx.env.USER_DATA_PATH + '/' + fileName
            wx.getFileSystemManager().writeFile({
                filePath: filePath,
                data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
                encoding: 'base64',
                success: function() {
                    resolve(filePath)
                },
                fail: function(error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}

module.exports = {
	getH5Platform:getH5Platform,
	initFriendTask: initFriendTask,
	getH5Login: getH5Login,
	// 根据手机号合并账号
	mergeAccount: function(mobile) {
		// 如果用户手机号不为空,尝试合并账号
		if (!mobile) {
			return;
		}
		uni.showLoading({
			title: '合并账号中'
		})
		getApp().globalData.request({
			s: 'Member_MergeAccount.phone',
			mobile: mobile
		}).then(synLoginRes => {
			uni.hideLoading()
			// 登录成功,保存用户userInfo
			if (synLoginRes.data.data) {
				uni.showModal({
					title: '提示',
					content: '合并其他平台账号成功!是否返回上一页面?',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				});
			} else {
				uni.showModal({
					title: '提示',
					content: '网络异常,编号1623124890'
				});
			}
		});
	},
	loadJS: loadJS,
	orc: orc,
	formatTime: formatTime,
	getFourCate: getFourCate,
	numberFloor: numberFloor,
	numberCeil: numberCeil,
	appApiLog: appApiLog,
	request: request,
	setStorage: setStorage,
	getQueryVariable: getQueryVariable,
	loginByCode: loginByCode,
	tranNumber: tranNumber,
	getCurrentSys: getCurrentSys,
	setUpCommision: setUpCommision
}
