import axios from 'axios';
import { token } from '@/common/token';
import vm from '@/main';

const code = {
    authorization: '00',
    error: '02',
    success: '01',
}

axios.defaults.baseURL = process.env.BASE_URL;

/**
 * 最终直接根据url名称调用接口方法
 * 例如
 * import { apis } from '@/api'
 * apis.getItemGroupType(parmas).then(...)
 */
import urls from './requests';

const apis = {}

for (let key in urls) {
    apis[key] = (params = {}) => {
        return new Promise((reslove, reject) => {
            let instance = axios
                .create({
                    headers: {
                        Authorization: 'Bearer ' + token.value
                    }
                });

            instance.interceptors.response.use((res) => {
                if (res.data.code === code.authorization) {
                    token.value = '';
                    // vm.$router.replace({
                    //     path: '/login'
                    // }).catch(err => { });
                }
                return res;
            }, (err) => {
                return Promise.reject(err);
            });

            instance
                .post(urls[key], params)
                .then(({ data }) => {
                    if (data.code === code.success) {
                        reslove(data);
                    } else {
                        if (vm.version.beta) {
                            alert(data.message);
                        }
                        reject(data);
                    }
                })
                .catch(err => {
                    if (process.env.PROD) {
                        vm.$dialog.alert({ message: '发生错误，请联系管理员' });
                    } else {
                        console.warn(err, urls[key]);
                    }
                });
        })
    }
}

export {
    axios,
    apis,
    code
};
