import Vue from 'vue'
import Vuex from 'vuex'
import config from 'common/config.js'
import reqUtil from 'util/util-js/requstUtil.js'
import date from 'util/util-js/date.js'
import cNumber from 'util/util-js/makeNumber.js'
import BLE from 'util/util-js/BLE.js';
//快速打击部分
import o0 from "@/util/util-js/o0.js"
import o0Project from "@/util/util-js/o0Project.js"

import deviceData from "@/util/util-js/devices.js"

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		//引导层
		bGuidePages: false,

		//是否显示Canvas
		bCanvasShow: true,
		/**
		 * 是否需要强制登录
		 */
		forcedLogin: false,

		/**
		 * 蓝牙实时发送数据的页面的名称
		 */
		currentPageName: '',

		hasLogin: false,
		userInfo: null,
		userName: "匿名",
		days: 0,
		remainingDays: 0,
		signature: '',
		avatarUrl: "/static/defaultAvatar.png",
		// 是否是新用户,
		//TODO：登录接口返回的数据来判断
		bNewUser: false,
		//是否是第一次走新手
		bNewGuide: false,
		token: '',
		gender: 0,

		//省市区数据
		city: {
			label: '北京市-北京市-东城区',
			cityCode: "110101",
			//picker 选择器的index数组
			value: [0, 0, 0]
		},

		birthday: date.formatTime(new Date()),
		//默认值
		height: 0,
		weight: 0,
		//最近在玩的列表
		playGames: [],
		//最近在玩的排行游戏列表
		playRankingGames: [],
		//全部的游戏列表
		allGames: [],
		//关注的游戏列表
		favoriteGames: [],
		// 排行榜里面显示的游戏
		rankSelectedGame: null,
		rankInfo: null,
		cityName: "某市",
		/**
		 * 默认的运动数据
		 * date.addDaysFromNewDate(new Date(),1)
		 */
		defaultPlanData: {
			startTime: date.formatDate(new Date()),
			endTime: date.addDaysFromNewDate(new Date(), 6),
			targetWeight: 0, //目标公斤
			calorie: 360, //运动消耗的卡路里，默认300 大卡
			cumulativeCalorie: 0, //累计增重
			sportTime: 40, //运动时间
			/**
			 * 本地记录的消耗卡路里数量
			 */
			localCalorie: 0,
			/**
			 * 显示卡路里，过了12点清空
			 */
			showCalorie: 0,
			/**
			 * 总和
			 */
			allCalorie: 0
		},
		/**
		 * 计划的运动数据
		 */
		planData: {
			startTime: date.formatDate(new Date()),
			endTime: date.formatDate(new Date()), //date.addDaysFromNewDate(new Date(),1),
			targetWeight: 0, //目标公斤
			cumulativeCalorie: 0, //累计增重
			calorie: 300, //运动消耗的卡路里
			sportTime: 40, //运动时间
			/**
			 * 本地记录的消耗卡路里数量
			 */
			localCalorie: 0,
			/**
			 * 显示卡路里，过了12点清空
			 */
			showCalorie: 0,
			/**
			 * 总和
			 */
			allCalorie: 0
		},

		//记录表盘计划刷新的卡路里
		oldArcbarProCalorie: 0,
		//记录表盘当前的总卡路里
		oldArcbarAllCalorie: 0,


		//当前运动的世时间
		localSportTime: 0,


		//当前运动时间,运动时候记录的时间
		runingTime: 0,
		//蓝牙设备信息列表
		//id 不可变,用于保存到本地区分
		BLEInfoList: deviceData.getDeviceList(),
		//记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
		BLEDeviceList: [],
		//显示的蓝牙设备,取本地数据时候更新
		BLEDeviceShowList: [],
		//选择连接的蓝牙设备
		BLEConnectDevice: null,
		//获取到的服务
		BLEGetServices:null,
		//当前发送给蓝牙的指令，目前是只有蓝牙手柄
		currentInstruction: '',

		instructionState: {
			// bAcc: false, //是否开启加速计状态
			// bGyroscope: false, //是否开启陀螺仪状态
			bOpen: false, //是否开启指令
			bSteps: false, //是否开启步数
		},


		//绑定的设备
		DeviceBindingList: [],
		ConnectBindingDevice: null,

		cIndex: -1,
		//当前是否连接
		bConnection: false,
		//最近连接过的设备
		finallyUseDevice: null,

		//phoneNumber
		phoneNumber: '',
		openid: '',
		appleid: '',

		//获取验证码
		bCodeDisabled: false,
		count: 59,
		interval: null,

		//conversion列表
		oldSwiperList: [],

		// 计划任务过期
		bPlanExpired: false,
		// 制定玩计划任务后
		bPlanFinish: false,

		//标准体重,男女根据当前年龄计算
		standardWeight: 0,

		//是否安装了微信
		bInstallWechat: false,
		bHideWeixin: false,

		system: '', // 系统版本
		platform: '', // 平台
		appName: '',
		version: '1.6.3', //软件版本
		versionCode: '',
		showEndTime: config.endTime, //游戏显示时间字段，后台返回对应此时间之前的数据

		globalAcc: null,
		globalOri: null,

		//当前显示的模式下标
		currentModeIndex: 0,

		//蓝牙变量操作
		/**
		 * 操作蓝牙设备
		 */
		bOpenBluetooth: false,
		/**
		 * 是否初始化蓝牙适配器
		 */
		bOpenSuccess: false,
		/**
		 * 是否监听蓝牙状态变化
		 */
		bListenAdapterStateChange: false,
		/**
		 * 是否监听寻找新设备事件
		 */
		bListenDeviceFound: false,

		// 设备Id
		BLEDeviceId: "",
		// 服务Id
		BLEServiceId: "",
		// 特征值id
		BLENotifyCharacteristicId: "",

		//监听rssi对象
		BLERSSIInterval: null,

		//蓝牙服务timeout
		getBLEDeviceServicesTimeout: null,

		//本地游戏地址
		// http://192.168.0.112:7456/build/index.html
		// http://127.0.0.1:7456/build/index.html
		LocationGameUrl: "http://110.43.54.43/t8/",

		//快速打击对象
		filter: null,
		deviceMs: 1

	},
	mutations: {

		/**
		 * 获取记录的最后一次连接设备
		 * @param {Object} state
		 */
		getFinalUseDevice(state) {
			// 获取本地存储的最后一次使用的设备
			//1.获取最近连接的蓝牙设备, 指蓝牙搜索到的obj
			const value = uni.getStorageSync('finallyUseDevice');
			if (value) {
				state.finallyUseDevice = value;
			}
			console.log('获取的finallyUseDevice', value);
		},

		/**
		 * 存储最后一次使用的设备信息，后面登陆时候，如果存在设备最后一次使用信息，则自动连接
		 * @param {Object} state
		 * @param {Object} device
		 */
		setFinallUseDevice(state, device) {
			uni.setStorage({
				key: 'finallyUseDevice',
				data: device,
				success: (res) => {
					state.finallyUseDevice = device;
					console.log("保存finallyUseDevice：", res);
				}
			})
		},
		/**
		 * 移除记录的use device
		 */
		clearFinallUseDevice(state) {
			uni.removeStorage({
				key: 'finallyUseDevice',
				success: (res) => {
					state.finallyUseDevice = null;
					console.log("移除finallyUseDevice：", res);
				}
			})
		},
		/**
		 * 设置运动时间
		 * @param {Object} state
		 * @param {Object} time
		 */
		setLocalSportTime(state, time) {
			// let _sportTime = Number(time);
			state.localSportTime = Number(time);

			uni.setStorage({
				key: 'localSportTime',
				data: state.localSportTime,
				success: (res) => {
					// uni.showToast({
					// 	title: "保存成功"
					// })
				}
			})
		},

		/**
		 * 设置卡路里
		 * @param {Object} state
		 * @param {Object} calorie
		 */
		setLocalCalorie(state, calorie) {
			state.planData.localCalorie = Number(calorie);

			uni.setStorage({
				key: 'localCalorie',
				data: state.planData.localCalorie,
				success: (res) => {
					// uni.showToast({
					// 	title: "保存成功"
					// })
				}
			})
		},

		/**
		 * 设置表盘显示的卡路里，
		 * @param {Object} state
		 * @param {Object} calorie
		 */
		setShowCalorie(state, calorie) {
			state.planData.showCalorie = Number(calorie);

			uni.setStorage({
				key: 'showCalorie',
				data: state.planData.showCalorie,
				success: (res) => {
					// uni.showToast({
					// 	title: "保存成功"
					// })
				}
			})
		},

		/**
		 * 增加卡路里
		 * @param {Object} state
		 * @param {Object} calorie
		 */
		addlocalCalorie(state, calorie) {
			//卡路里不能为负数
			calorie = Math.abs(calorie);

			//当前需要添加的卡路里
			let temNum = Number(calorie);
			//本地的卡路里
			let temNum2 = Number(state.planData.localCalorie);
			// 本地加 + 传入的卡路里
			let _numberLocal = temNum.add(temNum2);

			//显示的卡路里
			let _showCalorie = Number(state.planData.showCalorie);
			//显示的卡路里加上 本地卡路里 和添加的卡路里之和要小于或等于 计划的卡路里
			let _allCalorie = _numberLocal.add(_showCalorie);
			// console.log("计算的最后卡路里_showCalorie:", _showCalorie,_allCalorie);
			//如果超过计划的，用计划的卡路里记录
			if (_allCalorie > state.planData.calorie) {
				let _calorie = Number(state.planData.calorie);
				//假如更新时候，localCalorie 值不为0，但是还未更新给服务器，此时，不能设置localCalorie 0
				//用传入的值，减去 allcalorie 总和和目标的差
				let _value = Number(_allCalorie).sub(_calorie);
				let _endValue = Number(_numberLocal).sub(_value);
				state.planData.localCalorie = Number(_endValue.toFixed(2));
				//如果大于或者等于的话，用计划 于 显示的卡路里 差值
				// state.planData.localCalorie = Number(_calorie.sub(_showCalorie).toFixed(2));

				// //显示最大值
				// state.planData.showCalorie = Number(_calorie.sub(state.planData.localCalorie).toFixed(2));
			} else {
				//
				state.planData.localCalorie = Number(_numberLocal.toFixed(2));
				// //输入的卡路里 + 自身显示的卡路里
				// state.planData.showCalorie = Number(temNum.add(_showCalorie).toFixed(2)); 
			}

			console.log("计算的最后卡路里:", state.planData);

			if (state.planData.localCalorie < 0) {
				//如果修改计划时候，本地数据计算的结果为负数,先取总和，localCalorie负再重置为0
				state.planData.showCalorie = _showCalorie.add(state.planData.localCalorie);
				state.planData.allCalorie = state.planData.showCalorie;
				state.planData.localCalorie = 0;
			} else {
				state.planData.allCalorie = _showCalorie.add(state.planData.localCalorie);
			}




			try {
				uni.setStorageSync('localCalorie', state.planData.localCalorie);
			} catch (e) {
				// error
				console.error(e);
			}
			try {
				uni.setStorageSync('showCalorie', state.planData.showCalorie);
			} catch (e) {
				// error
				console.error(e);
			}
			// uni.setStorage({
			// 	key: 'localCalorie',
			// 	data: state.planData.localCalorie,
			// 	success: (res) => {
			// 		// uni.showToast({
			// 		// 	title: "保存成功"
			// 		// })
			// 	}
			// })

			// uni.setStorage({
			// 	key: 'showCalorie',
			// 	data: state.planData.showCalorie,
			// 	success: (res) => {
			// 		// uni.showToast({
			// 		// 	title: "保存成功"
			// 		// })
			// 	}
			// })
		},
		/**
		 * 每次登陆同步本地数据到服务器
		 * 当天的数据更新，只更新一次
		 * @param {Object} state
		 */
		syncLocalDataToServer(state, callback) {
			let self = this;
			uni.getStorage({
				key: 'syncDate',
				success: function(res) {
					// console.log(res.data);
					let oldTime = res.data;
					let nDate = new Date();
					let newTime = date.formatDate(nDate);
					let days = date.datedifference(newTime, oldTime);
					// console.log(days);
					// 如果相差大于1天，
					if (days != 0) {
						// 更新存储日期
						uni.setStorageSync("syncDate", newTime);



						// 执行更新函数
						self.commit("syncRequestEvent", {
							success: () => {
								//清空显示的本地数据
								self.commit("setShowCalorie", 0);
								state.planData.allCalorie = state.planData.showCalorie.
								add(state.planData.localCalorie);

								if (callback)
									callback({
										newDate: nDate
									});
							}
						});

						//清空记录的本地运动时间
						// console.log('情况运动时间');
						self.commit("setLocalSportTime", 0);

						//设置本地数据是0
						state.localSportTime = 0;


					} else {
						if (callback)
							callback({
								newDate: nDate
							});
					}

					// date.getDays.
				},
				fail: function(res) {
					// console.error(res);
					// 如果没有日期，则存储一个新的
					let nDate = new Date();
					let tempTime = date.formatDate(nDate);
					uni.setStorageSync("syncDate", tempTime);

					if (callback)
						callback({
							newDate: nDate
						});
				}
			});



		},
		// 同步数据的请求
		syncRequestEvent(state, data) {
			let self = this;
			let {
				success,
				fail
			} = data;

			//需要卡路里取整存服务器，小数点后面，继续保留。以消除累计误差
			let oldLocalCalorie = state.planData.localCalorie;
			let _localCalorieInt = parseInt(state.planData.localCalorie);
			//小数点后面
			let _afterLocalCalorie = Number(oldLocalCalorie).sub(_localCalorieInt);

			console.log("*******===:", oldLocalCalorie, _localCalorieInt, _afterLocalCalorie);


			if (_localCalorieInt === 0) {
				// uni.showToast({
				// 	title: '',
				// 	icon: 'loading',
				// 	mask: true,
				// 	duration: 1000
				// })
				if (success)
					success();
				return;
			}
			uni.showToast({
				title: '',
				icon: 'loading',
				mask: false,
				duration: 10000
			})
			//把卡路里累计到cumulativeCalorie 变量，之后传服务器 += Math.round(state.planData.localCalorie)
			state.planData.cumulativeCalorie += _localCalorieInt;
			//添加到showCalorie 中
			state.planData.showCalorie = Number(state.planData.showCalorie).add(_localCalorieInt);

			state.planData.allCalorie = state.planData.showCalorie.add(_afterLocalCalorie);

			//不管是否同步成功，清空本地记录的卡路里，前一步已添加到cumulativeCalorie
			self.commit("setLocalCalorie", _afterLocalCalorie);
			self.commit("setShowCalorie", Number(state.planData.showCalorie));


			// 把卡路里记录到服务器
			reqUtil.requestData(config.URL.FITNESSPROGRAM, state.planData, 'POST').then(
				res => {
					// console.warn(res);
					if (res.code == 0) {
						uni.showToast({
							title: '同步成功',
							mask: true,
							duration: 1000
						});
						//同步一下服务器的返回值
						state.planData = Object.assign(state.planData, res.data);
						//暂时默认同步拳击1 的卡路里
						reqUtil.requestData(config.URL.UPLOADRANKING, {
							gameId: '1', //拳击模式 game id = 1;
							score: _localCalorieInt,
							cityCode: state.city.cityCode,
						}, "POST").then(res => {
								console.warn('****上传首页拳击卡路里,后面多个模式，可能需要多个不同的游戏id ***', res);
							},
							e => {
								console.log(e)
							});

						setTimeout(() => {
							uni.hideToast();
						}, 1000);



						if (success)
							success();
					} else {

						state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(_localCalorieInt);
						state.planData.showCalorie = Number(state.planData.showCalorie).sub(_localCalorieInt);

						self.commit("setLocalCalorie", oldLocalCalorie);
						if (fail)
							fail();
					}
					console.log("减法 ==", Number(state.planData.cumulativeCalorie).sub(_localCalorieInt));


				},
				e => {
					console.log(e);
					state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(_localCalorieInt);
					state.planData.showCalorie = Number(state.planData.showCalorie).sub(_localCalorieInt);
					self.commit("setLocalCalorie", oldLocalCalorie);

					uni.hideToast();
					if (fail)
						fail();
				}
			);
		},
		//登录成功后，重置一下状态
		resetCountDown(state) {

			if (state.interval) {
				clearInterval(state.interval);
				state.interval = null;
				state.count = 59;
				state.bCodeDisabled = false;
			}

		},

		//验证码操作
		countDown(state, phoneNumber) {
			//限制验证码操作
			state.bCodeDisabled = true;
			state.interval = setInterval(() => {
				--state.count;
				if (state.count <= 0) {
					clearInterval(state.interval);
					state.interval = null;
					state.count = 59;
					state.bCodeDisabled = false;
				}
			}, 1000);
			setTimeout(() => {
				clearInterval(state.interval)
				state.count = 59;
				state.bCodeDisabled = false;
			}, 60000);
			reqUtil.requestData(config.URL.GETCODE, {
				"phoneNumber": phoneNumber
			}).then(res => {
					console.log('requestData GETCODE =====', res);
					uni.showToast({
						title: "发送成功",
						mask: true,
						duration: 1000
					})

				},
				e => {
					console.log(e)
				});

		},
		//获取记录的蓝牙列表数据
		getBLEDeviceList(state) {
			// console.log("getBLEDeviceList=");
			uni.getStorage({
				key: 'BLEDeviceList',
				success: (res) => {
					console.log("*****getBLEDeviceList=", res);
					let _list = res.data;
					state.BLEDeviceList = res.data;
					//更新BLEDeviceShowList 数组
					state.BLEDeviceShowList = [];
					_list.forEach(item => {
						//如果记录到本地的id,和信息列表中的id一致,则结合
						for (let i = 0; i < state.BLEInfoList.length; i++) {
							let eq = state.BLEInfoList[i];
							if (item.id == eq.id) {
								state.BLEDeviceShowList.push(Object.assign({}, item, eq));
								break;
							}
						}
					})

				}
			})
		},

		//添加蓝牙设备数据
		addBLEDevice(state, data) {
			let devicelist = [];
			if (state.BLEDeviceList && state.BLEDeviceList.length != 0) {
				devicelist = state.BLEDeviceList;
			}
			// console.log(data, devicelist)

			let bHas = false;
			devicelist.forEach((item, index, selfArr) => {
				if (item.id == data.id) {
					//如果存在,更新保存的数据，比如 mac或者uuid等 
					selfArr[index] = item = Object.assign({}, item, data);
					bHas = true;
				}
			})
			//把当前添加的的蓝牙设信息备作为最后一次连接覆盖到本地
			this.commit('setFinallUseDevice', data);

			if (bHas) {
				return;
			}
			//设置蓝牙列表本地信息
			devicelist.push(data);
			uni.setStorage({
				key: 'BLEDeviceList',
				data: devicelist,
				success: (res) => {
					// uni.showToast({
					// 	title: "保存成功"
					// })
					state.BLEDeviceList = devicelist;
					// console.log("devicelist:",devicelist);
					//更新BLEDeviceShowList 数组
					state.BLEDeviceShowList = [];
					devicelist.forEach(item => {
						//如果记录到本地的id,和信息列表中的id一致,则结合
						for (let i = 0; i < state.BLEInfoList.length; i++) {
							let eq = state.BLEInfoList[i];
							if (item.id == eq.id) {
								// console.log("item:",item);
								state.BLEDeviceShowList.push(Object.assign({}, item, eq));
								break;
							}
						}
					})
					// console.log("state.BLEDeviceShowList:",state.BLEDeviceShowList);
				}
			})
		},
		//删除蓝牙设备数据
		deleteBLEDevice(state, index) {
			let devicelist = [];
			devicelist = state.BLEDeviceList;

			devicelist.splice(index, 1);
			uni.setStorage({
				key: 'BLEDeviceList',
				data: devicelist,
				success: (res) => {
					uni.showToast({
						title: "删除成功"
					})
					state.BLEDeviceList = devicelist;
					//更新BLEDeviceShowList 数组
					state.BLEDeviceShowList = [];
					devicelist.forEach(item => {
						//如果记录到本地的id,和信息列表中的id一致,则结合
						for (let i = 0; i < state.BLEInfoList.length; i++) {
							let eq = state.BLEInfoList[i];
							if (item.id == eq.id) {
								state.BLEDeviceShowList.push(Object.assign({}, item, eq));
								break;
							}
						}
					})
				}
			})
		},

		//获取计划表数据
		getPlanData(state, callback) {
			reqUtil.requestData(config.URL.FITNESSPROGRAMGET).then(res => {
					// console.log('获取计划表数据:getPlanData=====', res.data);
					if (res.code == 0) {

						state.planData = Object.assign(state.planData, res.data);

						// 处理本地数据
						let templocalCalorie = uni.getStorageSync("localCalorie");
						// console.log("templocalCalorie:", templocalCalorie, state.planData);
						if (templocalCalorie) {
							templocalCalorie = Number(templocalCalorie);
							if (templocalCalorie > state.planData.calorie) {
								state.planData.localCalorie = state.planData.calorie;
								uni.setStorage({
									key: "localCalorie",
									data: state.planData.localCalorie
								});
							} else {
								state.planData.localCalorie = templocalCalorie;
							}
						} else {
							state.planData.localCalorie = 0;
						}

						//处理本地的cumulativeCalorie
						let tempShowCalorie = uni.getStorageSync("showCalorie");
						// console.log("tempShowCalorie:", tempShowCalorie, state.planData);
						if (tempShowCalorie) {
							tempShowCalorie = Number(tempShowCalorie);
							if (tempShowCalorie > state.planData.calorie) {
								state.planData.showCalorie = state.planData.calorie;
								uni.setStorage({
									key: "showCalorie",
									data: state.planData.showCalorie
								});
							} else {
								state.planData.showCalorie = tempShowCalorie;
							}
						} else {
							state.planData.showCalorie = 0;
						}


						state.planData.allCalorie = state.planData.showCalorie.add(state.planData.localCalorie);

						// console.log("======",state.planData )
						state.days = date.datedifference(res.data.startTime, res.data.endTime) + 1;
						let nDate = new Date();
						let tempTime = date.formatDate(nDate);
						state.remainingDays = date.datedifference(tempTime, res.data.endTime) + 1;

						// console.log("state.remainingDays======", state.remainingDays);
					}
					// showArcbar
					if (callback) {
						callback();
					}

				},
				e => {
					console.log(e)
				});
		},
		/**
		 * 获取全部游戏
		 * @param {Object} state
		 */
		getAllGame(state, callback) {
			//获得全部游戏列表
			if (state.allGames.length != 0) {
				if (callback)
					callback();
				return;
			}
			reqUtil.requestData(
				config.URL.GAMELIST_BY_RANKING_SHOW, {
					rankingShow: 1,
					page: 1,
					size: 100
				}
			).then(res => {
					// console.log('获取默认的全部游戏 =====', res);
					if (res.code == 0) {
						state.allGames = [];
						state.allGames = state.allGames.concat(res.data);
					}
					if (callback)
						callback();
				},
				e => {
					console.log(e);
					if (callback)
						callback();
				}
			);
		},
		getRankGame(state, data) {
			let {
				param,
				callback
			} = data;

			reqUtil.requestData(config.URL.GETRANKRANGR, param).then(res => {

					console.log('获取默认的游戏数据:GETRANKRANGR=====', res);
					if (res.data != null) {
						state.rankSelectedGame = res.data.gameInfo;
						state.rankInfo = res.data.rankInfo;
						//然后获取排名

					}
					if (callback)
						callback(res);

				},
				e => {
					console.log(e)
				});
		},
		/**
		 * 苹果端登陆
		 * @param {Object} state
		 * @param {Object} data
		 */
		appleUserInfoLogin(state, data) {
			let self = this;
			let {
				params,
				callback
			} = data;
			console.log('获取用户数据:USERINFOAPPLEADD params=====', params);
			reqUtil.requestData(config.URL.USERINFOAPPLEADD, params, 'POST').then(res => {
					console.log('获取用户数据:USERINFOAPPLEADD =====', res);
					if (res.code == 0) {
						let userInfo = res.data;
						self.commit('login', userInfo);
						console.log("11~~");
					} else if (res.code = 201) {
						state.hasLogin = true;
					}
					console.log("apple callback!!!");
					callback();
				},
				e => {
					console.log(e)
				});
		},
		//添加用户信息和登录
		addUserAvatarAndLogin(state, data) {
			let self = this;
			let {
				params,
				filePath,
				callback
			} = data;
			console.log("addUserAvatarAndLogin 初始化对应数据");
			reqUtil.reqUpload(config.URL.USERINFOADDAVATARINFO, params, filePath).then(res => {
					console.log('获取用户数据:USERINFOADDAVATARINFO =====', res);
					if (res.code == 0) {
						let userInfo = res.data;
						self.commit('login', userInfo);
					} else if (res.code = 201) {
						state.hasLogin = true;
					}

					if (callback) {
						callback();
					}



				},
				e => {
					console.log(e)
				});
		},
		//app登录或h5
		accountLogin(state, callback) {
			let self = this;
			// console.log("app登录或h5 初始化对应数据")
			reqUtil.requestData(config.URL.USERINFOURL).then(res => {
					console.log('获取用户数据:USERINFOURL =====', res);
					if (res.code == 0) {
						let userInfo = res.data.userInfo;
						state.phoneNumber = res.data.phoneNumber || '';
						state.openid = res.data.openid || '';
						self.commit('login', userInfo);
					} else if (res.code = 201) {
						state.hasLogin = true;
					}

					if (callback) {
						callback();
					}



				},
				e => {
					console.log(e)
				});
		},
		//小程序页面登录
		login(state, userInfo) {
			console.log("登陆的信息==", userInfo);
			if (userInfo.cityCode == "" || userInfo.cityCode == null) {
				//不存在就设置默认值
				userInfo.cityCode = state.city.cityCode;
			}
			let cityCode = userInfo.cityCode;
			// console.log("cicicicitycode:", cityCode);
			let provinceData = require('@/components/slambb-picker/city-data/province.js').default;
			let cityData = require('@/components/slambb-picker/city-data/city.js').default;
			let areaData = require('@/components/slambb-picker/city-data/area.js').default;
			// 解析citycode
			for (let i = 0; i < provinceData.length; i++) {
				if (provinceData[i].value == cityCode.substr(0, 2)) {
					let currentCityData = cityData[i];
					for (let j = 0; j < currentCityData.length; j++) {
						if (currentCityData[j].value == cityCode.substr(0, 4)) {
							let areaDataTemp = areaData[i][j];
							for (let k = 0; k < areaDataTemp.length; k++) {
								if (areaDataTemp[k].value == cityCode) {
									state.city.value = [i, j, k];
									state.city.label = provinceData[i].label +
										'-' +
										currentCityData[j].label +
										'-' +
										areaDataTemp[k].label;
									state.cityName = currentCityData[j].label;
									break;
								}
							}
							break;
						}
					}
					break;
				}
			}

			state.userInfo = userInfo;
			state.userName = userInfo.username || '新用户';
			state.avatarUrl = userInfo.avatarUrl || '/static/defaultAvatar.png';
			state.gender = userInfo.gender;
			state.signature = userInfo.signature || '';
			state.birthday = userInfo.birthday;
			state.city.cityCode = cityCode.toString();
			state.weight = userInfo.weight || state.weight;
			state.height = userInfo.height || state.height;
			state.hasLogin = true;

			//登录时候 获取一下排行榜里面的游戏
			// this.commit('getRankGame', {
			// 	param: {
			// 		type: "china",
			// 		cityCode: 12345
			// 	}
			// });

		},

		// 退出登录
		// 删除token 操作
		delectToken(state, data) {
			let self = this;
			let {
				success
			} = data;
			reqUtil.requestData(config.URL.USERLOGINOUT, {}).then(res => {
					console.log('USERLOGINOUT=====', res);
					self.commit("logout");
					try {
						//清空保存的storage
						uni.clearStorageSync();
					} catch (e) {
						// error
						console.error(e);
					}
					if (state.BLERSSIInterval) {
						clearInterval(state.BLERSSIInterval);
						state.BLERSSIInterval = null;
					}

					if (state.BLEConnectDevice) {
						self.commit("onCloseBLEConnection", {
							getSuccess: () => {}
						});
					}

					if (success) {
						success(res);
					}

				},
				e => {
					console.log(e)
				});
		},
		logout(state) {
			state.userInfo = null;
			state.userName = "匿名";
			state.avatarUrl = '/static/defaultAvatar.png';
			state.days = '0';
			state.signature = '';
			state.gender = 0;
			state.hasLogin = false;

			state.phoneNumber = '';
			state.openid = '';
			state.appleid = '';

			//处理设备值
			state.cIndex = -1;
			//绑定的设备
			state.ConnectBindingDevice = null;
			//蓝牙设备
			state.BLEConnectDevice = null;
			
			//蓝牙服务
			state.BLEGetServices = null;

			//最近连接过的设备
			state.finallyUseDevice = null;

			//记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
			state.BLEDeviceList = [];
			//显示的蓝牙设备,取本地数据时候更新
			state.BLEDeviceShowList = [];

			//记录表盘计划刷新的卡路里
			state.oldArcbarProCalorie = 0;
			//记录表盘当前的总卡路里
			state.oldArcbarAllCalorie = 0;
		},

		loginUserInfo(state, data) {
			let {
				infoRes,
				success,
				fail
			} = data;
			console.log('loginUserInfo');

			reqUtil.requestData(config.URL.WXGETUSERINFO, {
				appid: 'wxd6dfd60729d33d17',
				encryptedData: infoRes.encryptedData,
				iv: infoRes.iv,
				signature: infoRes.signature,
				rawData: infoRes.rawData
			}).then(res => {
					console.log('wxInfoRes=====', res);
					let userInfo = res.data;
					this.commit('login', userInfo);
					if (success) {
						success(res);
					}

				},
				e => {
					console.log(e)
					if (fail) {
						success(fail);
					}
				});
		},
		//这里统一静默处理login
		oauth(state, context) {
			let {
				value,
				callback
			} = context;
			uni.login({
				provider: value,
				success: (res) => {
					// console.log('code:', res);
					reqUtil.requestData(config.URL.USERlOGINURL, {
						appid: 'wxd6dfd60729d33d17',
						code: res.code,
						platfrom: value
					}).then(res => {
							console.log('login token=====', res);
							state.token = res.data.token;
							uni.setStorageSync('token', state.token);
							uni.getUserInfo({
								provider: value,
								success: (infoRes) => {
									if (callback) {
										callback(infoRes);
									}
								},
								fail: (failRes) => {
									//假如没有授权，login 之后，不做处理，需要用户点击授权时候，再进行处理用户登录
									console.log('getUserInfo failRes:', failRes)
								}
							});
						},
						e => {
							console.log(e)
						});


				},
				fail: (err) => {
					console.error('授权登录失败：' + JSON.stringify(err));
				}
			});
		},
		onLuanchLogin(state, data) {
			let {
				success
			} = data;
			const filters = ['weixin', 'qq', 'sinaweibo'];
			let platform = '';
			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					if (res.provider && res.provider.length) {
						for (let i = 0; i < res.provider.length; i++) {
							if (~filters.indexOf(res.provider[i])) {
								platform = res.provider[i];
								console.log("platform=", platform);
								uni.showToast({
									icon: 'loading',
									title: ''
								})
								this.commit('oauth', {
									value: platform,
									callback: (infoRes) => {
										// console.log("infoRes:", infoRes);
										this.commit('loginUserInfo', {
											infoRes: infoRes,
											success: (res) => {
												console.log("获取用户成功");
												if (success) {
													success(res);
												}
												uni.hideToast();
											},
											fail: (res) => {
												console.error("获取用户失败");
												uni.hideToast();
											}
										});
									}
								})
							}
						}
						this.hasProvider = true;
					}
				},
				fail: (err) => {
					console.error('获取服务供应商失败：' + JSON.stringify(err));
				}
			});
		},


		initAdapter(state, callback) {

			// if (state.bOpenBluetooth) return;

			//初始化蓝牙模块
			BLE.openBluetoothAdapter({
				success: (res) => {
					state.bOpenSuccess = true;
					state.bOpenBluetooth = true;
					if (callback)
						callback(res);

					//监听断开事件
					BLE.onBLEConnectionStateChange();

				},
				fail: (fail) => {
					state.bOpenSuccess = false;
					state.bOpenBluetooth = false;
					uni.showToast({
						title: '蓝牙尚未开启!',
						icon: 'none'
					})
				},
				complete: (complete) => {
					console.log("complete bListenAdapterStateChange:", state.bListenAdapterStateChange);
					if (state.bListenAdapterStateChange) return;

					state.bListenAdapterStateChange = true;
					uni.onBluetoothAdapterStateChange((res) => {
						console.log('adapterState changed, now is', res)
						// 手机蓝牙状态
						state.bOpenBluetooth = res.available;
						if (state.bOpenBluetooth && !state.bOpenSuccess) {
							this.commit('initAdapter');
						}
					})

				}
			});
		},

		onGetDevices(state, context) {
			let {
				success
			} = context;
			if (!state.BLEConnectDevice) return;
			// #ifdef APP-PLUS
			let deviceId = state.BLEConnectDevice.deviceId;
			uni.getBLEDeviceRSSI({
				deviceId,
				success: res => {
					let _dis = Math.pow(Math.E, (Math.abs(res.RSSI) - 66.78) / 16.56);

					if (_dis > state.BLEConnectDevice.limitDis) {
						if (state.cIndex != -1) {
							uni.showToast({
								title: '设备断开连接！',
								icon: 'none',
								duration: 2000,
								mask: true
							})
						}

						setTimeout(() => {
							BLE.closeBLEConnection(deviceId);
							state.cIndex = -1;
							state.bConnection = false;
						}, 1000)

					} else {
						// console.log("DIS~~~~~~~~~", _dis);
						if (success) {
							success({
								RSSI: res.RSSI,
								DIS: _dis
							});
						}
					}
				}
			})
			// #endif


		},
		//清除连接的开启的timeout
		onUnloadCreateBLEConnectionTimeout(state) {
			if (state.getBLEDeviceServicesTimeout) {
				clearTimeout(state.getBLEDeviceServicesTimeout);
				state.getBLEDeviceServicesTimeout = null;
			}
		},
		//连接蓝牙
		onCreateBLEConnection(state, context) {
			let {
				index,
				item,
				initItem = false,
				getSuccess = null,
				getinitAdapter = null
			} = context;

			BLE.createBLEConnection(item, success => {
					state.bConnection = true;
					if (state.getBLEDeviceServicesTimeout) {
						clearTimeout(state.getBLEDeviceServicesTimeout);
						state.getBLEDeviceServicesTimeout = null;
					}
					
					state.getBLEDeviceServicesTimeout = setTimeout(function() {
						BLE.getBLEDeviceServices(item, () => {
							uni.showToast({
								title: '连接成功',
								icon: 'loading',
								duration: 2000,
								mask: true
							})
							//是否需要设置item，默认不设置
							if (initItem) {
								state.cIndex = index;
								state.BLEConnectDevice = item;
							}
							if (getSuccess)
								getSuccess();
						},(serviceList)=>{
							//搜索服务失败后
							state.BLEGetServices = serviceList;
						});
					}, 2000);
					// this.commit('onGetDevices', {
					// 	success: () => {

					// 		if (state.getBLEDeviceServicesTimeout) {
					// 			clearTimeout(state.getBLEDeviceServicesTimeout);
					// 			state.getBLEDeviceServicesTimeout = null;
					// 		}

					// 		state.getBLEDeviceServicesTimeout = setTimeout(function() {
					// 			BLE.getBLEDeviceServices(item, () => {
					// 				uni.showToast({
					// 					title: '连接成功',
					// 					icon: 'loading',
					// 					duration: 2000,
					// 					mask: true
					// 				})
					// 				//是否需要设置item，默认不设置
					// 				if (initItem) {
					// 					state.cIndex = index;
					// 					state.BLEConnectDevice = item;
					// 				}
					// 				state.bConnection = true;
					// 				if (getSuccess)
					// 					getSuccess();
					// 			});
					// 		}, 500);

					// 		// uni.$emit('connectionSuccess');

					// 		if (state.BLERSSIInterval) {
					// 			clearInterval(state.BLERSSIInterval);
					// 			state.BLERSSIInterval = null;
					// 		}
					// 		state.BLERSSIInterval = setInterval(() => {
					// 			this.commit('onGetDevices', {
					// 				success: () => {}
					// 			});
					// 		}, 1000)
					// 	}
					// })

				},
				fail => {
					console.log("***fail:",fail);
					if (fail.errCode === 10012) {
						console.log("连接超时,请重试!");
						uni.showToast({
							title: '连接失败，请重试',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					} else if (fail.errCode === 10013) {
						console.log("连接失败,蓝牙地址无效!");
						uni.showToast({
							title: '连接失败，蓝牙地址无效',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					} else if (fail.errCode === 10000) {
						// console.log("连接失败,初始化 uni.openBluetoothAdapter 调用之后使用");
						// uni.showToast({
						// 	title: '连接失败，检查手机蓝牙是否开启',
						// 	icon: 'none',
						// 	duration: 2000,
						// 	mask: true
						// })

						this.commit('initAdapter', () => {
							if (getinitAdapter) {
								getinitAdapter();
							}
						})
						// this.initAdapter(() => {
						// 	this.onDevice(item, e);
						// });
					} else {
						// err.errCode10003原因多种：蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
						console.log("连接失败,请重试!");
						uni.showToast({
							title: '设备未开启或被占用异常导致无法连接。',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					}
				});
		},
		//直接处理成功
		onCreateBLESuccess(state, context) {
			let {
				item,
				getSuccess = null
			} = context;

			BLE.createBLEConnection(item, success => {
					state.BLEConnectDevice = item;
					state.bConnection = true;
					if (getSuccess) {
						getSuccess();
					}

					// if (state.BLERSSIInterval) {
					// 	clearInterval(state.BLERSSIInterval);
					// 	state.BLERSSIInterval = null;
					// }
					// state.BLERSSIInterval = setInterval(() => {
					// 	this.commit('onGetDevices', {
					// 		success: () => {}
					// 	});
					// }, 1000)

					// uni.showToast({
					// 	icon: "none",
					// 	title: "连接设备成功！",
					// 	duration: 2000
					// })
				},
				fail => {
					if (fail.errCode === 10012) {
						console.log("连接超时,请重试!");
						uni.showToast({
							title: '连接超时，检查对应设备是否开启？',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					} else if (fail.errCode === 10013) {
						console.log("连接失败,蓝牙地址无效！");
						uni.showToast({
							title: '蓝牙地址无效，检查设备是否正常？',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					} else if (fail.errCode === 10000) {
						console.log("连接失败,初始化 wx.openBluetoothAdapter 调用之后使用");
						uni.showToast({
							title: '连接失败，检查手机蓝牙是否开启？',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					} else {
						console.log("连接失败,请重试!");
						uni.showModal({
							title: '连接失败',
							content: '设备未开启或被占用。请重启app和设备后重新连接。'
						})
						// uni.showToast({
						// 	title: '设备未开启或被占用异常导致无法连接。',
						// 	icon: 'none',
						// 	duration: 2000,
						// 	mask: true
						// })
					}
				});
		},
		//获取蓝牙服务
		onGetBLEDeviceServices(state, context) {
			let {
				item,
				success = null,
			} = context;
			BLE.getBLEDeviceServices(item, success,(serviceList)=>{
				state.BLEGetServices = serviceList;
			});
		},
		onCloseBLEConnection(state, context) {

			console.log("onCloseBLEConnection");
			let {
				getSuccess = null,
			} = context;

			if (state.BLERSSIInterval) {
				clearInterval(state.BLERSSIInterval);
				state.BLERSSIInterval = null;
			}

			BLE.closeBLEConnection(state.BLEConnectDevice.deviceId, () => {
				state.cIndex = -1;
				state.BLEConnectDevice = null;
				//蓝牙服务
				state.BLEGetServices = null;

				if (getSuccess) {
					getSuccess();
				}
				state.bConnection = false;
				
				uni.closeBluetoothAdapter({
					success(res) {
						console.log(res)
						state.bOpenBluetooth = false;
					}
				})
			});

			
		},
		//不关闭 adapter
		onOnlyCloseBLEConnection(state, context) {
			let {
				getSuccess = null
			} = context;

			if (state.BLERSSIInterval) {
				clearInterval(state.BLERSSIInterval);
				state.BLERSSIInterval = null;
			}

			BLE.closeBLEConnection(state.BLEConnectDevice.deviceId, () => {
				state.cIndex = -1;
				state.BLEConnectDevice = null;
				//蓝牙服务
				state.BLEGetServices = null;
				
				if (getSuccess) {
					getSuccess();
				}
				state.bConnection = false;
			});

		},
		onWriteBLEConnectionValue(state, context) {
			let {
				getSuccess = null,
				getFail = null,
				value
			} = context;

			if (!state.BLEConnectDevice && state.cIndex == -1) {
				uni.showToast({
					title: '蓝牙设备未连接',
					icon: 'none'
				})
			}
			// console.log(22);
			//记录蓝牙盒子当前的指令
			state.currentInstruction = value;
			// 发送 3 ：开启原始数据
			// 发送4 ：关闭原始数据
			// 发送 5 ：开启步数
			// 发送6 ：关闭步数
			if (value == "3") {
				state.instructionState.bOpen = true;
			} else if (value == "4") {
				state.instructionState.bOpen = false;
			} else if (value == "5") {
				state.instructionState.bSteps = true;
			} else if (value == "6") {
				state.instructionState.bSteps = false;
			}
			let retryCount = 3;
			
			BLE.writeBLECharacteristicValue(value,retryCount,getSuccess,getFail);
		},
		//获取距离
		onGetRSSITransDistance(state, context) {
			let {
				RSSI
			} = context;
			BLE.getRSSITransDistance(RSSI);
		},


		//添加使用的前端信息
		gOnAddClientInfo(state, context) {

			uni.getSystemInfo({
				success: (res) => {
					// console.log("系统信息:", res);
					let clientInfo = res;

					clientInfo.clientSystem = res.system;

					reqUtil.requestData(config.URL.ADDCLIENTINFO, clientInfo, 'POST').then(
						res => {
							console.warn(res);
						},
						e => {}
					);
				},
				fail: (err) => {},
				complete: () => {}
			})


		},

		//创建快速打击对象
		gCreateFilterObj(state) {
			state.filter = null;
			state.deviceMs = 1;
			state.filter = new o0Project.Filter();
			console.log("gCreateFilterObj");
		},
		//更新快速打击对象数据
		gUpdateFilter(state, context) {

			let {
				data,
				callback
			} = context;

			let {
				min,
				s,
				ms
			} = data;
			var msGap = ms - state.deviceMs;
			state.deviceMs = ms;
			while (msGap < 0) {
				msGap += 1000;
			}
			// console.log(data);
			let {
				ax,
				ay,
				az
			} = data.acc;

			state.filter.Update(new o0.Vector3(ax, ay, az), msGap, callback); //我自己的更新acc的函数
		},
		/**
		 * 限制开始游戏
		 */
		glimitPlayGame(state, context) {
			let {
				gameTags,
				callback
			} = context;

			//没有标签直接进去
			if (gameTags.length == 0) {
				callback();
				return;
			}

			let canPlay = false;
			gameTags.forEach((item) => {
				//如果存在普通模式
				if (item.tagMode === 'normal') {
					canPlay = true;
				}
				if (canPlay)
					return;
			})

			if (!canPlay) {
				//2.如果普通模式不存在，就判断是否连接硬件了
				if (!state.BLEConnectDevice || state.cIndex == -1) {
					uni.showToast({
						title: "请连接标签对应的设备模式！",
						icon: "none",
						duration: 2000,
						mask: true
					})
					return;
				}
				//3.如果连接了设备，判断但是处于什么模式
				gameTags.forEach((item, index, selfArr) => {
					//如果存在普通模式
					if (item.tagMode === state.BLEConnectDevice.usageMode) {
						canPlay = true;
					}
					if (canPlay)
						return;
					if (index == selfArr.length - 1) {
						uni.showToast({
							title: "游戏没有当前设备模式！",
							icon: "none",
							duration: 2000,
							mask: true
						})
					}
				})
			}

			if (canPlay) {
				callback();
			}
		},

		checkAppUpdata(state) {
			//#ifdef APP-PLUS
			let _temp = {
				appid: plus.runtime.appid,
				version: state.version,
				versionCode: state.versionCode,
				platform: state.platform.toLocaleLowerCase(),
			}
			//#endif
			//#ifdef H5
			//此 _temp 测试用
			let _temp = {
				appid: '1',
				version: "2.0.0",
				versionCode: "20122202",
				platform: "android",
			}
			//#endif
			reqUtil.requestData(config.URL.APPVERSIONUPDATE, _temp).then(res => {
					console.log('requestData APPVERSIONUPDATE =====', res);
					let _data = res.data;
					if (res.code == 0 && res.data.status === 1) {
						uni.showModal({ //提醒用户更新  
							title: "更新提示",
							content: res.data.note,
							success: (res) => {
								if (res.confirm) {
									if (state.platform.toLocaleLowerCase() == "android") {
										plus.runtime.openURL(_data.url, function(res) {
											plus.nativeUI.alert("本机没安装应用宝,请安装后获取新版本。");
										}, 'com.tencent.android.qqdownloader');

									} else {
										//ios
										plus.runtime.openURL(_data.url);
									}
								}
							}
						})

					} else {
						uni.showToast({
							title: '当前为最新版本',
							icon: 'none',
							duration: 2000,
							mask: true
						})
					}
				},
				e => {
					console.log(e)
				});

		},

	}
})

export default store
