import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex); //vue的插件机制

import api from '@/api/api.js'
import { date } from '../uni_modules/uv-ui-tools/libs/function/test';

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: {
		configList: {}, //配置列表
		shop : true, 
		userInfo : {}, //用户信息
		shopData : {},
		buy : {},
		customerPhone : '',//客服电话
		productDetail : {},//商品详情用于中转
		cartInfo : {},//采购商下单的时候供应商开户行信息
		pic : '',//清关服务图片
	},
	getters: {
		// 角色 true 为供应商 false 为采购商
		userShop(state){
			return state.shop
		},
		userInfo(state){
			return state.userInfo
		},

	},
	mutations: {
		// 初始化配置
		initConfig(state){
			api('getConfig', res => {
				if(res.code == 200){
					// state.configList = res.result
					
					res.result.forEach(n => {
						state.configList[n.name] = n
					})
				}
			})
			
			// let config = ['getPrivacyPolicy', 'getUserAgreement']
			// config.forEach(k => {
			// 	api(k, res => {
			// 		if (res.code == 200) {
			// 			state.configList[k] = res.result
			// 		}
			// 	})
			// })
		},
		login(state, form){
			uni.showLoading({
				title: '登录中...'
			})
			
			api('loginUser', form, res => {

				uni.hideLoading()

				if(res.code != 200){
					return
				}
				state.userInfo = res.result.userInfo
				state.buy = res.result.buy
				state.shopData = res.result.shop
				state.shop = !!res.result.shop
				uni.setStorageSync('token', res.result.token)
				
				if(!state.shopData && !state.buy){
					uni.reLaunch({
						url: '/pages_order/auth/selectionIdentity?back=no&'
					})
				}else{
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			})
		},
		// 获取个人信息
		getUserInfo(state){
			api('getImagePhoneOther', res => {
				if(res.code == 200){
					state.userInfo = res.result.my
					state.customerPhone = res.result.phone
					
					
					state.buy = res.result.buy
					state.shopData = res.result.shop
					state.pic = res.result.pic
					
					// 如果什么身份都没有，就去注册
					if(!state.shopData && !state.buy){
						uni.reLaunch({
							url: '/pages_order/auth/selectionIdentity?back=no&'
						})
					}
					
					// 没有供应商身份
					if(!state.shopData){
						state.shop = false
					// 没有采购商身份
					}else if(!state.buy){
						state.shop = true
					}
				}
			})
		},
		logout(state){
			uni.showModal({
				title: '确认退出登录吗',
				success(r) {
					if(r.confirm){
						state.userInfo = {}
						state.role = false
						uni.removeStorageSync('token')
						uni.redirectTo({
							url: '/pages/index/index'
						})
					}
				}
			})
		},
		setShop(state, date){
			state.shop = date
		},
	},
	actions: {},
})

export default store