import {APP_NAME, SERVER_API_DOMAIN, SERVER_API_HTTP_TYPE, SERVER_API_PORT, SERVER_API_VERSION, REQUEST_URL} from "./config";
import userInfo from './userInfo';
import tool from './tool';
import axios from './axiosPlugin'
import ElementUI from 'element-ui'

const network = {
    loginGetAccessToken(adminName, password){
        let promise = new Promise((resolve, reject) => {
            // if(userInfo.hasLogin()){
            //     reject('E40005');
            //     return false;
            // }
            axios.post(`${REQUEST_URL}oauths/login?suppress_response_code=1`, {
                LoginForm : {
                    adminName,
                    password
                }
            }).then(response => {
                // 更新本地accessToken
                userInfo.accessToken(response.accessToken);
                userInfo.accessTokenExpiresIn(response.accessTokenExpiresIn);
                userInfo.accessTokenUpdateAt(response.accessTokenUpdateAt);
                userInfo.refreshToken(response.refreshToken);
                userInfo.refreshTokenExpiresIn(response.refreshTokenExpiresIn);
                userInfo.refreshTokenUpdateAt(response.refreshTokenUpdateAt);
                userInfo.loginTimestamp(response.accessTokenUpdateAt);
                // 成功
                resolve(response);
            }).catch(error => {
                //console.log('登录获取数据错误');
                userInfo.clear();
                reject(error);
            });
        });
        return promise;
    },
    updateAccessToken(){
        let promise = new Promise((resolve, reject) => {
            if(!userInfo.hasLogin()){
                //console.log('尚未登录');
                //userInfo.clear();
                reject('E40004');
                return false;
            }
            // 比较本地accessToken是否还有效
            if(userInfo.accessToken() && userInfo.accessTokenExpiresIn() && parseInt(userInfo.accessTokenExpiresIn()) + parseInt(userInfo.accessTokenUpdateAt()) - 30 > parseInt(tool.getTimestamp())){
                // 有效
                //console.log('accessToken有效');
                resolve(userInfo.accessToken());
                return true;
            } else {
                // 已失效，去更新
                let refreshToken = userInfo.refreshToken();
                let refreshTokenExpiresIn = userInfo.refreshTokenExpiresIn();
                let refreshTokenUpdateAt = userInfo.refreshTokenUpdateAt();
                if(refreshToken && refreshTokenExpiresIn && parseInt(refreshTokenExpiresIn) - 30 + parseInt(refreshTokenUpdateAt) > parseInt(tool.getTimestamp())) {
                    // 有效，去更新
                    axios.get(`${REQUEST_URL}oauths/refresh-token?suppress_response_code=1&refresh-token=${refreshToken}`).then(response => {
                        // 更新本地accessToken
                        userInfo.accessToken(response.accessToken);
                        userInfo.accessTokenExpiresIn(response.accessTokenExpiresIn);
                        userInfo.accessTokenUpdateAt(response.accessTokenUpdateAt);
                        userInfo.refreshToken(response.refreshToken);
                        userInfo.refreshTokenExpiresIn(response.refreshTokenExpiresIn);
                        userInfo.refreshTokenUpdateAt(response.refreshTokenUpdateAt);
                        // 成功
                        //console.log('accessToken更新成功，refreshToken更新为：'+userInfo.refreshToken());
                        //console.log('accessToken更新成功，refreshToken的更新时间为：'+tool.formatDate(userInfo.refreshTokenUpdateAt()));
                        //console.log('accessToken更新成功，refreshToken的有效时间为：'+userInfo.refreshTokenExpiresIn());
                        resolve(response.accessToken);
                    }).catch(error => {
                        //userInfo.clear();
                        //console.log(error);
                        reject('E40001');
                    });
                } else {
                    //console.log('refreshToken已失效');
                    userInfo.clear();
                    // 失效
                    reject('E40003');
                    return false;
                }
            }
        });
        return promise;
    },
    getUserInfo(callback, errorback){
        let promise
        this.updateAccessToken().then(accessToken => {
            return promise = new Promise((resolve, reject) => {
                //let accessToken = userInfo.accessToken();
                axios.get(`${REQUEST_URL}oauths/info?suppress_response_code=1&access-token=${accessToken}`).then(response => {
                    // 更新本地userInfo
                    userInfo.userId(response.ID);
                    userInfo.adminName(response.ADMIN_NAME);
                    userInfo.baseData({roleId: response.ROLE_ID});
                    // 成功
                    resolve(response);
                }).catch( error => {
                    reject(error);
                });
            });
        }).then(response => {
            callback(response);
        }).catch(error => {
            //console.log('获取信息失败');
            errorback(error);
        });
        //return promise;
    },
    getMenu(callback, errorback){
        let promise
        this.updateAccessToken().then(accessToken => {
            return promise = new Promise((resolve, reject) => {
                //let accessToken = userInfo.accessToken();
                axios.get(`${REQUEST_URL}oauths/menu?suppress_response_code=1&access-token=${accessToken}`).then(response => {
                    // 成功
                    resolve(response);
                }).catch( error => {
                    reject(error);
                });
            });
        }).then(response => {
            callback(response);
        }).catch(error => {
            //console.log(error);
            errorback(error);
        });
        //return promise;
    },
    getData(route, callback, errorback){
        let promise
        this.updateAccessToken().then(accessToken => {
            return promise = new Promise((resolve, reject) => {
                //let accessToken = userInfo.accessToken();
                axios.get(`${REQUEST_URL}${route}?suppress_response_code=1&access-token=${accessToken}`).then(response => {
                    // 成功
                    resolve(response);
                }).catch( error => {
                    reject(error);
                });
            });
        }).then(response => {
            callback(response);
        }).catch(error => {
            error = tool.errorHandle(error);
            ElementUI.Message.error(error.message);
            if(errorback !== undefined){
                errorback(error);
            }
        });
    },
    postData(route, data, callback, errorback){
        let promise
        this.updateAccessToken().then(accessToken => {
            return promise = new Promise((resolve, reject) => {
                //let accessToken = userInfo.accessToken();
                axios.post(`${REQUEST_URL}${route}?suppress_response_code=1&access-token=${accessToken}`, data).then(response => {
                    // 成功
                    resolve(response);
                }).catch( error => {
                    reject(error);
                });
            });
        }).then(response => {
            callback(response);
        }).catch(error => {
            error = tool.errorHandle(error);
            ElementUI.Message.error(error.message);
            if(errorback !== undefined){
                errorback(error);
            }
        });
    }

}

export default network;