import {
	getStore,
	setStore
} from '@/untils/store.js'
import {
	getVipCode,
	bindVip
} from "@/api/vip.js"

const user = {
	state: {
		vipCode: getStore({
			name: 'vipCode'
		}) || '0',
	},
	getters: {
		isVip(state) {
			return state.vipCode != '0'
		},
		vipCode(state) {
			return state.vipCode
		}
	},
	actions: {
		getVipCode({
			commit,
			getters
		}, idNumber) {
			return new Promise((resolve, reject) => {
				if (getters.isVip) {
					resolve();
				} else if(getters.authInfo.idNumber) {
					getVipCode(getters.authInfo.idNumber).then(res => {
						commit('SET_VIPCODE', res.data.data);
						resolve();
					}).catch(error => {
						reject(error);
					})
				} else {
					resolve();
				}
			})
		},
		bindVipCode({
			commit,
			getters
		}, code) {
			return new Promise((resolve, reject) => {
				bindVip(getters.authInfo.idNumber, code).then(res => {
					commit('SET_VIPCODE', code);
					resolve();
				}).catch(error => {
					reject(error);
				})
			})
		}
	},
	mutations: {
		SET_VIPCODE: (state, code) => {
			state.vipCode = code;
			setStore({
				name: 'vipCode',
				content: code,
				type: 'session'
			})
		}
	}
}
export default user
