import {
    createStore
} from 'vuex';
import http from '../plugins/http';

export default createStore({
    state: {
        finished: false,
        userInfo: null,
        firstUrl: '',
        couponInfo: null,
        invitor: null,
        review: false,
        reviewPay: false,
        from: '',
        inviteCode: '',
        loginBackUrl: '',
        productId: '',
        netTime: 0,
        usedBuy: true,
        routerLogin: false,
    },
    mutations: {
        setFinished(state, finished) {
            state.finished = finished;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },
        setFirstUrl(state, url) {
            state.firstUrl = url;
        },
        setCouponInfo(state, couponInfo) {
            state.couponInfo = couponInfo;
        },
        setInvitor(state, invitor) {
            state.invitor = invitor;
        },
        setProductId(state, productId) {
            state.productId = productId;
        },
        setReview(state, review) {
            state.review = review;
        },
        setReviewPay(state, reviewPay) {
            state.reviewPay = reviewPay;
        },
        setFrom(state, from) {
            state.from = from;
        },
        setInviteCode(state, inviteCode) {
            state.inviteCode = inviteCode;
        },
        setLoginBackUrl(state, loginBackUrl) {
            state.loginBackUrl = loginBackUrl;
        },
        setNetTime(state, netTime) {
            state.netTime = netTime;
        },
        setUsedBuy(state, usedBuy) {
            state.usedBuy = usedBuy;
        },
        setRouterLogin(state, routerLogin) {
            state.routerLogin = routerLogin
        }
    },
    actions: {
        getUserInfo(context) {
            return http.http
                .get('/user/my')
                .then(res => {
                    http.axios.defaults.headers.common['X-Username'] = res.id;
                    context.commit('setUserInfo', res);
                    return Promise.resolve(res);
                })
                .catch(() => {
                    context.commit('setUserInfo', null);
                    return Promise.reject();
                });
        },
        getTime(context) {
            http.http.get('/auth/getTime').then(res => {
                context.commit('setNetTime', Number(res) - new Date().getTime());
            });
        },
        getUsedBuy(context) {
            http.http.get('/sysConfig/get/used_buy').then(res => {
                if (res.value === '0') {
                    context.commit('setUsedBuy', false);
                } else {
                    context.commit('setUsedBuy', true);
                }
            });
        }
    },
    modules: {}
});