import axios from 'axios'
import Qs from 'qs'
import ajaxurl from './ajaxurl'
import storage from './storage'

var IMEI = storage.getItem('IMEI') || uuid(16, 16)
storage.setItem('IMEI', IMEI)

// let macAddr
// address.mac(function (err, addr) {
//     macAddr = addr
//     if (err) {
//         throw err
//     }
// })

function createAxios(platform) {
    let loginDoctorCache = storage.getItem(storage.API_LOGIN_DOCTOR) || {
        id: '', uid: '', token: ''
    }
    let axiosInstance = axios.create({
        // config里面有这个transformRquest，这个选项会在发送参数前进行处理。
        // 这时候我们通过Qs.stringify转换为表单查询参数
        // `transformRequest`允许请求的数据在传到服务器之前进行转化。
        // 这个只适用于`PUT`,`GET`,`PATCH`方法。
        // 数组中的最后一个函数必须返回一个字符串，一个`ArrayBuffer`,或者`Stream`
        transformRequest: [function (data) {
            data = Qs.stringify(data)
            return data
        }],
        // 设置Content-Type
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'userAgent': `{'id': '${loginDoctorCache.id}','uid': '${loginDoctorCache.uid}','imei': '${IMEI}','token': '${loginDoctorCache.token}','platform': '${platform}' }`
        },
        timeout: 60000
    })

    return axiosInstance
}

function getAxiosInstance(method, configs) {
    let accessable = true,
        instance = null,
        promise = null
    let axiosInstance = createAxios(4)
    if (accessable) {
        configs[0] = ajaxurl.useServer + configs[0]
        instance = axiosInstance[method]
        if (method === 'get') {
            configs[1] = {
                params: configs[1]
            }
            promise = instance.apply(axiosInstance, configs)
        } else {
            promise = instance.apply(axiosInstance, configs)
        }
        return promise
        // .then(function (res) {
        //     let result = res.data,
        //         status = result.status

        //     if (status === 200) {
        //         return res
        //     } else if (status === 997) {
        //         return alert('当前未登录状态，请登录')
        //     } else if (status === 998) {
        //         return alert('登录超时，请检查网络重新登录')
        //     } else if (status === 999) {
        //         return alert('异地登录，请确认唯一登录')
        //     } else {
        //         return alert('错误' + status + '，请联系客服')
        //     }
        // })
    } else {
        setTimeout(function () {
            throw Error('无访问权限')
        }, 500)

        return null
    }
}
function getIMAxiosInstance(method, configs) {
    let accessable = true,
        promise = null
    let axiosInstance = createAxios(3)
    if (accessable) {
        configs[0] = ajaxurl.imServer + configs[0]
        if (method === 'get') {
            configs[1] = {
                params: configs[1]
            }
            promise = axiosInstance[method].apply(axiosInstance, configs)
        } else {
            promise = axiosInstance[method].apply(axiosInstance, configs)
        }
        return promise
    } else {
        setTimeout(function () {
            throw Error('无访问权限')
        }, 500)

        return null
    }
}
function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if(len) {
        // Compact form  
        for(i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        // rfc4122, version 4 form  
        var r;

        // rfc4122 requires these characters  
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as  
        // per rfc4122, sec. 4.1.5  
        for(i = 0; i < 36; i++) {
            if(!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

export default {
    get() {
        return getAxiosInstance('get', Array.prototype.slice.call(arguments))
    },
    post() {
        return getAxiosInstance('post', Array.prototype.slice.call(arguments))
    },
    put() {
        return getAxiosInstance('put', Array.prototype.slice.call(arguments))
    },
    delete() {
        return getAxiosInstance('delete', Array.prototype.slice.call(arguments))
    },
    imget() {
        return getIMAxiosInstance('get', Array.prototype.slice.call(arguments))
    },
    impost() {
        return getIMAxiosInstance('post', Array.prototype.slice.call(arguments))
    },
    imput() {
        return getIMAxiosInstance('put', Array.prototype.slice.call(arguments))
    },
    imdelete() {
        return getIMAxiosInstance('delete', Array.prototype.slice.call(arguments))
    }
}

// error.message: Request failed with status code 502
// error.stack
/*
    "Error: Request failed with status code 502
        at createError (http://localhost:3000/commons.bundle.js:11076:15)
        at settle (http://localhost:3000/commons.bundle.js:11933:12)
        at XMLHttpRequest.handleLoad (http://localhost:3000/commons.bundle.js:10911:7)"
    */
// error.request.responseURL: "http://ehr.yihu.com/wlyy/weixin/getSign"
// error.request.readyState: 4
// error.request.status: 502
// error.request.responseType: ""
/*
    error.request.responseText:
    "<html>
    <head><title>502 Bad Gateway</title></head>
    <body bgcolor="white">
    <center><h1>502 Bad Gateway</h1></center>
    <hr><center>nginx/1.9.5</center>
    </body>
    </html>
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    <!-- a padding to disable MSIE and Chrome friendly error page -->
    "
    */
/*
    JSON.stringify(error.response.config):
    "{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, *\/*","Content-Type":"application/x-www-form-urlencoded"},"method":"post","url":"http://ehr.yihu.com/wlyy/weixin/getSign","data":"pageUrl=http%3A%2F%2Flocalhost%3A3000%2Fviews%2Fdemo%2Fwx.html"}"
*/
// error.response.status: 502
/*
    JSON.stringify(error.response.headers):
    '{"date":"Wed, 28 Jun 2017 08:10:52 GMT","server":"nginx","connection":"keep-alive","content-length":"574","content-type":"text/html; charset=utf-8"}'
    */
// error.response.statusText: "Bad Gateway"
// error.response.data 与 error.request.responseText 一样
