import axios from 'axios'
import configMes from './configMes.js'
import uuid from 'uuid'
import session from './session'
import storage from './storage.js'

class System {
    constructor() {

    }

    isAndroidApp() {
        return window && window.JavascriptBridge && window.JavascriptBridge.getToken;
    }

    isIosApp() {
        return window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.JavaScriptBridge;
    }

    isNative() {
        return this.isAndroidApp() || this.isIosApp();

    }

    isWeixin() {
        const ua = navigator.userAgent.toLowerCase();
        if ((/micromessenger/i).test(ua)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取native的登录token
     * @returns token
     */
    getNativeToken(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.getToken){
                return window.JavascriptBridge.getToken();
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getToken',
                param: opt
            })
            return '';
        }

        return null;
    }


    /**
     * 获取native的sessionid
     * @returns sessionid
     */
    getSessionId(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.getSessionId){
                let mySessionId =  window.JavascriptBridge.getSessionId() || new Date().getTime();
                configMes.setSessionid(mySessionId);
                return mySessionId;
            }
            return new Date().getTime();

        } else if (this.isIosApp()) {
            let mySessionId =  window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getSessionId',
                param: opt
            })|| new Date().getTime();

            setTimeout(function() {
                if(window && window.sessionid !=null){
                //    console.log("getnat:sessionid"+window.sessionid);
                    configMes.setSessionid(window.sessionid);
                }else{
              //      console.log("nonat:sessionid"+new Date().getTime());
                    configMes.setSessionid(new Date().getTime());
                }

            }, 1000);

            return mySessionId;
        }else{
            let storSessionid = storage.get('sky-forest-ubt', 'sessionid');
            if(storSessionid){
                return storSessionid;
            }

            let mySessionId = new Date().getTime();
          //  console.log("sys:sessionid"+mySessionId);
            configMes.setSessionid(mySessionId);
            return mySessionId;
        }
        return null;
    }
    /**
     * 获取native的version
     * @returns version
     */
    getVersion(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.getSessionId){
                let myVersion =  window.JavascriptBridge.getVersion() || 1;
                configMes.setVersion(myVersion);
                return myVersion;
            }
            return 1;

        } else if (this.isIosApp()) {
            let myVersion =  window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getVersion',
                param: opt
            })|| 1;

            setTimeout(function() {
                if(window && window.myVersion !=null){
               //     console.log("getnat:myVersion"+window.myVersion);
                    configMes.setVersion(window.myVersion);
                }else{
              //      console.log("nonat:myVersion"+1);
                    configMes.setVersion(1);
                }

            }, 1000);

            return myVersion;
        }else{
            let storVersion = storage.get('sky-forest-ubt', 'version');
            if(storVersion){
                return storVersion;
            }

            let myVersion = 1;
          //  console.log("sys:version"+myVersion);
            configMes.setVersion(myVersion);
            return myVersion;
        }
        return null;
    }




    /**
     * 隐藏返回
     */
    hiddenBack(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.hiddenBack){
                return window.JavascriptBridge.hiddenBack();
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'hiddenBack',
                param: opt
            })
            return '';
        }
        return null;
    }
    /**
     * 显示返回
     */
    showBack(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.showBack){
                return window.JavascriptBridge.showBack();
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'showBack',
                param: opt
            })
            return '';
        }
        return null;
    }



     /**
     * 获取native的登录token
     * @returns token
     */
    closeMailPage(){

        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.closeMailPage){
                const argu = JSON.stringify(opt);
                return window.JavascriptBridge.closeMailPage(argu);
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'closeMailPage',
                param: opt
            })
            return '';
        }

        return null;
    }

    /**
     * 获取native的登录token
     * @returns token
     */
    savePicture(opt){
        // const opt = {};
        opt = opt || {};
        // opt.view = opt.view || '';
        // opt.id = opt.id || 0;
        // opt.index = opt.index || 0;
        opt.url = opt.url || '';
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.savePicture){
                const argu = JSON.stringify(opt);
                return window.JavascriptBridge.savePicture(argu);
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'savePicture',
                param: opt
            })
            return '';
        }

        return null;
    }



    /**
     * 获取native的uuid
     * @returns uuid
     */
    getNativeUuid(){
        const opt = {};
        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.getUuid){
                let myUuid = window.JavascriptBridge.getUuid()||uuid.v1()+"_Android_H5";
                configMes.setUuid(myUuid);

                return myUuid;
            }
            return uuid.v1();
        } else if (this.isIosApp()) {
            let myUuid =  window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getUuid',
                param: opt
            }) || uuid.v1()+"_Ios_H5";

            setTimeout(function() {
                if(window.uuid && window.uuid !=null){
                    configMes.setUuid(window.uuid);
                }else{
                    configMes.setUuid(myUuid);
                }

            }, 1000);

            return myUuid;
        }else{

            let strUuid = storage.get('sky-forest-ubt', 'uuid');
            if(strUuid){
                return strUuid;
            }

            let myUuid = uuid.v1();
            configMes.setUuid(myUuid);
            return myUuid;
        }

        // return null;
    }

    /**
     * 获取native的moblie
     * @returns moblie
     */
    getMobile(){
        const opt = {};

        if (this.isAndroidApp()) {
            if(window.JavascriptBridge && window.JavascriptBridge.getMobile){
                return window.JavascriptBridge.getMobile();
            }
            return '';

        } else if (this.isIosApp()) {
            return window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getMobile',
                param: opt
            })
            return '';
        }

        return null;
    }

    /**
     * 参数定义
     * view:页面名称，string类型：
     *      public-space(公共空间);
     *      baidu-map(百度地图);
     *      land-space(园林景观);
     *      video-player(视频播放);
     *      vr-player(vr播放);
     *      h5(h5页面);
     *      simple-article(简单图文页面);
     *      smart-book-article(智能楼书图文页面);
     *      live-info(直播介绍页面);
     *      homeDetail(楼盘详情页);
     *      moment(此时此刻)
     *      consultantService(IM)
     *      shangju(上居native首页)
     *      videochat(视频通话)
     * id:资源id
     * index:资源索引
     * url:资源url
     * title:标题
     * code:资源码(planCode)
     * hideHeader:是否隐藏头，默认不隐藏
     * */

    go(opt) {
        opt = opt || {};
        opt.view = opt.view || '';
        opt.id = opt.id || 0;
        opt.index = opt.index || 0;
        opt.url = opt.url || '';
        opt.title = opt.title || '';
        opt.code = opt.code || '';
        opt.hideHeader = !!opt.hideHeader;
        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.go(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'scheme',
                param: opt
            })
            return true;
        }
    }

    /**
     * 通过让app调用回调函数，执行音频和视频的自动播放
     *
     */
    execCallback(funcStr){
        if(!funcStr){
            funcStr = 'execCallback$func'
        }

        if (this.isAndroidApp()) {
            window.JavascriptBridge.execCallback(funcStr);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'execCallback',
                param: funcStr
            })
            return true;
        }
    }
    /**
     * 通过让app显示相册
     *
     */
    showAlbum(picList,bgType){

        if (this.isAndroidApp()) {
            window.JavascriptBridge.showAlbum(picList,bgType);
            return true;
        } else if (this.isIosApp()) {
            var parm = {};
            parm["picList"] = picList;
            parm["bgType"] = bgType;
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'showAlbum',
                param: JSON.stringify(parm)
            })
            return true;
        }
    }

    /**
     * 获取经纬度
     * 参数定义
     * successFunc: 扫描成功后，调用的js函数名称，比如：getLatlng$OnSuccess(lat,lng),lat和lng都为浮点类型，表示经纬度
     * failFunc: 扫描失败后，调用的js函数名称，比如：getLatlng$OnFail(jsonStr)
     *      sonStr是json字符串，序列化之前的定义如下：
     *      {
     *          code:错误码（11000：系统或设备不支持，11001：位置服务不可用，11999：其他错误）
     *          msg:错误消息
     *      }
     * */
    getLatlng(opt){
        opt = opt || {};
        opt.successFunc = opt.successFunc || 'getLatlng$OnSuccess';
        opt.failFunc = opt.failFunc || 'getLatlng$OnFail';

        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.getLatlng(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'getLatlng',
                param: argu
            })
            return true;
        } else if(this.isWeixin()){
            this.weiXinReady(function(argu){
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        window[argu.successFunc](res.latitude,res.longitude)
                    }
                });
            },opt)
        }
    }

    /**
     * 初始化头部的喜欢按钮
     * 参数：
     * url：收藏的url
     * title：标题
     * subtitle：副标题
     * thumbnail：封面图片
     * isFavorited：是否已经收藏
     */
    initFavorite(opt){
        opt = opt || {};
        opt.url = opt.url || location.origin+location.pathname+location.hash;
        opt.title = opt.title || document.title;
        opt.subtitle = opt.subtitle||'';
        opt.thumbnail = opt.thumbnail||'http://skyforest.static.elab-plus.com/share.png';
        opt.isFavorited = opt.isFavorited||false;

        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.initFavorite(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'initFavorite',
                param: opt
            })
            return true;
        }
    }

    /**
     * 开始ibeacon扫描，app这边开始以后，每秒轮询一次，
     * 如果失败，再重试2次，如果全部失败，调用failFunc传入的函数名，停止轮询；如果成功，调用successFunc传入的函数名，继续轮询
     * 参数定义
     * uuids: 设备的uuid列表，字符串数组
     * successFunc: 扫描成功后，调用的js函数名称，比如：startBeaconDiscovery$OnSuccess(jsonStr)
     *      jsonStr是json字符串，序列化之前的定义如下：Array<iBeacon>
     *      iBeacon:{
     *          uuid:设备id
     *          name:设备名称
     *          major：主设备号
     *          minor：次设备号
     *          measuredPower：设备的测量强度
     *          rssi:设备的信号强度
     *      }
     * failFunc: 扫描失败后，调用的js函数名称，比如：startBeaconDiscovery$OnFail(jsonStr)
     *      sonStr是json字符串，序列化之前的定义如下：
     *      {
     *          code:错误码（11000：系统或设备不支持，11001：蓝牙服务不可用，11002：位置服务不可用，11003：已经开始搜索，11999：其他错误）
     *          msg:错误消息
     *      }
     * */
    startBeaconDiscovery(opt){

        if(!opt || !opt.uuids){
            return;
        }

        opt.successFunc = opt.successFunc || 'startBeaconDiscovery$OnSuccess';
        opt.failFunc = opt.failFunc || 'startBeaconDiscovery$OnFail';

        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.startBeaconDiscovery(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'startBeaconDiscovery',
                param: opt
            })
            return true;
        }
    }


    /**
     * 停止ibeacon扫描
     * */
    stopBeaconDiscovery(opt){
        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.stopBeaconDiscovery(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'stopBeaconDiscovery',
                param: opt
            })
            return true;
        }
    }

    /**
     * 重新播放上居的启动视频
     * */
    playShangJuVideo(){
        const opt = {};

        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.playShangJuVideo(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'playShangJuVideo',
                param: opt
            })
            return true;
        }
    }

    /**
     * 重新播放上居的启动视频
     * */
    initPageJs(){
        const opt = {};

        if (this.isAndroidApp()) {
            const argu = JSON.stringify(opt);
            window.JavascriptBridge.initPageJs(argu);
            return true;
        } else if (this.isIosApp()) {
            window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                sel: 'initPageJs',
                param: opt
            })
            return true;
        }
    }

    /**
     * 调用native登录
     * @param opt
     * redirect：登录成功后跳转的url
     */
    login(opt){
        opt = opt || {};
        opt.redirect = opt.redirect || '';

        try {
            if (this.isAndroidApp()) {
                const argu = JSON.stringify(opt);
                window.JavascriptBridge.login(argu);
            } else if (this.isIosApp()) {
                window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                    sel: 'login',
                    param: opt
                })
            } else {

            }
        } catch (err) {
            console.log(err)
        }
    }

    /**
     *  H5页面初始化传给app的参数
     *  参数定义
     *  pageid:pageid
     */
    initPageMeta(opt) {
        opt = opt || {};
        opt.pageid = (opt.pageid || '').toString();

        try {
            if (this.isAndroidApp()) {
                const argu = JSON.stringify(opt);
                window.JavascriptBridge.pageMeta(argu);
            } else if (this.isIosApp()) {
                window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                    sel: 'pageMeta',
                    param: opt
                })
            }
        } catch (err) {
            console.log(err)
        }
    }

    /**
     *  参数定义
     *  title:分享标题，逻辑，优先使用这个title，如果为空则用页面title
     *  desc:分享描述
     *  type:分享类型，url：链接方式；image：图片方式
     *  cover:链接方式的封面图片url
     *  image:图片方式的图片url
     *  url:分享的url，为空则是当前页面
     */
    initShareMeta(opt) {
        opt = opt || {};
        opt.title = opt.title || '';
        opt.desc = opt.desc || '';
        opt.type = opt.type || 'url';
        opt.cover = opt.cover || '';
        opt.image = opt.image || '';
        opt.url = opt.url || '';
      //  console.log("initShareMeta:start");
        try {
            if (this.isAndroidApp()) {

                if(system.isWeixin()){
                //    console.log("initShareMeta: isweixin");
                    this.setWeiXinShare({
                        title: opt.title,
                        desc: opt.desc,
                        imgUrl: opt.cover
                    });
                }else{
                  //  console.log("title:"+opt.title);
                    const argu = JSON.stringify(opt);
                    window.JavascriptBridge.shareMeta(argu);
                }

            } else if (this.isIosApp()) {
                if(system.isWeixin()){
               //     console.log("initShareMeta: isweixin");
                    this.setWeiXinShare({
                        title: opt.title,
                        desc: opt.desc,
                        imgUrl: opt.cover
                    });
                }else{
                 //   console.log("initShareMeta: H5");
                    window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                        sel: 'shareMeta',
                        param: opt
                    })
                }

            } else {
                // console.log("initShareMeta: isweixin");
                this.setWeiXinShare({
                    title: opt.title,
                    desc: opt.desc,
                    imgUrl: opt.cover
                });
            }
        } catch (err) {
            console.log(err)
        }
    }

    /**
     *  参数定义
     *  title:分享标题，逻辑，优先使用这个title，如果为空则用页面title
     *  desc:分享描述
     *  type:分享类型，url：链接方式；image：图片方式
     *  cover:链接方式的封面图片url
     *  image:图片方式的图片url
     *  url:分享的url，为空则是当前页面
     */
    openShare(opt) {
        opt = opt || {};
        opt.title = opt.title || '';
        opt.desc = opt.desc || '';
        opt.type = opt.type || 'url';
        opt.cover = opt.cover || '';
        opt.image = opt.image || '';
        opt.url = opt.url || '';
        try {

            if (this.isAndroidApp()) {
                const argu = JSON.stringify(opt);
                window.JavascriptBridge.openShare(argu);
            } else if (this.isIosApp()) {
                window.webkit.messageHandlers.JavaScriptBridge.postMessage({
                    sel: 'openShare',
                    param: opt
                })
            }
        } catch (err) {
            console.log(err)
        }
    }

    setWeiXinShare(shareOpt) {
        this.weiXinReady(function(argu){
            //console.log("setWeiXinShareTitle"+JSON.stringify(argu));
            wx.onMenuShareTimeline(argu);
            wx.onMenuShareAppMessage(argu);

            // wx.onMenuShareTimeline({
            //     title:argu.title,
            //     desc:argu.desc,
            //     imgUrl:argu.imgUrl,
            // });
            // wx.onMenuShareAppMessage({
            //     title:argu.title,
            //     desc:argu.desc,
            //     imgUrl:argu.imgUrl,
            // });


        },shareOpt)
    }

    weiXinReady(func,argu){
        if(configMes.isWxReady){
            func(argu)
        } else{
            wx.ready(function () {
                configMes.isWxReady= true;
                func(argu)
            });
        }
    }
}

const system = new System();

export default system;
