/**
 * 登录状态管理
 * 个人信息数据持久化
 */
import Vue from 'vue';
import Vuex from 'vuex';
// import $api from "@/api.js";
import Request from '@/js_sdk/luch-request/luch-request/index.js';
const http = new Request();
import md5 from '@/js_sdk/js-md5/md5.min.js';
import {config} from '@/config/config.js'
Vue.use(Vuex);
// const userKey = md5("userInfo");
const userKey = "userInfo";
const hPageKey = md5('historyPage');
// const sysTokenKey = md5('accessToken');
const sysTokenKey ='accessToken';
const loginUrl = '/pages/login/loginType';
export default new Vuex.Store({
	state: {
		hasLogin: false,
		userInfo: {
			customerCompanyInfoForm:{}
		},
		token: '',
		cartListTmp:[],
		hPage: ''
	},
	mutations: {
		addCart(state,data){
			if(data){
				state.cartListTmp = data
				console.log("vuex add：",state.cartListTmp)
			}			
		},
		clearCart(state){
			state.cartListTmp = []
			console.log(state.cartListTmp)
		},
		login(state, token = '') {
			token = token instanceof Object ? token.token : token;
			state.token = token || uni.getStorageSync(sysTokenKey).accessToken || '';
			state.hasLogin = Boolean(state.token);			
			//保存token
			uni.setStorage({
				key: sysTokenKey,
				data: {
					accessToken: state.token
				}
			});
		},
		/**
		 * 退出登录，传入false只更新缓存不跳转
		 */
		logout(state, v = true) {
			state.hasLogin = false;
			state.userInfo = {};
			state.token = '';
			uni.removeStorage({
				key: userKey
			});
			uni.removeStorage({
				key: sysTokenKey
			});
			//跳到登录页
			// v && $api.goto(loginUrl);
		},
		// historyPage(state, pUrl = '') {
		// 	if($api.alterUrl('/',pUrl) != loginUrl){
		// 		state.hPage = pUrl || uni.getStorageSync(hPageKey).url;
		// 		//记录历史页
		// 		uni.setStorage({
		// 			key: hPageKey,
		// 			data: {
		// 				url: state.hPage
		// 			}
		// 		});
		// 	}
		// },
		
		async upInfo(state, provider = {}) {
			const token = uni.getStorageSync(sysTokenKey);
			let thetoken = 'Bearer ' + token.accessToken;
			//用户信息结构
			const infoObj = {
				"page": 0,
				"pageNo": 0,
				"pageNum": 1,
				"pageSize": 10,
				"pageStart": null,
				"pageEnd": null,
				"limit": 0,
				"accessToken": null,
				"fkProductGuid": null,
				"fkOrgGuid": null,
				"state": null,
				"createUser": "",
				"createTime": "",
				"modifiedUser": "",
				"modifiedTime": "",
				"orgBrevity": null,
				"ico": null,
				"params": null,
				"codeUrlPrefix": null,
				"loginOrgGuid": null,
				"msgCode": null,
				"storeName": null,
				"guid": "",
				"account": "",
				"passwd": "",
				"customerType": null,
				"customerName": "",
				"nickName": "",
				"pid": null,
				"phone": null,
				"sex": null,
				"score": null,
				"wxId": "",
				"unionId": null,
				"headImage": "",
				"isCompany": 0,
				"isValidate": 0,
				"isEnable": 1,
				"queryStr": null,
				"carbonAmount": null,
				"goodsNum": null,
				"farmerNum": null,
				"farmerPersonNum": null,
				"goodsList": null,
				"loginType": null,
				"customerCompanyInfoForm": null,
				"channelType": null
			};
			const then = res => {
				if (res.data.code == 0) {
					let data = res.data.retBody instanceof Object ? res.data.retBody : infoObj;
					//处理头像连接
					// data.headImage = $api.alterUrl($api.href, data.headImage || "");
					state.userInfo = data;
					uni.setStorage({ //缓存用户登陆状态
						key: userKey,
						data
					});
				}
			};
			//读取本地缓存信息进行赋值
			then({
				code: 0,
				data: Object.assign(uni.getStorageSync(userKey),provider)
			});
			//在线更新取得用户信息
			then(await(
					http.get(config.apiBaseurl + '/carbon-h5/wap/customer/getCustomerByToken',{header: {Authorization:thetoken}}).then(res => {
						// console.log('getCustomerByToken', res.data);
						if(res.data.retHead.errCode == 0){res.data.code = 0;}
						// 处理非微信头像
						let headImage = res.data.retBody.headImage;
						if (headImage) {
						   //判断是否符合http://符合返回真不符合返回假
						   var http = /^http:\/\/.*/i.test(headImage);
						   //判断是否符合https://符合返回真不符合返回假
						   var https = /^https:\/\/.*/i.test(headImage);
						   //如果两个都为假，我们就为客户添加http://
						   if (!http && !https) {
							   headImage = config.onlineImg + headImage;
						   }
					   };
					    res.data.retBody.headImage = headImage;
						// 处理非微信头像						
						return res;
					}).catch(err => {
						// console.log('err', err)
					})
				));
		}
	}
});
