// 公共函数

import GoEasy from "./lib/goeasy-2.2.4.min.js";
import IMService from "./lib/imservice"
import commonData from './commonData.js'
/*线上使用*/
// 静态图片路径
const serverUrl = 'https://api.kuailaiyou.top/prjcenter/prjKLY/fileroot/images/front/';
// 请求URL路径
const serverUrlReq = 'https://api.kuailaiyou.top/';
//const serverUrlReq = 'https://zpwebapi.kaidekuai.com/';  
// 请求webviewURL路径
const webviewServerUrlReq = 'https://admin.kuailaiyou.top/';


// 静态图片路径
//const serverUrl = 'https://app.tjzhxx.cn:4100/prjcenter/prjKLY/fileroot/images/front/';
// 请求URL路径
//const serverUrlReq = 'https://app.tjzhxx.cn:4100/';
// 请求webviewURL路径
//const webviewServerUrlReq = 'https://app.tjzhxx.cn:4100/';



/*本地测试*/

// 静态图片路径
//const serverUrl = 'http://api.bizdbKLY.com/prjcenter/prjKLY/fileroot/images/front/';
// 请求URL路径
//const serverUrlReq = 'http://api.bizdbKLY.com/';
// 请求webviewURL路径
//const webviewServerUrlReq = 'http://admin.bizdbKLY.com/';


// request数据
const requestUrl = (url, data, callback, auto_change_params = true, Trader2 = false) => {
	// 改造URL
	let url_new = Trader2 ? url : (commonData.sys_role == 1 ? url.replace('Worker', 'Trader') : url.replace(
		'Trader', 'Worker'))
	console.log('原请求路径：'+url+' 改造后请求路径：'+url_new);
	let data_new = {
		...data,
		...commonData.data_token,
		FOREND_TOKEN: uni.getStorageSync('FOREND_TOKEN'),
		phone: data.phone ? data.phone : uni.getStorageSync('PHONE'),
		// FOREND_TOKEN: '0_16415187935b9011bc8aa3ce44cb0cf40dac3d48b4', //用户
		// FOREND_TOKEN: '0_1641527485b098792a509f99b8c991030644125b2b', //商户
		// phone: '17640181459',
	}
	// 改造参数
	if (auto_change_params) {
		if (data_new.bizCatalog) {
			data_new.bizCatalog = commonData.sys_role == 1 ? data_new.bizCatalog.replace('Worker', 'Trader') :
				data_new
				.bizCatalog.replace('Trader', 'Worker')
		}
		if (data_new.handleMode) {
			data_new.handleMode = commonData.sys_role == 1 ? data_new.handleMode.replace('Worker', 'Trader') :
				data_new
				.handleMode.replace('Trader', 'Worker')
		}
	}
	const requestTask = uni.request({
		url: serverUrlReq + 'ajaxEntryCenter.php?WsAjaxPrj=KLY' + url_new,
		method: 'post',
		header: {
			'content-type': 'application/json'
		},
		data: {
			...data_new,
		},
		success: (res) => {
			// 异常处理
			if (res.data.ErrMsg) {
				uni.hideLoading();
				// res.data.ErrMsg为字符串时做一般处理
				if (typeof(res.data.ErrMsg) == 'string') {
					// FOREND_TOKEN异常处理
					if (res.data.ErrMsg.indexOf('FOREND_TOKEN') != -1 || res.data.ErrMsg.indexOf(
							'phone') != -1) {
						uni.showModal({
							title: '当前未登录',
							confirmText: '去登陆',
							cancelText: '游客登录',
							showCancel: commonData.sys_role == 1 ? false : true,
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/login/index?need_back=1'
									})
								} else {
									// 设定游客模式
									uni.setStorageSync('IS_TOURIST', '1')
								}
								callback({
									status: false,
									data: '未登录',
								})
							}
						})
						return
					}
					// 其他异常处理
					uni.showModal({
						title: '操作失败',
						content: JSON.stringify(res.data.ErrMsg),
						showCancel: false,
						success: function(res2) {
							callback({
								status: false,
							})
						}
					});
				} else {
					// res.data.ErrMsg为非字符串时做特殊回调处理
					callback({
						status: false,
						data: res.data
					});
				}
			} else {
				// 非异常处理
				callback({
					status: true,
					data: res.data
				});
			}
		},
		fail: result => {
			uni.hideLoading();
			uni.showModal({
				// title: '接口调用网路错误',
				content: JSON.stringify(result.errMsg),
				showCancel: false,
				success: function(res) {
					callback({
						status: false
					})
				}
			});
		}
	});
}

// 获取位置信息
const getPositionLocal = callback => {
	uni.getLocation({
		type: 'wgs84',
		success: res => {
			// console.log('位置信息')
			// console.log(res)
			let latitude = res.latitude;
			let longitude = res.longitude;
			// callback({
			// 	status: true,
			// 	city: '天津市',
			// 	latitude,
			// 	longitude,
			// })
			// return
			requestUrl('&WsAjaxBiz=Public&WsAjaxAction=entityDataHandle', {
				bizCatalog: 'LbsEntity',
				handleMode: 'fetchAddressByLocation',
				lat: latitude,
				lng: longitude,
			}, res => {
				// console.log('根据经纬度返回城市名称')
				// console.log(res)
				if (res.status) {
					callback({
						status: true,
						city: res.data.Result.city,
						latitude,
						longitude,
					})
				} else {
					// uni.showModal({
					// 	title: '获取位置失败',
					// 	content: JSON.stringify(res),
					// 	showCancel: false
					// })
					callback({
						status: false,
					})
				}
			})
		},
		fail: e => {
			if (e.errMsg.indexOf('频繁调用') == -1) {
				uni.showModal({
					title: '获取位置信息失败',
					content: JSON.stringify(e),
					showCancel: false
				})
			}
			// console.log('获取位置信息失败')
			// console.log(e)
			callback({
				status: false,
			})
		},
		complete: () => {
			uni.hideLoading()
		}
	});
}

// 上传图片/视频到阿里云OSS
const uploadFileApiOSS = (callback, fileType = 'image', allow_album = true) => {
	if (fileType == 'image') {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: allow_album ? ['album', 'camera'] : ['camera'], //从相册选择
			success: res => {
				success_fun(res.tempFilePaths[0], callback)
			},
			fail: res => {
				fail_fun(res, callback)
			}
		});
	} else {
		uni.chooseVideo({
			count: 1,
			sourceType: ['camera', 'album'],
			success: res => {
				success_fun(res.tempFilePath, callback)
			},
			fail: res => {
				fail_fun(res, callback)
			}
		});
	}
	// 成功回调
	function success_fun(filePath, callback) {
		uni.showLoading({
			title: '上传中...',
			mask: true
		})
		let tiemr = new Date();
		let address = tiemr.getFullYear() + '' + (tiemr.getMonth() + 1) + '' + tiemr.getDate();
		address = 'zskp/userHead/' + address + '/';
		let str = filePath.substr(filePath.lastIndexOf('.'));
		let nameStr = address + tiemr.getTime() + str;
		let ossUrl = 'https://goeasy-kuailaiyou.oss-cn-beijing.aliyuncs.com/';
		uni.uploadFile({
			url: ossUrl,
			filePath,
			fileType,
			name: 'file',
			formData: {
				name: nameStr,
				key: nameStr,
				policy: 'eyJleHBpcmF0aW9uIjoiMjA1MC0wMS0wMVQxMjowMDowMC4wMDBaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==', // 输入你获取的的policy
				OSSAccessKeyId: 'LTAI5tSQRXPMmcJbE3TGDPCr', // 输入你的AccessKeyId
				success_action_status: '200', // 让服务端返回200,不然，默认会返回204
				signature: 'sjxOXt7eILxUdyE/0idSJaCGrc8=' // 输入你获取的的signature
			},
			success: res => {
				uni.hideLoading();
				if (res.statusCode == '200') {
					callback({
						status: true,
						data: ossUrl + nameStr
					});
				} else {
					uni.showModal({
						title: 'OSS文件上传失败',
						content: JSON.stringify(res),
						showCancel: false,
						success: function(res) {
							callback({
								status: false,
							})
						}
					});
				}
			}
		});
	}
	// 失败回调
	function fail_fun(res, callback) {
		// console.log(res.errMsg.indexOf('cancel'))
		if (res.errMsg.indexOf('cancel') == -1) {
			uni.showModal({
				title: '文件选择失败',
				content: JSON.stringify(res),
				showCancel: false,
				success: function(res) {
					callback({
						status: false,
					})
				}
			});
		}
	}
}

// 上传文件到服务器
const uploadFileApi = callback => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		success: (chooseImageRes) => {
			uni.showLoading({
				title: '上传中...',
				mask: true
			})
			const tempFilePaths = chooseImageRes.tempFilePaths;
			uni.uploadFile({
				url: serverUrlReq + 'ajaxEntryCenter.php?WsAjaxPrj=KLY' +
					"&WsAjaxBiz=PublicAPP&WsAjaxAction=fileUpload",
				filePath: tempFilePaths[0],
				name: 'file',
				formData: {
					'uploadfile': 'file'
				},
				success: (uploadFileRes) => {
					console.log(uploadFileRes)
					let res = JSON.parse(uploadFileRes.data);
					uni.hideLoading();
					if (res.ErrMsg) {
						uni.showModal({
							title: '文件上传失败',
							content: res.ErrMsg,
							showCancel: false,
							success: function(res) {
								callback({
									status: false,
								})
							}
						});
					} else {
						callback({
							status: true,
							data: res.Result
						});
					}
				},
				fail(result) {
					uni.hideLoading();
					uni.showModal({
						title: '文件上传fail',
						content: JSON.stringify(result),
						showCancel: false,
						success: function(res) {
							callback({
								status: false
							})
						}
					});
				},
			});
		},
		fail: res => {
			uni.showModal({
				title: '文件选择失败',
				content: JSON.stringify(res),
				showCancel: false,
				success: function(res) {
					callback({
						status: false,
					})
				}
			});
		}
	});
}

// goEasy相关
const goEasy = GoEasy.getInstance({
	host: "hangzhou.goeasy.io", //应用所在的区域地址: 【hangzhou.goeasy.io |singapore.goeasy.io】
	appkey: "BC-b1e650ef62484e08826652d48242b06b", // common key,
	modules: ["im"],
	// true表示支持通知栏提醒，false则表示不需要通知栏提醒
	allowNotification: true //仅有效于app,小程序和H5将会被自动忽略

});

goEasy.onClickNotification((message) => {
	let currentUrl;
	const routes = getCurrentPages();

	if (routes && routes.length) {
		const curRoute = routes[routes.length - 1].route;
		const curParam = routes[routes.length - 1].options;
		currentUrl = '/' + curRoute + `?to=${curParam.to}`;
	}

	let newUrl;
	switch (message.toType) {
		case GoEasy.IM_SCENE.PRIVATE:
			newUrl = '/pages/message/chat?to=' + message.senderId;
			break;
			// case GoEasy.IM_SCENE.GROUP:
			// 	newUrl = '/pages/chat/groupChat/groupChat?to=' + message.groupId;
			// 	break;
	}

	if (currentUrl !== newUrl) {
		uni.navigateTo({
			url: newUrl,
		});
	}

});

const init_go_easy = (user_info, type) => {
	let currentUser = {
		"uuid": type + user_info.id,
		"name": type == 'user_' ? (user_info.true_name ? user_info.true_name : user_info.nickname) : (user_info
			.company_name ? user_info.company_name : (user_info.nickname ? user_info.nickname :
				'商家名称')),
		"avatar": user_info.profile_photo != '' ? user_info.profile_photo : '/static/user.png'
	}
	// console.log('初始化init_go_easy')
	// console.log(currentUser)
	uni.setStorageSync('currentUser', currentUser);
	if (goEasy.getConnectionStatus() === 'disconnected') {
		getApp().globalData.imService = new IMService(goEasy, GoEasy);
		getApp().globalData.imService.connect(currentUser);
	}
}
// 获取会话最新数据
const get_message_data = () => {
	//监听会话列表变化
	goEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {});
	goEasy.im.latestConversations({
		onSuccess: function(result) {
			let content = result.content;
			// console.log('加载会话列表成功')
			// console.log(content)
			let unreadTotal = content.unreadTotal;
			get_user_info(res => {
				let ss_notice_unreaded = res.data.Result.ss_notice_unreaded
				this.unreadTotal = Number(unreadTotal) + ss_notice_unreaded;
				if (this.unreadTotal > 0) {
					uni.setTabBarBadge({
						index: 1,
						text: this.unreadTotal.toString()
					});
				} else {
					uni.removeTabBarBadge({
						index: 1
					});
				}
			})
		},
		onFailed: function(error) {
			console.log("获取最新会话列表失败：, code:" + error.code + " content:" + error.content);
		}
	});
}
const formatDate = function(t) {
	t = t || Date.now();
	let time = new Date(t);
	let str = time.getMonth() < 9 ? ('0' + (time.getMonth() + 1)) : (time.getMonth() + 1);
	str += '-';
	str += time.getDate() < 10 ? ('0' + time.getDate()) : time.getDate();
	str += ' ';
	str += time.getHours();
	str += ':';
	str += time.getMinutes() < 10 ? ('0' + time.getMinutes()) : time.getMinutes();
	return str;
}

const formatDate2 = now => {
	let y = ''
	let m = ''
	let d = ''
	let h = ''
	let mi = ''
	let s = ''
	y = now.getFullYear();
	m = now.getMonth() + 1;
	d = now.getDate();
	h = now.getHours()
	mi = now.getMinutes()
	s = now.getSeconds()
	return y + '-' + (m < 10 ? "0" + m : m) + '-' + (d < 10 ? "0" + d : d);
}

function getNextDate(date, day) {
	var dd = new Date(date);
	dd.setDate(dd.getDate() + day);
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
	var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
	return y + "-" + m + "-" + d;
}

// 检测是否包括手机号码等敏感信息
const is_contain_sensitive_words = str => {
	str = String(str)
	// 检测手机号码
	if (str.length >= 11) {
		for (let i = 0; i < str.length - 10; i++) {
			let str_new = Number(str.slice(i, i + 11))
			if (!isNaN(str_new)) {
				if (str_new >= 13000000000 && str_new < 20000000000) {
					return true
				}
			}
		}
	}

	// 检测是否包括敏感词汇
	const sensitive_words = [
		'共产党', '民进党', '民主进步党', '国民党', '中华民国', '蔡英文', '苏贞昌', '吴钊燮', '微信', '手机号', '电话号码',
	]
	for (let i in sensitive_words) {
		if (str.indexOf(sensitive_words[i]) !== -1) {
			return true
		}
	}

	return false
}

// 从数组中多选数组
const select_from_arr = (data, index) => {
	let district = data[0]
	let district_index_arr = data[1]
	let index_of = district_index_arr.indexOf(index)
	if (index_of === -1) {
		district_index_arr.push(index)
		return district_index_arr
	} else {
		let district_index_new = []
		district_index_arr.map((item, index2) => {
			if (index2 !== index_of) {
				district_index_new.push(item)
			}
		})
		return district_index_new
	}
}

// 获取最新用户信息
const get_user_info = callback => {
	requestUrl('&WsAjaxBiz=Worker&WsAjaxAction=entityDataHandle', {
		handleMode: 'fetch',
		bizCatalog: 'WorkerEntity',
	}, res => {
		callback(res)
	})
}

// 从身份证中获取年龄
const get_age_from_id_num = idcard => (idcard && idcard.length == 18 && !isNaN(idcard.slice(6, 10))) ? (new Date()
	.getFullYear() - Number(idcard.slice(6, 10))) : ''

// 时间戳转换为时间
function getLocalTime(nS) {
	return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}

// 检测是否为身份证号码
function IsIdCard(str) {
	var reg = /^[1-8][1-7]\d{4}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dX]$/;
	return reg.test(str);
}

// 核销/支付
const paySettleMer = (workid, callback = () => {}, handleMode = 'paySettle') => {
	console.log(handleMode)
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	let params2 = {
		bizCatalog: 'TodoWorkEntity',
		handleMode: 'fetch',
		workid,
	}
	// 查询待支付金额
	requestUrl('&WsAjaxBiz=Worker&WsAjaxAction=entityDataHandle', params2, res => {
		if (res.status) {
			console.log('查询待支付金额')
			console.log(res.data)
			uni.hideLoading()
			uni.showModal({
				title: '确认支付' + res.data.Result.btr_feetotal + '元？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '加载中...',
							mask: true
						})
						uni.login({
							success: res => {
								let params = {
									bizCatalog: 'TodoWorkEntity',
									handleMode,
									workid,
									minaCode: res.code,
									todo: 'allow',
								}
								console.log('paySettle处理请求参数')
								console.log('支付参数', params)

								requestUrl(
									'&WsAjaxBiz=Trader&WsAjaxAction=entityDataHandle',
									params,
									res => {
										console.log('paySettle处理获取参数')
										console.log(res)
										if (res.status) {
											let prePayInfo = res.data.Result
												.prePayInfo
											// 走支付
											if (prePayInfo) {
												console.log('prePayInfo')
												console.log(prePayInfo)
												uni.hideLoading()
												uni.requestPayment({
													...prePayInfo,
													success: (res2) => {
														uni.showModal({
															title: '支付成功',
															showCancel: false,
															success: res => {
																callback
																	()
															}
														})
													},
													fail: function(
														res2) {
														if (res2
															.errMsg
															.indexOf(
																'cancel'
															) == -1
														) {
															uni.showModal({
																title: '支付失败',
																content: JSON
																	.stringify(
																		res2
																	),
																showCancel: false,
															})
														}
													}
												});
											} else {
												// 走余额
												uni.showModal({
													title: '支付成功',
													showCancel: false,
													success: res => {
														callback()
													}
												})
												uni.hideLoading()
												return
											}
										}
										uni.hideLoading()
									})
							}
						})
					}
				}
			})
		}
	})
}

// 处理报名者假头像
const formate_enrolled_heads = (enrolled_heads, num) => {
	let res_arr = []
	if (num > 0) {
		num = num > 3 ? 3 : num
		let enrolled_heads_arr = enrolled_heads.split(',')
		if (enrolled_heads_arr.length > 1) {
			res_arr = enrolled_heads_arr.slice(0, num)
		}
	}
	return res_arr
}
// 计算时间
const calc_hours = (start_time, end_time) => {
	let h1 = start_time.slice(0, 2)
	let min1 = start_time.slice(3, 5)
	let h2 = end_time.slice(0, 2)
	let min2 = end_time.slice(3, 5)
	let res = (Number(h2) - Number(h1)) + (Number(min2) - Number(min1)) / 60
	return res < 0 ? '--' : res.toFixed(1)
}
// 计算日期
const calc_date = (begin_datetime, finish_datetime) => {
	if (begin_datetime && finish_datetime) {
		let total_date = (new Date(finish_datetime) - new Date(begin_datetime)) / (1000 * 3600 * 24) + 1
		if (total_date > 0) {
			return total_date
		} else {
			return '--'
		}
	} else {
		return '--'
	}
}

const formate_name_card = (data) => {
	let res = {
		...data
	}
	let lawer_name = res.lawer_name
	let lawer_idcard = res.lawer_idcard
	let str = ''
	for (let i = 0; i < lawer_name.length - 1; i++) {
		str += '*'
	}
	res.lawer_name = str + lawer_name.slice(lawer_name.length - 1, lawer_name.length)
	str = ''
	for (let i = 0; i < 13; i++) {
		str += '*'
	}
	res.lawer_idcard = lawer_idcard.slice(0, 3) + str + lawer_idcard.slice(16, 18)
	return res
}
const formate_name_card_mem = (data) => {
	let res = {
		...data
	}
	let true_name = res.true_name
	let idcard = res.idcard
	let str = ''
	for (let i = 0; i < true_name.length - 1; i++) {
		str += '*'
	}
	res.true_name = str + true_name.slice(true_name.length - 1, true_name.length)
	str = ''
	for (let i = 0; i < 13; i++) {
		str += '*'
	}
	res.idcard = idcard.slice(0, 3) + str + idcard.slice(16, 18)
	return res
}
export default {
	formate_name_card_mem,
	formate_name_card,
	formatDate,
	init_go_easy,
	GoEasy,
	goEasy,

	serverUrl,
	serverUrlReq,
	webviewServerUrlReq,
	requestUrl,
	select_from_arr,
	uploadFileApi,
	uploadFileApiOSS,
	getPositionLocal,
	get_user_info,
	is_contain_sensitive_words,
	get_age_from_id_num,
	getLocalTime,
	IsIdCard,
	formatDate2,
	paySettleMer,
	get_message_data,
	formate_enrolled_heads,
	calc_hours,
	calc_date,
	getNextDate,
}
