import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex) // vue的插件机制
// 模块
import requestList from "./requestList.js";
import addressDefault from "./addressDefault.js";
// 共用工具
import request from "@/common/request/index.js";
import {
	appId,
	login,
	getUserProfile
} from "@/common/device/index";

const store = new Vuex.Store({
	state: {
		bind:0,
		face:"",
		name:"",
		openid:'',
		appId:"",
		customer_id:""
	},
	mutations: {
		increment(state, options) {
			Object.keys(options).forEach(item => state[item] = options[item])
		}
	},
	actions: {
		// 自动登录获取用户状态
		async codeSession({
			commit,
			state
		}, options) {
			var result = await login();
			let {
				code
			} = result;
			
			// 相关请求
			result = await request({
				url: "/customer/code2Session/",
				method: "post",
				data: {
					code,
					appid: appId,
				}
			});
			if (result.code != 0) return;
			let {
				openid,
				bind,
				customer_id = '',
				face = '',
				name = '',
				tel = '',
				token = '',
				cart_count=''
			} = result.data; //bind
			if (token) uni.setStorageSync('TOKEN', token);
			commit('increment', {
				appId,
				openid,
				cart_count,
				customer_id,
				bind,
				face,
				name,
				tel
			});
		},
		// 快捷登录
		async wxbind({
			commit,
			state
		}, options) {
			let {
				encryptedData,
				iv
			} = options;
			if( !encryptedData || !iv) return false;
			let {
				appId,
				openid
			} = state;
				let referrer=uni.getStorageSync('referrer') || '';
			var result = await request({
				url: "/customer/wxbind/",
				method: "post",
				data: {
					encryptedData,
					iv,
					appid: appId,
					openid,referrer
				}
			});
			if (result.code != 0) return;
			let {
				customer_id,
				face,
				name,
				tel,
				token
			} = result.data;
			uni.setStorageSync('TOKEN', token);
			commit('increment', {
				customer_id,
				bind: 1,
				face,
				name,
				tel,
				appId,
				openid
			});
		},
		// 用户更新资料
		async getUserProfile({
			commit,
			state
		}, options) {
			var result = await getUserProfile("完善用户登录资料！");
			let {
				encryptedData,
				iv
			} = result;
			let {
				appId,
				openid
			} = state;
			result = await request({
				method: "post",
				url: "/customer/setUserInfo/",
				data: {
					encryptedData,
					iv,
					appid: appId,
					openid
				}
			})
			if (result.code != 0) return;
			let {
				face,
				name
			} = result.data;
			// 相关请求
			commit('increment', {
				face,
				name
			});
		}
	},
	modules: {
		requestList,
		addressDefault
	},
})

export default store
