import utils from '@/utils/encode';
// import login from '../api/login.js';
// import station from '@/api/station.js';
import QQMapWX from '@/static/qqmap-wx-jssdk.min.js';
import oilIdentityApi from '@/api/oil-identity.js'
class Anticorrosive {
	//需要的基本数据定义
	reqData = null
	data = null;
	configure = null;
	pageKeys = ['outputField', 'field', 'type', 'defaultValue'];
	constructor(data, configure) {
		// 初始化数据 => 校验数据
		this.data = data;
		this.configure = configure;
		return this.chenk();
	}
	
	// 递归 生成数据结构
	generate(data, configure) {
		// 通过传入的源数据生成相应的数据结构
		let reqData = data instanceof Array ? [] : {};
		//递归配置参数直到数据类型为基本类型 创建相应的数据（深拷贝）
		for (const fields of configure) {
			this.pageKeys.forEach(item => {
				let fieldsKeys = Object.keys(fields);
				if (!fieldsKeys.includes(item)) throw new Error(`必填字段 :${item} 不能为空`);
			})
			let field = data[fields.field] === undefined ? fields.defaultValue ? fields.defaultValue : null : data[
				fields.field]; //如果为undefined直接为null；
			let isChildField = fields?.childField ? true : false; //判断是否有子配置项
			let isType = fields.type === typeof field; //判断数据类型是否匹配
			// console.log(field,fields.type,typeof field,'isType')
			//检测是field类型  基本类型/引用类型
			if (field instanceof Function) { //引用类型且为Function
				console.warn("Function类型无法配置");
				reqData[fields.outputField] = field
			} else if (field instanceof Set) { //引用类型且为Set
				console.warn("Set类型无法配置");
				reqData[fields.outputField] = field
			} else if (field instanceof Map) { //引用类型且为Map
				console.warn("Map类型无法配置");
				reqData[fields.outputField] = field
			} else if (field instanceof Array) { //引用类型且为数组 递归
				if (!isType) console.warn(`数据源与数据类型不匹配:${fields.field}`);
				reqData[fields.outputField] = [];
				reqData[fields.outputField] = isChildField ? field.map(element => this.generate(element, fields
					.childField)) : field;
			} else if (field instanceof Object) { //引用类型 递归
				if (!isType) console.warn(`数据源与数据类型不匹配:${fields.field}`);
				reqData[fields.outputField] = isChildField ? this.generate(field, fields.childField) : field;
			} else {
				//  null 和基本类型
				reqData[fields.outputField] = this.voluation(field, fields);
			}
		}
		return reqData
	}
	// 数据校验
	chenk() {
		let testingType = true;
		if (this.data == undefined || this.data.constructor == Function || this.data.constructor == Set || this.data
			.constructor == Map || !(this.data instanceof Object)) {
			testingType = false
		}
		if (this.configure == undefined || this.configure.constructor == Function || this.configure.constructor ==
			Set || this.configure.constructor == Map || !(this.configure instanceof Object)) {
			testingType = false
		}
		if (testingType) {
			// 校验通过 => 生成数据
			return this.generate(this.data, this.configure)
		} else {
			return this.data
		}
	}
	voluation(data, configure) {
		if (!(typeof configure.defaultValue === configure.type)) throw new Error(
			`定义的数据类型与默认值数据类型不匹配:${configure.field}`);
		let value = null;
		let isData = data === null;
		if (isData) return configure.defaultValue; //如果data为null直接返回默认值
		switch (configure.type) {
			case 'number':
				value = isNaN(Number(data)) ? configure.defaultValue : Number(data);
				break;
			case 'string':
				value = String(data)
				break;
			case 'boolean':
				value = Boolean(data)
				break;
		}
		if (configure?.customHandler) { //是否有自定义处理程序
			let customHandlerValue = configure.customHandler(value);
			value = customHandlerValue !== undefined ? customHandlerValue : value
		}
		return value
	}
}

export default {
	Anticorrosive,
	getPhone(e){
		return new Promise((re,rj)=>{
			const data1 = {
				...e.detail,
				sessionKey: uni.getStorageSync('sessionKey'),
				unionId: uni.getStorageSync('unionid'),
				openId: uni.getStorageSync('openid'),
				appId: 'wxed3e2914d6aa4d52'
			}; 
			oilIdentityApi.ackPhone(data1).then(resj => { 
				re(resj.data)
			});
		}) 
	},
	async WXlogin(e) {
		return new Promise((re, rj) => {
			uni.login({
				provider: 'weixin',
				success: async (loginRes) => {
					const code = loginRes.code
					oilIdentityApi.sendCode(loginRes.code).then(res => {
						if (res.code === 20000) {
							uni.setStorageSync('sessionKey', res.data.sessionKey);
							uni.setStorageSync('openid', res.data.openId);
							uni.setStorageSync('unionid', res.data.unionId);
							const data1 = {
								...e.detail,
								sessionKey: uni.getStorageSync('sessionKey'),
								unionId: uni.getStorageSync('unionid'),
								openId: uni.getStorageSync('openid'),
								appId: 'wxed3e2914d6aa4d52'
							}
							oilIdentityApi.getPhone(data1).then(resj => {
								re(resj.data.phoneNumber)
							});
						} else if (res.code == 1002) {
							uni.showModal({
								title: '微信登录失败提醒',
								content: `${res.msg}如有疑问，请联系客服处理`
							})
	
						}
					}).catch(err => {
						uni.showToast({
							title: '登陆失败',
							icon: 'none'
						})
	
					})
	
				},
				fail: err => {},
			})
		})
	},
	difTags(res) {
		res.data.forEach((item, index) => {
			item['tags'] = ['maxCurrent', 'createSource'].map((tag, tagIndex) => {
				let result = {}
				switch (tag) {
					case 'maxCurrent':
						result = {
							label: `最大${item[tag]}A`,
							color: '#6EA29BCC'
						}
						break;
					case 'createSource':
						let source = this.difSource(item[tag]);
						result = {
							...source
						}
						break;
				}
				return result
			});
			if (index == 0) item['tags'].unshift({
				label: '距离最近',
				color: '#36658DFF'
			})
		})
	},
	difSource(e) {
		switch (e) {
			case 'XXCD':
				return {
					label: '星星充电',
						color: '#E48011CC'
				}
			case 'QT':
				return {
					label: '其他',
						color: '#121836CC'
				}
			case 'KD':
				return {
					label: '快电',
						color: '#FF5F0FCC'
				}
			case 'TLD':
				return {
					label: '特来电',
						color: '#7AA0F4CC'
				}
			case 'YKC':
				return {
					label: '云快充',
						color: '#00A7EBCC'
				}
			case 'ZGGD':
				return {
					label: '中国国电',
						color: '#27AB3BCC'
				}
		}
	},
	userLocationChenk(){ 
		return new Promise((re,rj)=>{
			wx.getSetting({
				success(res) {
					console.log(res.authSetting,'res.authSetting')
					if (!res.authSetting[ 'scope.userLocation']) {
								console.log('用户没有授权用户没有授权用户没有授权用户没有授权')
						// 用户没有授权
						uni.showModal({
							title: '提示',
							content: '您暂无授权定位权限，将无法显示油站距离',
							success(res) {
								if (res.confirm) {
									wx.openSetting({
										success(res) {
											if (res.authSetting['scope.userLocation']) {
												re()
												// 授权成功，重新定位
											} else {
												// 没有允许定位权限
												wx.showToast({
													title: '您拒绝了定位权限，将无法使用附近电站站功能',
													icon: 'none'
												});
												rj('拒绝了定位权限')
											}
										},
										fail() {
											rj('openSetting调用失败')
										}
									})
								}else{
									rj('取消授权')
								}
							}
						})
					}else{
						re()
					}
				},
				fail(err){
					rj(err)
				}
			})
		}) 
	},
	getLocation() {
		return new Promise((re, rj) => {
			uni.getLocation({
				type: 'wgs84',
				geocode: true,
				success: function(res) {
					const qqmapsdk = new QQMapWX({
						key: 'NYEBZ-YURY3-XTU3N-YBR54-PKW6E-ROB2F'
					});
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: res.latitude,
							longitude: res.longitude
						},
						success(addressRes){
							 var address = addressRes.result.formatted_addresses.recommend;
							 let location = {
								 ...res,
								 address
							 }
							 uni.setStorageSync('location',location );
							 re(location)
						},
						fail(err){
							rj(err)
						}
					})

				},
				fail(err) {
					rj(err)
				}
			})
		})

	},
	routingParameterGeneration(parameter){
		if(parameter==null||parameter==undefined) return;
		const parameterType = typeof parameter;
		if( parameterType== 'string'){
			let obj = {};
			let splitParameter =   parameter.split('?');
			if(splitParameter.length<=1){
				console.warn("暂无路径参数");
				return
			} 
			splitParameter[1].split('&').forEach(item=>{
				if(item.indexOf('=')!==-1){
					let  splitItem = item.split('=')
					obj[splitItem[0]] =  splitItem[1]
				}else{
					console.warn("error");
					console.log(item)
				}
			})
			return  obj
		}else if(parameterType == 'object'){
			let stringParameter = '?' 
			let parameterEntries = Object.entries(parameter);
			parameterEntries.forEach((key,index)=>{
				let itemString = `${key[0]}=${key[1]}${ parameterEntries.length-1==index?'':'&' }`;
				stringParameter += itemString
			}) 
			return stringParameter
		}
	},
	scanCode() {
		return new Promise((re, rj) => {
			uni.scanCode({
				onlyFromCamera: true,
				success: (res) => {
					re(res)
				},
				fail(err) {
					rj(err)
				}
			});
		})

	},
	loginOut() {
		// return new Promise((re, rj) => {
		// 	login.logoutAuthSystem('ELEC_COM_DRIVER_MINI').then(res => {
		// 		if (res.code == 20000) {
		// 			re(res)
		// 		} else {
		// 			rj(res)
		// 		}
		// 	}).catch(err => {
		// 		rj(err)
		// 	})
		// })
	},
	getCode(data) {
		return new Promise((re, rj) => {
			login.sendSmsForEleccomDriverMini(data).then(res => {
				if (res.code == 20000) {
					re(res)
				} else {
					rj(res)
				}
			}).catch(err => {
				rj(err)
			})
		})
	},
	bindLoginByPhoneOilOmsWebMini(data) {
		// return new Promise((re, rj) => {
		// 	login.bindLoginByPhoneOilOmsWebMini({
		// 		...data,
		// 		sessionKey: uni.getStorageSync('sessionKey'),
		// 		unionId: uni.getStorageSync('unionid'),
		// 		openId: uni.getStorageSync('openid'),
		// 	}).then(res => {
		// 		if (res.code == 20000) {
		// 			re(res)
		// 		} else {
		// 			rj(res.code)
		// 		}
		// 	}).catch(err => {
		// 		rj(err)
		// 	})
		// })
	},
	sendCode(code) {
		// return new Promise((re, rj) => {
		// 	login.sendCode(code).then(res => {
		// 		uni.setStorageSync('openid', res.data.openId);
		// 		uni.setStorageSync('unionid', res.data.unionId);
		// 		uni.setStorageSync('sessionKey', res.data.sessionKey)
		// 		re(res)
		// 	}).catch(err => {
		// 		rj(err)
		// 	})
		// })
	},
	autoLogin(codeData) {
		// return new Promise((re, rj) => {
		// 	login.loginOilOmsWebMini(codeData).then(res => {
		// 		if (res.code == 20000) {
		// 			re(res)
		// 		} else {
		// 			rj(res.code)
		// 		}
		// 	}).catch(err => {
		// 		rj(err)
		// 	})
		// })
	},
	weixinLogin() {
		return new Promise((re, rj) => {
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					re(loginRes)
				},
				fail: err => {
					rj(err)
				},
			})
		})
	},
	async getCards() {
		// await station.getAccountList().then(res => {
		// 	if (res.code == 20000) {
		// 		res.data.forEach(item => {
		// 			item['isEye'] = false
		// 		})
		// 		uni.setStorageSync('cards', res.data);
		// 	}
		// })
	},
	async loginSuccess(res) {
		let resData = res.data
		if (resData.authTokenDTO.loginFlag) {
			uni.setStorageSync('Authorization', resData.authTokenDTO.accessToken)
			uni.setStorageSync('accountStatus', resData.isCompanyAccount)
			let user = resData.authTokenDTO.loginUser
			uni.setStorageSync('user', user);
			await this.getCards();
			setTimeout(() => {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					complete: (err) => {}
				})
			}, 500);
			uni.reLaunch({
				url: '/pages/index/index',
				fail() {
					console.log('跳转失败')
				}
			})
		}
	},

	//调起上传图片
	chooseImage(clickfn) {
		const JSESSIONID = utils.uuid()
		let chooseImageUrl = ''
		uni.chooseImage({
			success: (chooseImageRes) => {
				uni.showLoading({
					title: '加载中'
				})
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.uploadFile({
					url: 'https://www.xingoil.com/adminapi/oil-oss/obejct/uploadFile',
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						ossKey: 'xingyou',
						pathKey: 'publicxingyou',
						encrypt: 'PUBLIC',
					},
					header: {
						"Content-Type": "multipart/form-data",
						"Authorization": uni.getStorageSync('Authorization'),
						'dataSources': 'MP',
						"imei": uni.getStorageSync('unionid'),
						"openId": uni.getStorageSync('openid'),
						'JSESSIONID': JSESSIONID,
						'token': utils.md5Salt(JSESSIONID)
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						chooseImageUrl = JSON.parse(uploadFileRes.data).data.publicUrl
						clickfn(chooseImageUrl)
					},
					fail: () => {
						uni.hideLoading()
					}
				});
			},
			fail: () => {
				uni.hideLoading()
			}
		});
	},
	getnum(num, size = 2) {
		if (String(num).indexOf('.') == -1 || String(num).split('.')[1].length < 2) return Number(num).toFixed(size);
		var s = num.toString();
		var result = s.substring(0, s.indexOf(".") + 1 + size); 
		return result
	},
	//数据转为两位小数
	numberSetting(obj, key, nm = 2) {
		if (arguments.length < 2) throw new Error('请检查函数配置参数,最少传递两个必填参数');
		if (!Array.isArray(key)) throw new Error('参数2必须为Array');
		// if (obj.constructor.toString().indexOf('Object') == -1) throw new Error('参数1必须为Object');
		if (Array.isArray(obj)) {
			obj.forEach((item, index) => {
				if (Array.isArray(item)) {
					this.numberSetting(item, key, nm)
				}
				let keyArray = Object.keys(item)
				keyArray.forEach(i => {
					if (key.includes(i)) {
						item[i] = isNaN(Number(item[i])) ? 0.00 : Number(item[i]).toFixed(nm)
					}
				})
			})
		} else {
			Object.keys(obj).forEach(keys => {
				if (key.includes(keys)) {
					// if (isNaN(Number(obj[keys]))) throw new Error(keys + '值不是数字')
					// obj[keys] = Number(obj[keys]).toFixed(nm);
					obj[keys] = isNaN(Number(obj[keys])) ? 0.00 : Number(obj[keys]).toFixed(nm)
				}
			})
		}

	},
	/*
	校验数据规范
	data:校验源数据,
	options:校验配置,
	correct:是否修正
	*/
	checkData(data, options, correct = false) {
		// 校验对象
		let checkData = {
			typeFn(data, type) {
				return typeof data == type
			},
			correctFn(item) {
				console.log('校验失败', item)
				//查看是否修正
				if (correct) {
					//修正
					switch (item.type) {
						case 'number':
							data[item.field] = data[item.field] == null ? item.defaultValue : data[item.field] ===
								'' || isNaN(Number(data[item.field])) ? item.defaultValue : Number(data[item.field])
							break;
						case 'string':
							data[item.field] = data[item.field] == null ? item.defaultValue : String(data[item
								.field])
							break;
						case 'null':
							data[item.field] = null
							break;
					}
				} else {
					//无需直接退出
					wx.exitMiniProgram({
						success: function() {
							console.log('拜拜')
						}
					})
					// throw new Error('错误！！！');
				}
			},
		}
		//参数校验
		if (arguments.length < 2) throw new Error('请检查函数配置参数,最少传递两个必填参数');
		if (!Array.isArray(options)) throw new Error('参数2必须为Array');
		//获取对象的key
		let dataKeys = Object.keys(data);
		//开始通过 options 校验
		options.forEach(item => {
			//判断是否有该字段
			if (typeof data[item.field] !== 'undefined') {
				//校验数据类型
				if (!checkData.typeFn(data[item.field], item.type)) {
					//类型校验失败
					checkData.correctFn(item);
				}
			} else {
				console.log(`%c  ${item.field} ← 错误值,请检查源数据中该字段`, 'font-size:50px;color:red');
				checkData.correctFn(item);
			}
		})
	},
	//表单校验
	checkFn(obj, whiteList, configure = {}) {
		//校验状态 con
		let con = {
			result: true,
			field: '',
			WrongText: '',
			errCheckField: ''
		}
		//校验参数
		if (arguments.length < 1) throw new Error('请检查函数配置参数,最少传递1个必填参数');
		if (obj.constructor.toString().indexOf('Object') == -1) throw new Error('参数1必须为Object');
		if (whiteList && !Array.isArray(whiteList)) throw new Error('参数2必须为Array');
		let configurationTable = Object.keys(configure)
		// console.log(configurationTable, obj, '需要校验的字段数组')
		// 循环需要校验的对象
		Object.keys(obj).forEach(keys => {
			// console.log(keys, '当前循环的校验对象')
			//如果循环的当前字段在白名单内跳过
			// console.log(whiteList, '白名单')
			if (whiteList.includes(keys)) return
			//校验状态改变跳过
			// console.log(con.result, '校验状态')
			if (!con.result) return
			if (configurationTable.includes(keys)) {
				//当前需要匹配的字段 obj[keys] configure[keys]
				//循环配置参数 拿到校验配置
				// console.log('key:', keys, '源对象:', obj[keys], '校验配置', configure[keys], '匹配到的需要校验的数据')
				Object.keys(configure[keys]).forEach(pages => {
					if (!con.result) return
					// console.log('字段:', keys, '开始校验', pages, )
					// configure[keys][pages]
					switch (pages) {
						case 'type':
							con.result = typeof obj[keys] == configure[keys][pages]
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + '校验出错'
								con.errCheckField = pages
							}
							break;
						case 'length':
							con.result = obj[keys].toString().length == configure[keys][pages]
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + '校验出错'
								con.errCheckField = pages
							}
							break;
						case 'minLength':
							con.result = obj[keys].toString().length >= configure[keys][pages]
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + '校验出错'
								con.errCheckField = pages
							}
							break;
						case 'maxLength':
							con.result = obj[keys].toString().length <= configure[keys][pages]
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + '校验出错'
								con.errCheckField = pages
							}
							break;
						case 'custom':
							con.result = configure[keys][pages].test(obj[keys])
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + '校验出错'
								con.errCheckField = pages
							}
							// console.log('自定义类型校验', configure[keys][pages], '值', obj[keys])
							break;
						case 'tacitly':
							con.result = Boolean(obj[keys])
							if (!con.result) {
								con.field = keys
								con.WrongText = configure[keys].WrongText ? configure[keys].WrongText :
									'字段:' + con.field + ',' + pages + '校验出错'
								con.errCheckField = pages
							}
							// console.log('自定义类型校验', configure[keys][pages], '值', obj[keys])
							break;
						default:
							// console.log(pages, '其他')
							break;
					}
				})
			}
		});
		// console.log(con, '校验结果')
		return con
	}
}