import axios from 'axios';
import { Toast } from 'antd-mobile';
var qs =  require('qs');

const instance = axios.create();
const token = localStorage.getItem("token");

let defaultHeaders = {
    token,
  };

  const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（用户名或密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
  };

export const createAPI = (baseURL) => {
    return (conf = {}) => {
        let opts = conf.opts || {};
        let urlParams = '';

        let headers = { ...defaultHeaders, ...opts.headers, token: conf.token};
        if (conf.opts) {
            urlParams = "?";
            urlParams += qs.stringify(conf.opts)
        }


        return instance(Object.assign({}, {
            url: conf.url + urlParams,
            baseURL: baseURL,
            method: conf.method,
            data: conf.payload || null,
            headers,
        }))
            .then(function (response) {
                response = response.data || response.tree;

                if (!response || !(response.data || response.tree)) {
                    // response.status === 'failure' && (window.location.href = '/login')
                    response.code === 'idt-jwt-500' && (window.location.href = '/login')
                    console.log('response出错, 无返回数据！', response);
                    Toast.fail(response.message)
                    // return false;
                };
                if (response.data && response.data.errorMessage) {
                    Toast.fail(response.data.errorMessage);
                    return false;
                }
                // 保存到本地
                if (response && response.data && response.data.token) {
                    const userInfo = {
                        userealname: response.data.userealname,
                        useName: response.data.userName,
                        xb: response.data.xb,
                        gzrq: response.data.gzrq,
                        csrq: response.data.csrq,
                        gzdh: response.data.gzdh,
                        yddh: response.data.yddh,
                        sjxh: response.data.sjxh,
                        email: response.data.email,
                    };
                    localStorage.setItem('userInfo', JSON.stringify(userInfo))
                    defaultHeaders = {
                        token: response.data.token,
                    };
                    localStorage.setItem("token", response.data.token);
                }
                if (response && response.data && response.data.developer) {
                    localStorage.setItem("developer", response.data.developer);
                }
                if (response && response.data && response.data.leftOperateBar) {
                    localStorage.removeItem("menu");
                    const menu = response.data.leftOperateBar.map(item => ({ icon: item.imgType, text: item.nodeName, id: item.id, children: item.children }))
                    menu.length > 0 && localStorage.setItem("menu", JSON.stringify(menu));
                }

                if (response.data || response.tree || response.success) {
                    return response.data ? response.data : response;
                } else {
                    return false;
                }

            })
            .catch(error => {
                if (error.response) {
                    const { status, statusText } = error.response;
                    const errortext = codeMessage[status] || statusText;

                    if (status === 401) {
                        // TODO 重新登录
                        // history.push('/user/login');
                        Toast.fail(errortext);
                        return false;
                    } else if (status === 400 || status > 401) {
                        Toast.fail(errortext);
                    }
                }
                return false;
            });
    };
}

export const convertRESTAPI = (url, opts) => {
    if (!opts) return url;

    const pathKeys = Object.keys(opts);

    pathKeys.forEach((key) => {
        const r = new RegExp('(:' + key + '|{' + key + '})', 'g');
        url = url.replace(r, opts[key]);
    });
    return url;
}


