import $ from 'jquery';
import BDY from 'BDY';
import HiydSdk from 'extSdk';
import { Indicator } from 'mint-ui';
import { Toast } from 'mint-ui';
import { MessageBox } from 'mint-ui';

// require('../artDialog/artDialog');

//+++++++++++++++++++++++++++ hash 参数控制 +++++++++++++++++++++++++++++++++++++

/**
 * js获取url参数的值，(函数内部decodeURIComponent值)
 * @author benzhan
 * @param {string} name 参数名
 * @return {string} 参数值
 */
function getParam(name) {
    //先获取#后面的参数
    var str = document.location.hash.substr(2);
    var value = getParam2(name, str);
    if (value == null) {
        str = document.location.search.substr(1);
        value = getParam2(name, str);
    }

    return value;
};

function getParam2(name, str) {
    //获取参数name的值
    var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");

    //再获取?后面的参数
    var r = str.match(reg);
    if (r != null) {
        try {
            return decodeURIComponent(r[2]);
        } catch (e) {
            return null;
        }
    }
    return null;
};

/**
 * js设置url中hash参数的值, (函数内部encodeURIComponent传入的value参数)
 * @author benzhan
 * @param {string} name 参数名
 * @return {string} value 参数值
 */
function setParam(name, value, causeHistory) {
    var search = document.location.search.substr(1);
    if ($.type(name) === "object") {
        // 支持 setParam(value, causeHistory)的写法
        causeHistory = value;
        value = name;
        
        for (var key in value) {
            search = setParam2(key, value[key], search);
        }
    } else {
        search = setParam2(name, value, search);
    }

    if (causeHistory) {
        if (history.pushState) {
            history.pushState({}, null, "?" + search);
        } else {        		
            document.location.search = search;
        }
    } else {
        if (history.replaceState) {
            history.replaceState({}, null, "?" + search);
        } else {
            console.error("history.replaceState:" + history.replaceState);
        }
    }
};

function setParam2(name, value, str) {
    if ($.type(name) === "object") {
        // 支持 setParam(value, causeHistory)的写法
        str = value;
        value = name;
        for (var key in value) {
            str = setParam2(key, value[key], str);
        }
        return str;
    } else {
        var prefix = str ? "&" : "";
        var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
        var r = str.match(reg);
        value = encodeURIComponent(value);
        if (r) {
            if (r[2]) {
                var newValue = r[0].replace(r[2], value);
                str = str.replace(r[0], newValue);
            } else {
                var newValue = prefix + name + "=" + value + "&";
                str = str.replace(r[0], newValue);
            }
        } else {
            var newValue = prefix + name + "=" + value;
            str += newValue;
        }
        
        return str;
    }
};

function removeParam(name, causeHistory) {
    let search = document.location.search.substr(1);
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let r = search.match(reg);
    if (r) {
        if (r[1] && r[3]) {
            search = search.replace(r[0], '&');
        } else {
            search = search.replace(r[0], '');
        }
    }
    
    if (causeHistory) {
        document.location.search = search;
    } else {
        if (history.replaceState) {
            history.replaceState({}, null, "?" + search);
        } else {
            console.error("history.replaceState:" + history.replaceState);
        }
    }
};

function parseHash(strUrl) {
    strUrl = strUrl ? strUrl : document.location.search.substr(1);
    
    //获取参数name的值
    var reg = new RegExp("(^|!|#|&|\\?)(\\w*)=([^&]*)", "g");
    
    //先获取#后面的参数
    var r = reg.exec(strUrl);
    var datas = {};
    
    var i = 0;
    while (r != null) {
        datas[r[2]] = decodeURIComponent(r[3]);
        r = reg.exec(strUrl);            
    }
    
    return datas;
};
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++ get 和 post +++++++++++++++++++++++++++++++++++++   
function _getDefaultData(data) {
    data = data || {};

    var ouid = getCookie('ouid');
    ouid && (data.ouid = ouid);
    
    var defaultKeys = ['gym_id'];
    for (var i in defaultKeys) {
        var key = defaultKeys[i];
        var value = getLocalData(key);
        if (value && value != "undefined") {
            data[key] = value;
        }
    }
    
    for (var k in data) {
        var v = data[k];
        if (v == null || typeof v === 'undefined') {
            delete data[k];
        } else {
            if (typeof v === 'string') {
                data[k] = $.trim(v);
            }
        }
    }
    
    return data;
}

/**
 * option object {'cache', 'loading', 'onTimeout'}
 * cache为every、once
 */
function post(url, data, callback, option) {
    option = option || {};
    // 支持postCross(url, callback)的写法;
    if ( typeof data == 'function') {
        option = callback || {};
        callback = data;
        data = {};
    }

    data = _getDefaultData(data);

    var xhr = new XMLHttpRequest();
    BDY.xhrs.push(xhr);
    BDY.xhrCount++;

    xhr.index = BDY.xhrs.length;
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.withCredentials = true;
    // 兼容ios6.0会缓存
    if (window.KalaGame) {
        xhr.setRequestHeader("Cache-Control", "no-cache");
    }
    data = $.param(data);

    //获取cache的key
    if (option['cache']) {
        var cacheKey = 'ajaxCache-' + url + '?' + data;
        //如果有cache则不出现loading
        var isCached = _loadAjaxCache(cacheKey, callback);
        if (isCached) {
            option['loading'] = false;
            if (option['cache'] == "must") {
                return;
            }
        }
    }

    if (option['loading']) {
        xhr.timeout = 15000;
        showLoading();
    }

    xhr.send(data);
    xhr.ontimeout = option['onTimeout'] || function () {
        callback && callback({result:0, code:-11, msg:"网络超时，请重试"});
    };

    // 响应处理
    xhr.onload = function() {
        BDY.xhrs[xhr.index] = null;
        BDY.xhrCount--;

        option['loading'] && hideLoading();
        var objResult = _getAjaxResult(xhr.responseText);
        if (objResult['result'] && option['cache']) {
            var cache = localStorage.getItem(cacheKey);
            if (cache && cache == xhr.responseText) {
                // 网络返回跟缓存一致
                return;
            } else {
                localStorage.setItem(cacheKey, xhr.responseText);
            }
        }

        _handleResult(callback, objResult);
    };
}

function post2(url, data, callback, option) {
    option = option || {};
    // 支持postCross(url, callback)的写法;
    if ( typeof data == 'function') {
        option = callback || {};
        callback = data;
        data = {};
    }

    data = _getDefaultData(data);
    
    var xhr = new XMLHttpRequest();
    BDY.xhrs.push(xhr);
    BDY.xhrCount++;

    xhr.index = BDY.xhrs.length;
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // xhr.withCredentials = true;
    
    data = $.param(data);
    
    //获取cache的key
    if (option['cache']) {
        var cacheKey = 'ajaxCache-' + url + '?' + data;
        //如果有cache则不出现loading
        var isCached = _loadAjaxCache(cacheKey, callback);
        if (isCached) {
            option['loading'] = false;
            if (option['cache'] == "must") {
                return;
            }
        }
    }
    
    if (option['loading']) {
        xhr.timeout = 15000;
        showLoading();
    }
    
    xhr.send(data);
    xhr.ontimeout = option['onTimeout'] || function () {
        callback && callback({result:0, code:-11, msg:"网络超时，请重试"});
    };

    // 响应处理
    xhr.onload = function() {
        BDY.xhrs[xhr.index] = null;
        BDY.xhrCount--;

        option['loading'] && hideLoading();
        var objResult = _getAjaxResult(xhr.responseText);
        if (objResult['result'] && option['cache']) {
            var cache = localStorage.getItem(cacheKey);
            if (cache && cache == xhr.responseText) {
                // 网络返回跟缓存一致
                return;
            } else {
                localStorage.setItem(cacheKey, xhr.responseText);
            }
        }
        
        _handleResult(callback, objResult);
    };
}

function get(url, callback, option) {
    option = option || {};

    var xhr = new XMLHttpRequest();
    BDY.xhrs.push(xhr);
    BDY.xhrCount++;

    var data = {};
    _getDefaultData(data);
    for (var key in data) {
        if (!getParam2(key, url)) {
            url += url.indexOf('?') >= 0 ? '&' : '?';
            url += key + '=' + data[key];
        }
    }

    xhr.url = url;
    option['loading'] && showLoading();
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) {
            return;
        }

        BDY.xhrs[xhr.index] = null;
        BDY.xhrCount--;

        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && location.protocol == 'file:')) {
            option['loading'] && hideLoading();
            if (option['type'] == 'text') {
                callback(xhr.responseText);
            } else {
                callback(_getAjaxResult(xhr.responseText));
            }
        }
    };
    xhr.open("GET", url);
    // xhr.withCredentials = true;
    xhr.send();
}

function _getAjaxResult(text) {
    var objResult = {};
    var objError = {
        result : 0,
        msg : "系统繁忙，请稍后再试！"
    };

    try {
        objResult = JSON.parse(text);
        if (typeof objResult !== 'object' || objResult === null) {
            objResult = objError;
        }
    } catch (ex) {
        //非json的处理
        objResult = objError;
    }

    return objResult;
}

function _loadAjaxCache(cacheKey, callback) {
    var cache = localStorage.getItem(cacheKey);
    if (cache) {
        var objResult = JSON.parse(cache);
        objResult._fromCache = true;
        _handleResult(callback, objResult);
        
        return true;
    } else {
        return false;
    }
}

function _handleResult(callback, objResult) {

    //session_id失效，重新验证登录
    if(!objResult.result && objResult.code == -5) {
        openLogin();
    } else {
        callback && callback(objResult);
    }
}

function _deserialize(value){
    if (typeof value != 'string') {
        return undefined
    }
    try {
        return JSON.parse(value)
    }catch(e) {
        return value || undefined
    }
}

function getLocalData(key) {
    return getParam(key) || _deserialize(localStorage.getItem(key));
}

function setLocalData(key, val) {
    localStorage.setItem(key, JSON.stringify(val))
}

function getCookie(name) { 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]); 
    else 
        return null; 
}

function _setTimeout(callback, timeout) {
    var timer = setTimeout(callback, timeout);
    BDY.timeout.push(timer);
    return timer;
}

function _setInterval(callback, timeout) {
    var timer = setInterval(callback, timeout);
    BDY.interval.push(timer);
    return timer;
}

function _clearRes() {
    var len;
    var timeout = BDY.timeout;
    var interval = BDY.interval;
    len = timeout.length;
    for (var i = 0; i < len; i++) {
        clearTimeout(timeout[i]);
    }

    len = interval.length;
    for (var i = 0; i < len; i++) {
        clearInterval(interval[i]);
    }

    // 重置timer
    BDY.timeout = [];
    BDY.interval = [];

    for (var i in BDY.xhrs) {
        BDY.xhrs[i] && BDY.xhrs[i].abort();
    }

    BDY.xhrs = [];
    BDY.xhrCount = 0;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

var loadingDelayHandler = 0;
var loadingTimeoutHandler = 0;
var loadingInstance;

function showLoading(text, timeout, cancelable, delay) {
    // 超时时间为15s
    timeout = timeout || 15000;
    // 0.2s后才显示loading
    delay = delay || 200;
    
    if (cancelable == null) {
        cancelable = true;
    } else {
        cancelable = !!cancelable;
    }
    
    if (loadingDelayHandler) {
        return;
    }
    
    loadingDelayHandler = setTimeout(function() {
        if (!HiydSdk.showLoading(text, timeout, cancelable)) {
            loadingInstance = Loading.service({
                text: text
            });
            
            loadingTimeoutHandler = setTimeout(function(){
                hideLoading();
                showTip("加载超时，请稍后再试");
            }, timeout);
        }
    }, delay);
}

function hideLoading() {
    loadingDelayHandler && clearTimeout(loadingDelayHandler);
    loadingDelayHandler = 0;
    loadingTimeoutHandler && clearTimeout(loadingTimeoutHandler);
    loadingTimeoutHandler = 0;

    try {
        loadingInstance.close();
    } catch(e) {}
}

function showErrorTip(msg, timeout) {
    if (!msg) { return; }
    timeout = timeout || 3000;
    if (!HiydSdk.showErrorTip(msg, timeout)) {
        Message({
            message : msg,
            position: 'middle',
            duration: timeout
        });
    }
}

function showTip(msg, timeout) {
    if (!msg) { return; }
    timeout = timeout || 3000;
    if (!HiydSdk.showTip(msg, timeout)) {
        Toast({
            message : msg,
            position: 'bottom',
            duration: timeout
        });
    }
}

function showDialog(msg, callback, title, buttonLabels) {
    title = title || "提示";
    buttonLabels = buttonLabels || "确定";

    MessageBox({
        title: title,
        message: msg,
        confirmButtonText: buttonLabels
    }).then(action => {
        callback && callback(action);
    });
}

function confirm(msg, callback, title, buttonLabels) {
    title = title || "提示";
    buttonLabels = buttonLabels || "确定,取消";
    if (!HiydSdk.confirm(msg, callback, title, buttonLabels)) {

        MessageBox.confirm(msg, title).then(action => {
            callback && callback(true);
        }).catch(err => {
            callback && callback(false);
        });
    }
}

function setTitle(title) {
    document.title = title;
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        HiydSdk.run2('setTitle',[title]);
    }
    // HiydSdk.setTitle(title);
    //解决在IOS微信内置浏览器内无法通过document.title修改页面标题的hack
    if(checkWXAgent()) {
        var $body = $('body');
        var $iframe = $('<iframe src="/favicon.ico" style="display:none;"></iframe>');
        $iframe.on('load',function() {
        setTimeout(function() {
            $iframe.off('load').remove();
        }, 0);
        }).appendTo($body);
    }
}

function closeWebView() {
    if (!HiydSdk.closeWebView()) {
        historyBack();
    }
}

function openUrl(url, title, needTopBar) {
    if (!HiydSdk.openUrl(url, title, needTopBar)) {
        window.open(url);
    }
}

function tryAutoLogin() {
    if (window.Hiyd) {
        var flag = HiydSdk.openLogin();
        historyBack();
        
        return flag;
    } else {
        return false;
    }
}

function openLogin() {
    var flag = tryAutoLogin();
    //调用微信登录接口
    if (!flag) {
        var fromUrl = encodeURIComponent(document.location.href);
        var url = BDY.mHiydUrl + 'user/login?fromUrl=' + fromUrl;
        location.href = url;
        return false;
    }
}
    
//时间戳转换时间日期
function paserTime(data){
    var str = data.toString();
    var arr = str.split(".");

    if(arr[0].length == 1){
        return "0"+arr[0];
    }
    return arr[0];
}

function handleTime(timeStamp){
    var date = new Date(timeStamp);
    var timeStr = paserTime(date.getMonth()+1)+"月"+paserTime(date.getDay())+"日 "+paserTime(date.getHours())+":"+paserTime(date.getMinutes());

    return timeStr;
}

function checkWXAgent() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

function getFriendlyDateStr(date) {
    var timeSpan = new Date().getTime() - date.getTime();

    var ONE_MINUTE = 60 * 1000,
        ONE_HOUR = 60 * ONE_MINUTE,
        ONE_DAY = 24 * ONE_HOUR,
        ONE_MONTH = 30 * ONE_DAY,
        ONE_YEAR = 12 * ONE_MONTH;

    var friendlyString = '';

    if (timeSpan < ONE_MINUTE) {
        friendlyString = "刚刚";
    } else if (timeSpan < ONE_HOUR) {
        friendlyString = Math.floor(timeSpan / ONE_MINUTE) + "分钟前";
    } else if (timeSpan < ONE_DAY) {
        friendlyString = Math.floor(timeSpan / ONE_HOUR) + "小时前";
    } else if (timeSpan < ONE_MONTH) {
        friendlyString = Math.floor(timeSpan / ONE_DAY) + "天前";
    } else if (timeSpan < ONE_YEAR) {
        friendlyString = Math.floor(timeSpan / ONE_MONTH) + "个月前";
    } else if (timeSpan >= ONE_YEAR) {
        friendlyString = Math.floor(timeSpan / ONE_YEAR) + "年前";
    }

    return friendlyString;
};

var lib = {};
lib.getParam = getParam;
lib.getParam2 = getParam2;
lib.setParam = setParam;
lib.setParam2 = setParam2;
lib.removeParam = removeParam;
lib.parseHash = parseHash;
lib.post = post;
lib.post2 = post2;
lib.get = get;
lib.getLocalData = getLocalData;
lib.setLocalData = setLocalData;
lib.getCookie = getCookie;
lib.setTimeout = _setTimeout;
lib.setInterval = _setInterval;
lib.clearRes = _clearRes;
lib.setTitle = setTitle;
lib.closeWebView = closeWebView;
lib.openUrl = openUrl;
lib.showLoading = showLoading;
lib.hideLoading = hideLoading;
lib.showErrorTip = showErrorTip;
lib.showTip = showTip;
lib.showDialog = showDialog;
lib.confirm = confirm;
lib.checkWXAgent = checkWXAgent;
lib.handleTime = handleTime;
lib.getFriendlyDateStr = getFriendlyDateStr;

export default lib;