import $ from 'jquery';
import BDY from 'BDY';
import WjySdk from 'extSdk';
import _ from 'underscore'
import Indicator from 'mint-ui/lib/indicator';
import Toast from 'mint-ui/lib/toast';
import MessageBox from 'mint-ui/lib/message-box';

import 'mint-ui/lib/indicator/style.css';
import 'mint-ui/lib/toast/style.css';
import 'mint-ui/lib/message-box/style.css';

import PhotoSwipe from 'photoswipe';
import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default';

const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1; //android终端
const isiOS = navigator.userAgent.match(/(iPhone|iPod|iPad);?/i); //ios终端

var lib = {};

// 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) {
    var search = document.location.search.substr(1);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    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 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 loadDialog;

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 (!WjySdk.showLoading(text, timeout, cancelable)) {
            Indicator.open(text);
            
            loadingTimeoutHandler = setTimeout(function(){
                hideLoading();
                showTip("加载超时，请稍后再试");
            }, timeout);
        }
    }, delay);
}

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

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

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

function showTip(msg, timeout) {
    if (!msg) { return; }
    timeout = timeout || 2000;
    if (!WjySdk.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 (!WjySdk.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)) {
        WjySdk.run2('setTitle',[title]);
    }
    // WjySdk.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 (!WjySdk.closeWebView()) {
        historyBack();
    }
}

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

function tryAutoLogin() {
    if (window.Wjy) {
        var flag = WjySdk.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 initWxSdk() {
    if(!checkWXAgent()) {
        return;
    }
	
    let url = BDY.mHiydUrl +  "weixin/getJsSign";
    let data = {
        url : location.href,
        appid: 6
    };

	post(url, data, function(ret) {
		ret.data.debug = /test\.|webdev/.test(document.location.href) ? true : false;
		ret.data.jsApiList = [
            "chooseImage",
            "previewImage",
            "uploadImage",
        ];
		wx.config(ret.data);
	});
}

function handleTime(timeStamp,type){

    if(!timeStamp) return "--"

    var date = new Date(timeStamp)
    var year = date.getFullYear()
    var month = date.getMonth()+1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()

    month = month >= 10 ? month : "0"+month
    day = day >= 10 ? day : "0"+day
    hour = hour >= 10 ? hour : "0"+hour
    minute = minute >= 10 ? minute : "0"+minute

    if(type==2) {
        return year+"-"+month+"-"+day+" "+hour+":"+minute
    } else {
        return year+"年"+month+"月"+day+"日 "+hour+":"+minute
    }
}

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

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

function getDomain(){
    var host = location.host;

    if (host.indexOf("127.0.0.1") > -1 || host.indexOf("test.h5-glance.duowan.com") > -1) {
        lib.apiUrl = "//test.api.glance.oxzj.net";
        lib.upAdminDomain = "//test.up.admin.duowan.com";
    } else {
        lib.apiUrl =  "//api-glance.duowan.com";
        lib.upAdminDomain = "//phpadmin-up.duowan.com";
    } 
}

function getDownloadUrl(){
    var downloadUrl = "#";

    if(checkWXAgent()) {
        downloadUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.ouj.movietv";
    } else {
        if (isiOS) { 
            downloadUrl = "https://itunes.apple.com/us/app/%E5%BE%AE%E5%89%A7%E9%99%A2-5%E5%88%86%E9%92%9F%E7%9C%8B%E7%89%87/id1268549279?l=zh&ls=1&mt=8";
        } else {
            downloadUrl = "http://www.hiyd.com/static/apkDownload?appid=13"
        }
    }

    return downloadUrl; 
}

function getSchemaUrl(){
    return isAndroid ? 'glance://' : 'movietv://'
}

function getAppName() {
    let appName;
    if(lib.getParam("appid") == 1008 || lib.getParam("appid") == 17) {
        appName = '知了电影'
    } else {
        appName = '微剧院'
    }
    return appName;
}

//设置微信分享的参数
function setWxShare(data,sCallback,cCallBack){ //分享数据,success回调,cancel回调
    if (!checkWXAgent()) return;

    var checkWxInterval = setInterval(function(){
        if(wx) {
            clearInterval(checkWxInterval);

            // 适配https
            if(!data.imgUrl.match(/http\:\/\/|https\:\/\//)) {
                data.imgUrl = "https:" + data.imgUrl
            }
            
            wx.ready(function(){

                wx.onMenuShareTimeline({
                    title: data.title, // 分享标题
                    link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: data.imgUrl, // 分享图标
                    success: function () { 
                        sCallback && sCallback(); // 用户确认分享后执行的回调函数
                    },
                    cancel: function () { 
                        cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
                    }
                });

                wx.onMenuShareAppMessage({
                    title: data.title, // 分享标题
                    desc: data.desc, // 分享描述
                    link: data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: data.imgUrl, // 分享图标
                    success: function () { 
                        sCallback && sCallback(); // 用户确认分享后执行的回调函数
                    },
                    cancel: function () { 
                        cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
                    }
                });

            });

        }
    },200);
}

//图片预览
function setPreviewImage(imgList, curIndex,w,h) {
    let handleImgList = []
    if (checkWXAgent()) { //微信客户端
        _.each(imgList,(img,i)=>{
            if(img.indexOf("http")> -1){
                handleImgList.push(img)  
            } else {
                handleImgList.push(`https:${img}`)  
            }
        })
    
        wx.ready(function() {
            wx.previewImage({
                current: handleImgList[curIndex],
                urls: handleImgList
            });
        });
    } else {
        _.each(imgList,(pic,i)=>{
            handleImgList.push({
                src: pic,
                w: w || 1242,
                h: h || 1080
            })
        })

        let options = {
            index: curIndex
        };
        
        let gallery = new PhotoSwipe($('.pswp').get(0), PhotoSwipeUI_Default, handleImgList, options);
        gallery.init();
    }
}

function formatHttpProtocol(object) {
    let fData = JSON.stringify(object);
    fData = fData.replace(/http\:\/\//g, "//");
    return JSON.parse(fData);
}

/**
 * APP协议跳转
 * @param {String} schemaUrl 
 */
function goSchema(schemaUrl) {
    var url = getDownloadUrl();
    if(isAndroid) {
        $('body').append(`<iframe src='${schemaUrl}' style='display:none' target='' ></iframe>`);
    } else {
        window.location = schemaUrl
    }
    setTimeout(() => {
        window.location = url
    },25);
}

function init(){
    getDomain();
}

init();


lib.getParam = getParam;
lib.getParam2 = getParam2;
lib.setParam = setParam;
lib.setParam2 = setParam2;
lib.removeParam = removeParam;
lib.parseHash = parseHash;
lib.post = post;
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.checkWjyAgent = checkWjyAgent;
lib.handleTime = handleTime;
lib.setWxShare = setWxShare;
lib.setPreviewImage = setPreviewImage;
lib.formatHttpProtocol = formatHttpProtocol;
lib.goSchema = goSchema;
lib.downloadUrl = getDownloadUrl()
lib.schemaUrl = getSchemaUrl()
lib.appName = getAppName()

export default lib;