import Vue from 'vue';
import Vuex from 'vuex';
import http from './plugins/http';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        tableHeight: 0,
        fetchingData: false,
        userInfo: null,
        organization: null,
        isORGANIZER: false,
        psdEsay: false
    },
    mutations: {
        updatepsdEsay(state, psdEsay) {
            state.psdEsay = psdEsay;
        },
        updateTableHeight(state, height) {
            state.tableHeight = height;
        },
        updateFetchingData(state, fetchingData) {
            state.fetchingData = fetchingData;
        },
        updateUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },
        updateOrganization(state, organization) {
            state.organization = organization;
        },
        updateIsORGANIZER(state, isORGANIZER) {
            state.isORGANIZER = isORGANIZER;
        }
    },
    actions: {
        getUserInfo(context) {
            return http.axios
                .get('/user/my')
                .then(res => {
                    context.commit('updateUserInfo', res.data);
                    let flag = res.data.authorities.find(item => {
                        return item.name == 'ROLE_ORGANIZER';
                    });
                    context.commit('updateIsORGANIZER', !!flag);
                    if (flag) {
                        return http.axios.get('/organization/getByUserId/' + res.data.id);
                    } else {
                        return Promise.resolve();
                    }
                })
                .then(res => {
                    if (res) {
                        context.commit('updateOrganization', res.data);
                    } else {
                        context.commit('updateOrganization', null);
                    }
                    return Promise.resolve();
                })
                .catch(() => {
                    return Promise.reject();
                });
        },
        checkOrganization(context) {
            // console.log(context.state.organization);
            if (context.state.organization) {
                if (
                    context.state.organization.owner &&
                    context.state.organization.ownerEmail &&
                    context.state.organization.ownerPhone &&
                    context.state.organization.privacyPolicy &&
                    context.state.organization.idNo &&
                    context.state.organization.uscc &&
                    context.state.organization.district &&
                    context.state.organization.address &&
                    context.state.organization.businessLicense
                ) {
                    return Promise.resolve();
                } else {
                    return Promise.reject();
                }
            } else {
                return Promise.resolve();
            }
        }
    }
});
