// @ts-nocheck
import { Component } from 'react'
import { DeviceEventEmitter } from 'react-native';
import { toast, BaseUrl, isIos, toastShort, clearToast, version } from './base';
// import Store from './Store';
// import { store } from "../reducx/store/store";

// import { navigate, reset } from '../../NavigationService';
// import { getUserInfo } from '../reducx/action/action';
// import EVENT_KEY from './event-key';
import SplashScreen from 'react-native-splash-screen';
import { EVENT_KEY } from './event-key';
import Store from './Store';
// 
/**           
 * GET 请求时，拼接请求URL
 * @param url 请求URL
 * @param params 请求参数
 * @returns {*}
 */
const handleUrl = url => params => {
    if (params) {
        let paramsArray = []
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key])));
        if (url.search(/\?/) === -1) {
            typeof (params) === 'object' ? url += '?' + paramsArray.join('&') : url;
        } else {
            url += '&' + paramsArray.join('&');
        }
    };
    console.log('GetUrl', BaseUrl + url)
    return BaseUrl + url;
}


/**
 * fetch 网络请求超时处理
 * @param original_promise 原始的fetch
 * @param timeout 超时时间 30s
 * 
 */
const timeoutFetch = (original_fetch, timeout = 10 * 1000) => {
    let timeoutBlock = () => { }
    let timeout_promise = new Promise((resolve, reject) => {
        timeoutBlock = () => {
            // 请求超时处理
            reject('请求超时');
        }
    })

    // Promise.race(iterable)方法返回一个promise
    // 这个promise在iterable中的任意一个promise被解决或拒绝后，立刻以相同的解决值被解决或以相同的拒绝原因被拒绝。
    let abortable_promise = Promise.race([
        original_fetch,
        timeout_promise
    ])

    setTimeout(() => {
        timeoutBlock()
    }, timeout)

    return abortable_promise
}

/**
 * 网络请求工具类
 */
export default class HttpUtils extends Component {

    /**
     * 基于fetch 封装的GET 网络请求
     * @param url 请求URL
     * @param params 请求参数
     * @returns {Promise}
     */
    static getStatusCode = null;

    static postStatusCode = null;

    static clearUserCache = (url) => {
        toastShort("登陆信息已过期，请您重新登陆");
        // clearToast();
        Store.removeBaseData('userMsg')
            .then(res => {
                SplashScreen.hide(); // 关闭启动屏幕
                // store.dispatch(getUserInfo(null));
                // reset('Login', { canBack: false });
            })
            .catch(err => {
                // store.dispatch(getUserInfo(null));
                // reset('Login', { canBack: false });
            })
    };

    static onNetWorkError = () => {
        DeviceEventEmitter.emit(EVENT_KEY.networkError)
        toast('请检查您的网络设置，或在系统设置中查看是否已允许海囤生活App访问您的网络')
    };

    static getRequest = (url, params?= {}, needToken?: boolean, baseUrl?: 'api' | 'admin') => {
        console.log('get参数', params)
        // let state = store.getState();
        //console.log('http_redux_state', store.getState());
        // let info = store.getState().deviceInfo;
        // ////console.log("测试info", info)
        // ////console.log('测试http + redux参数', store.getState().deviceInfo);
        let headers = new Headers({
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        });
        headers.append('sign', 'app_sign_123456');                   // App签名
        headers.append('os_platform', isIos() ? 'ios' : 'android');  // 系统类型
        headers.append('version', '1.2.1');
        // if (state && state.userInfo) {
        //     headers.append('token', state.userInfo.token)
        // };
        // console.log("token:", state && state.userInfo && state.userInfo.token)
        // if (state && state.deviceInfo) {
        //     headers.append('device_union_id', state.deviceInfo.uniqueId);  // 系统类型
        //     headers.append('os_version', state.deviceInfo.sysVersion);
        // } else {
        //     headers.append('device_union_id', 'get_failed');  // 系统类型
        //     headers.append('os_version', 'get_failed')
        // };
        let code = null
        return timeoutFetch(fetch(handleUrl(url)(params), {
            method: 'GET',
            headers: headers,
            mode: 'cors'
        })).then(response => {
            code = response.headers.map['htsh_code'] ? Number(response.headers.map['htsh_code']) : -10000;
            return response.json();
        }).then(response => {
            if (code === -10000) {
                response.msg = '网络连接超时，请您稍后重试哦'
            };
            if (code === 10316) {
                this.clearUserCache(url);
                return response;
            }
            response.code = code;
            return response;
        }).catch(error => {
            if (error == 'TypeError: Network request failed') {
                this.onNetWorkError();
            } else if (error === "请求超时") {
                toastShort('服务器繁忙，请您稍后重试')
            } else {
                toast("网络出错了,请您稍后重试");
            }
        })
    }

    /**
     * 基于fetch 的 POST 请求
     * @param url 请求的URL
     * @param params 请求参数
     * @returns {Promise}
     */
    static postRequest = (url, params = {}, needToken?: boolean, urlType?= 'api') => {
        // let state = store.getState();
        //console.log('http_redux_state', store.getState());
        let headers = new Headers({
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        });
        headers.append('sign', 'app_sign_123456');                   // App签名
        headers.append('os_platform', isIos() ? 'ios' : 'android');  // 系统类型
        headers.append('version', '1.2.1');
        let code = null;
        // if (state && state.userInfo && needToken) {
        //     headers.append('token', state.userInfo.token)
        // };
        // if (state && state.deviceInfo) {
        //     headers.append('device_union_id', state.deviceInfo.uniqueId);  // 系统类型
        //     headers.append('os_version', state.deviceInfo.sysVersion);
        // } else {
        //     headers.append('device_union_id', 'get_failed');  // 系统类型
        //     headers.append('os_version', 'get_failed')
        // };
        let BASE_URL = '';
        if (urlType === 'api') {
            BASE_URL = BaseUrl;
        } else {
            let server = '';
            switch (version.type) {
                case 1:
                    server = 'test-';
                    break;
                case 2:
                    server = 'release-'
                    break;
                case 3:
                case 4:
                    server = '';
                    break;
                default:
                    server = ''
            }
            BASE_URL = `https://${server}admin-api.haitunshenghuo.com`;
        }
        console.log("urlType", urlType)
        let fetchUrl = BASE_URL + url;
        // console.log('params:', params)
        console.log('fetchUrl:', fetchUrl)
        return timeoutFetch(fetch(fetchUrl, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(params)
        })).then(response => {
            if (response.ok) {
                code = response.headers.map['htsh_code'] ? Number(response.headers.map['htsh_code']) : -10000;
                return response.json();
            } else {
                toast("网络出错了，请稍后重试")
            }
        }).then(response => {
            if (code === -10000) {
                response.msg = '网络连接超时，请您稍后重试哦'
            };
            if (code === 10316) {
                this.clearUserCache(fetchUrl);
                return response;
            }
            response.code = code;
            return response;
        }).catch(error => {
            if (error == 'TypeError: Network request failed') {
                this.onNetWorkError();
            } else if (error === "请求超时") {
                toastShort('服务器繁忙，请您稍后重试')
            } else {
                toast("网络出错了,请您稍后重试");
            }
        })
    }

    /**
     * 基于fetch 的 POST 请求
     * @param url 请求的URL
     * @param params 请求参数
     * @returns {Promise}
     * 
     */
    static postRequestWithFormData = (url, params = {}, needToken?: boolean, urlType?= 'api') => {
        let formdata = new FormData;
        // let state = store.getState();
        let code = null;
        ////console.log('http', store.getState().msg);
        let headers = new Headers({
            'Accept': 'multipart/form-data',
            'Content-Type': 'multipart/form-data',
        });
        headers.append('sign', 'app_sign_123456');                   // App签名
        headers.append('os_platform', isIos() ? 'ios' : 'android');  // 系统类型
        headers.append('version', '1.2.1');
        // if (state && state.userInfo && needToken) {
        //     headers.append('token', state.userInfo.token)
        // };
        // if (state && state.deviceInfo) {
        //     ////console.log("设备信息");
        //     headers.append('device_union_id', state.deviceInfo.uniqueId);  // 系统类型
        //     headers.append('os_version', state.deviceInfo.sysVersion);
        // } else {
        //     ////console.log("没有获取到设备信息");
        //     headers.append('device_union_id', 'get_failed');  // 系统类型
        //     headers.append('os_version', 'get_failed')
        // }
        let BASE_URL = '';
        if (urlType === 'api') {
            BASE_URL = BaseUrl;
        } else {
            let server = '';
            switch (version.type) {
                case 1:
                    server = 'test-';
                    break;
                case 2:
                    server = 'release-'
                    break;
                case 3:
                case 4:
                    server = '';
                    break;
                default:
                    server = ''
            }
            BASE_URL = `https://${server}admin-api.haitunshenghuo.com`;
        }
        let fetchUrl = BASE_URL + url;
        console.log(fetchUrl)
        formdata = new FormData();
        for (let key in params) {
            formdata.append(key, params[key])
        };
        console.log("formdata参数", formdata)
        return timeoutFetch(fetch(fetchUrl, {
            method: 'POST',
            headers: headers,
            body: formdata
        })).then(response => {
            if (response.ok) {
                code = response.headers.map['htsh_code'] ? Number(response.headers.map['htsh_code']) : -10000;
                return response.json()
            } else {
                toast("网络出错了，请稍后重试");
            }
        }).then(response => {
            if (code === -10000) {
                response.msg = '网络连接超时，请您稍后重试哦'
            };
            response.code = code;
            //console.log(response)
            if (code === 10316) {
                this.clearUserCache(fetchUrl);
                return response;
            };
            // code = null;
            return response
        }).catch(error => {
            console.log('postwithformdateError', error)
            if (error == 'TypeError: Network request failed') {
                this.onNetWorkError();
            } else if (error === "请求超时") {
                toastShort('服务器繁忙，请您稍后重试')
            } else {
                toast("网络出错了,请您稍后重试");
            }
        })
    }
}


export class Http {
    static getRequest = ( ) => {
        timeoutFetch(handleUrl())
    }

}


