import { Component } from 'react'
import { DeviceEventEmitter } from 'react-native';
import { toast, isIos, toastShort, clearToast, version, BaseUrl } 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';



//1
let header = (contentType?: any) => {
    let headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': contentType ? 'multipart/form-data' : 'application/json',
    });
    headers.append('sign', 'app_sign_123456');                   // App签名
    headers.append('os_platform', isIos() ? 'ios' : 'android');  // 系统类型
    headers.append('version', '1.2.1');
    console.log("headers：", headers)
    return headers
}

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;
}

//先定义延时函数
const delay = (timeOut = 8 * 1000) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject(new Error('网络超时'))
        }, timeOut);
    })
}

//fetch网络请求
const fetchPromise = (method, url, body?: any, isFile?: boolean) => {
    console.log("打印一下：", method, url)
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: method,
            body: isFile ? body : JSON.stringify(body),
            // headers: headers ? headers : {
            //     // 'Accept': 'application/json',
            //     'Content-Type': 'multipart/form-data'
            // },
        }).then((response) => {
            // if (response.status == 200) {
            //     return response.json();
            // } else {
            //     reject(new Error('服务器异常'));
            // }
            try {
                return response.json()
            } catch (error) {
                return error
            }
        }


        ).then((responseJson) => {
            // console.log("打印返回信息:", responseJson)
            if (responseJson && responseJson.code != 200) {
                toast(responseJson.msg)
                reject(responseJson.msg);
                return
            }
            resolve(responseJson);
        }).catch((err) => {
            toast(err)
            // console.log("err1", err)
            reject(new Error(err))
        })
    })
}

//race任务
const _fetch = (fetchPromise) => {
    return Promise.race([fetchPromise, delay()])
}

class HTTPUtil {
    static get = (url: string, params?: object) => {
        url = handleUrl(url, params)
        return _fetch(fetchPromise('Get', url));
    };

    static post = (url: string, params: any) => {
        url = BaseUrl + url
        console.log("打印参数", params)
        return _fetch(fetchPromise('Post', url, params))
        // let F = _fetch(fetchPromise('Post', url, params)).then(res => res).catch(err => toast(err))
        // return F
    }

    static postFile = (url, files: Array<string> | string, mulite?: boolean) => {
        url = BaseUrl + url
        let formData = new FormData();
        if (files.length == 0) {
            return
        }
        if (mulite) {
            for (var i = 0; i < files.length; i++) {
                var uri = files[i].uri
                var date = new Date()
                var name = date.getTime() + '.png'//用时间戳保证名字的唯一性
                let file = { uri: uri, type: 'multipart/form-data', name: name }
                formData.append('file', file)
            }
        }
        else {
            var uri = files
            var date = new Date()
            var name = date.getTime() + '.png'//用时间戳保证名字的唯一性
            let file = { uri: uri, type: 'multipart/form-data', name: name }
            formData.append('file', file)
        }
        let headers = {

        }
        return _fetch(fetchPromise('post', url, formData, true))
    }

}

export default HTTPUtil;