import axios from 'axios';
import Setting from '../../../../setting';

const copyTo = (source, target) => {
    for (let key in source) {
        if (typeof source[key] === 'Object') {
            if (target == null) {
                target = {};
            }
            copyTo(source[key], target[key]);
        } else {
            target[key] = source[key];
        }
    }
};

/**
 * 系统信息
 * */
export default {
    namespaced: true,
    state: {
        // 配置信息
        ...Setting
    },
    getters: {
        get: state => {
            return state;
        }
    },
    actions: {
        /**
         * @description 加载配置
         * @param {Object} state vuex state
         */
        async init({ state, rootState, commit }) {
            // 根目录
            let base = process.env.VUE_APP_BASE_PATH;
            if (!base) {
                base = '';
            } else {
                base = '/' + base;
            }

            console.log(process.env);

            await axios
                .get(base + '/static/setting.json')
                .then(async res => {
                    if (res.data) {
                        copyTo(res.data, state);
                    }

                    // 更新API地址
                    axios.defaults.baseURL = state.apiBaseURL;

                    // 更新自定义样式
                    if (state.layout) {
                        for (let key in state.layout) {
                            rootState.admin.layout[key] = state.layout[key];
                        }
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }
    }
};
