Source: ymtapi.js

/* global wx */
'use strict';
//   __    __           ______   ______  _____    __  __     
//  /\ \  /\ \ /'\_/`\ /\  _  \ /\__  _\/\  __`\ /\ \/\ \    
//  \ `\`\\/'//\      \\ \ \/\ \\/_/\ \/\ \ \/\ \\ \ \ \ \   
//   `\ `\ /' \ \ \__\ \\ \  __ \  \ \ \ \ \ \ \ \\ \ \ \ \  
//     `\ \ \  \ \ \_/\ \\ \ \/\ \  \ \ \ \ \ \_\ \\ \ \_\ \ 
//       \ \_\  \ \_\\ \_\\ \_\ \_\  \ \_\ \ \_____\\ \_____\
//        \/_/   \/_/ \/_/ \/_/\/_/   \/_/  \/_____/ \/_____/
//                                                                                                                                      
//     

/**
 * @namespace YmtApi
 * @description YmtApi是h5与原生native交互的协议及工具
 * @public
 * @author haiyang5210
 * @since 2015-06-25 10:48
 */


hui.define('ymtapi', ['hui_eventdispatcher'], function () {
    window.YmtApi = window.YmtApi || {};
    var YmtApi = window.YmtApi;

    var obj = new hui.EventDispatcher();
    for (var i in obj) {
        YmtApi[i] = obj[i];
    }

    YmtApi.version = '0.1.0';

    var ua = window.navigator.userAgent;
    YmtApi.isWechat = /MicroMessenger/i.test(ua);
    YmtApi.isSaohuoApp = /saohuoApp/i.test(ua);
    YmtApi.isYmtApp = /ymtapp/i.test(ua);
    // shareSource: 'ymtapp', 'saohuoApp'

    /**
     * @namespace YmtApi.utils
     * @description YmtApi.utils是辅助工具集
     * @public
     * @author haiyang5210
     * @since 2015-06-25 10:48
     */
    YmtApi.utils = {
        /**
         * @method YmtApi.utils.getAuthInfo
         * @description 获得token信息,没有则从cookie获得
         * @return {Object} currSearch
         * @example
         * YmtApi.utils.getAuthInfo();
         */
        getAuthInfo: function () {
            var currSearch = YmtApi.auth || YmtApi.utils.getUrlObj();
            var getTokenFormCookie = function () {
                var tokenMatch = document.cookie.match(/AccessToken=([^;]*)/);
                if (tokenMatch) {
                    return tokenMatch[1];
                }
                return null;
            };
            if (YmtApi.isYmtApp && (!currSearch.AccessToken || currSearch.AccessToken === 'nil')) {
                currSearch.AccessToken = getTokenFormCookie();
            }
            return currSearch;
        },
        /**
         * @method YmtApi.utils.getOrderSource
         * @description 获得订单来源
         * @return {string} 订单来源
         */
        getOrderSource: function () {
            var urlObj = YmtApi.utils.getUrlObj(),
                otherSource = urlObj['shareSource'], //是否有来源
                orderSource = '';
            if (YmtApi.isYmtApp) {
                orderSource = 'APP';
            }
            else if (YmtApi.isSaohuoApp) {
                orderSource = 'C2CAPP';
            }
            else if (YmtApi.isWechat) {
                orderSource = 'Wechat';
                if (/saohuoApp/i.test(otherSource)) {
                    orderSource = 'C2C' + orderSource;
                }
            }
            else { //如果都不符合 默认算作WAP
                orderSource = 'WAP';
            }
            return orderSource;
        },

        /**
         * @method YmtApi.utils.addAuth
         * @description 增加用户认证
         * @param {string}  url     需要增加的的地址
         * @param {Boolean} isForce 是否为强制认证,默认值:false;当为true
         *                              则会判断是否能得到用户认证,不能则触发登录。 
         */
        addAuth: function (url, isForce) {
            var authInfo = YmtApi.utils.getAuthInfo(),
                currSearch = YmtApi.utils.getUrlObj();

            if (isForce) {
                if (!authInfo || !authInfo.AccessToken || authInfo.AccessToken == 'nil') {
                    return YmtApi.toLogin();
                }
            }

            return YmtApi.utils.addParam(url, {
                UserId: authInfo.UserId,
                AccessToken: authInfo.AccessToken,
                shareSource: currSearch.shareSource
            });
        },
        /*
         * 移除认证
         */
        rmAuth: function (url) {
            return (url + '').replace(/&?AccessToken=[^&#]*/ig, '').replace(/&?UserId=[^&#]*/ig, '');
        },
        parseUrl: function (str) {
            var arr,
                part,
                url = {};
            if (!(str || '').replace(/^\s+|\s+$/, '')) {
                return {};
            }
            str = str.substring(1, str.length);
            if (str) {
                arr = str.split('&');
                for (var i in arr) {
                    part = arr[i].split('=');
                    url[part[0]] = part[1];
                }
            }
            return url;
        },
        /*
         * 获得当前页面的参数
         * return {UserId: 10001, AccessToken: 'ABCDSEFDG'}
         */
        getUrlObj: function () {
            return YmtApi.utils.parseUrl(location.search);
        },
        param: function (paramObj) {
            var str = [];
            for (var i in paramObj) {
                str.push(i + '=' + encodeURIComponent(paramObj[i]));
            }
            return str.join('&');
        },
        /*
         * 增加参数
         */
        addParam: function (url, params) {
            var SEARCH_REG = /\?([^#]*)/,
                HASH_REG = /#(.*)/;
            url = url || '';
            var search = {},
                searchMatch = url.match(SEARCH_REG),
                searchAttr = [],
                searchStr = '';

            if (searchMatch) {
                search = YmtApi.utils.parseUrl(searchMatch[0]);
            }

            search = hui.extends(search, params);

            for (var i in search) {
                if (search[i] !== undefined) {
                    searchAttr.push(i + '=' + search[i]);
                }
            }
            if (searchAttr[0]) {
                searchStr = '?' + searchAttr.join('&');
            }

            //是否存在search
            if (SEARCH_REG.test(url)) {
                url = url.replace(SEARCH_REG, searchStr);
            }
            else {
                //是否存在hash
                if (HASH_REG.test(url)) {
                    url = url.replace(HASH_REG, searchStr + '#' + url.match(HASH_REG)[1]);
                }
                else {
                    url += searchStr;
                }
            }
            return url;
        }

    };

    /**
     * YmtApi
     *
     * @description 
     *      这个脚本包含不同端的不同处理,方法名称参数类型基本保持一致,
     *      在特定场景不存在的方法也由空方法替代,不需要做过多的判断
     *      
     * @example
     *   工具方法:
     *      判断环境
     *          YmtApi.isWechat 
     *          YmtApi.isSaohuoApp
     *          YmtApi.isYmtApp
     *
     *      YmtApi.utils
     *          getAuthInfo    获得认证信息
     *          getOrderSource 获得订单来源
     *          addAuth        添加认证信息 url传递
     *          
     *                           码头app             扫货app            微信
     *  open 打开页面               Y                    Y                 Y
     *  openShare 打开分享          Y                    Y                 Y
     *  openChatList 会话列表       Y                    N                 N
     *  previewImage 会话详情       Y                    Y                 N
     *  openPay 打开支付            Y                    Y                 Y
     *  toLogin 打开登录            Y                    Y                 Y
     *  openConfirmOrder  一键购买  N                    Y                 Y
     *
     *  事件:
     *      这里是自定义事件,自己sendEvent为单页触发,而由webview sendEvent为
     *  全局触发,默认添加 userStatusChange 登录变更之后会触发,你可以可以自定义
     *  自己的登录会触发回调
     *  
     *      YmtApi.on('userStatusChange',function(){
     *          //Handling
     *      });
     *
     *      YmtApi.off('userStatusChange');//移除指定事件
     *      YmtApi.off('userStatusChange userStatusChange1 userStatusChange2');//移除指定多个事件
     *
     *      YmtApi.one('userStatusChange',function(){
     *      
     *      });//执行一次
     *
     *  微信YmtApi做了相应调整
     *  1、微信初始化不再自动执行,请使用相关功能单独 initWechat
     *      两个参数:
     *          options 【 微信初始化参数 】
     *              参考http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E6.AD.A5.E9.AA.A4.E4.B8.80.EF.BC.9A.E7.BB.91.E5.AE.9A.E5.9F.9F.E5.90.8D
     *          wxReadyCallback  【微信初始化完毕回调方法】
     *       另外方便部分页面和功能不需要自定义,直接使用默认配置,那在调用ymtapi.js 增加wxAutoInit=1参数 
     *       则自动会执行默认执行initWechat方法
     *    <script src="http://staticmatouapp.ymatou.com/js/YmtApi.js?wxAutoInit=1"> 【自动会执行initWechat使用默认参数】
     *
     *  2、所有页面将放开分享功能,如需关闭自己调用。【默认分享功能,允许分享当前页,切会移除token等信息分享当前页】
     *      initWechat({/*options* /},function(wx){
     *          wx.hideMenuItems(/* 关闭的自定义菜单列表* /);
     *      });
     * 
     *  3、toLogin
     *      支持回调url     
     *  
     *  
     */



    /**
     * @method YmtApi.open
     * @description 打开Webview
     * @param  {object} options
     * @example
     * YmtApi.open({
     *     url: 'http://matouapp.ymatou.com/forYmatouApp/home',
     *     shareFlag: 1,
     *     backFlag: 1,
     *     backType: 0,    
     *     backFlag: 1,  
     *     msgFlag: 1,     
     *     showWeiboFlag: 0,
     *     needJumpFlag: 1,
     *     title: '商品详情',
     *     shareTitle: '分享标题',
     *     shareContent: '分享内容',
     *     sharePicUrl: 'http://分享图片',
     *     shareLinkUrl: 'http://分享链接地址'
     * });

     */
    YmtApi.open = function (options) {
        if (!options || (!options.url && !options.shareUrl)) {
            throw new Error('open: url Can not be empty!!');
        }

        var args = {
            'url': 1,
            'shareurl': 1,
            'title': 1,
            'backtype': 1,
            'backflag': 1,
            'msgflag': 1,
            'sharetitle': 1,
            'sharecontent': 1,
            'sharepicurl': 1,
            'sharelinkurl': 1,
            'sharetip': 1,
            'price': 1,
            'needjumpflag': 1,
            'isnew': 1,
            'showsharebtn': 1,
            'shareflag': 1,
            'showweibobtn': 1,
            'showweiboflag': 1,
            'addauth': 1
        };
        var _param = {};
        for (var i in options) {
            !args[String(i).toLowerCase()] && (_param[i] = options[i]);
        }

        options.title && (_param.title = options.title);
        options.backType && (_param.backType = options.backType);
        options.backFlag && (_param.backFlag = 1);
        options.msgFlag && (_param.msgFlag = 1);
        // 容错处理
        options = YmtApi.configShare(options);

        if (YmtApi.isYmtApp) {
            // 示例:http://matouapp.ymatou.com/forYmatouApp/product/pid?
            // shareTitle=contigo%E5%BA%B7%E8%BF%AA%E5%85%8B%E5%84%BF%E7%AB%A5%E5%90%B8%E7%AE%A1%E4%BF%9D%E6%B8%A9%E6%9D%AF300ml
            // &sharePicUrl=http://p7.img.ymatou.com/G02/M06/B7/35/CgvUBFX4yGWAYZNmAABlStgzUBQ078_o.jpg
            // &shareUrl=http://haiyang.me
            // &needJumpFlag=1
            // &pid=66a92b97-2903-4927-a931-8a5045058742
            // 问题:
            // 1. 当传递的参数不完整时APP会闪退,故必须保证格式完整!!
            // 2. shareUrl参数未转码!!
            // 3. price未传也会闪退!!
            if (options.shareTitle) {
                var shareLinkUrl = String(options.shareLinkUrl || options.shareUrl || options.url);
                shareLinkUrl = shareLinkUrl.replace(/&?AccessToken=[^&#]*/ig, '').replace(/&?UserId=[^&#]*/ig, '');
                shareLinkUrl = shareLinkUrl.replace(/&?IDFA=[^&#]*/ig, '').replace(/&?DeviceId=[^&#]*/ig, '').replace(/&?DeviceToken=[^&#]*/ig, '');
                options.shareLinkUrl = shareLinkUrl;

                _param.shareTitle = encodeURIComponent(options.shareTitle);
                // shareUrl参数不能转码!!
                _param.shareUrl = options.shareLinkUrl;
                _param.sharePicUrl = encodeURIComponent(options.sharePicUrl);
                _param.shareTip = encodeURIComponent(options.shareTip);
                _param.price = options.price || '';
            }

            if (options.needJumpFlag || options.isNew) {
                _param.needJumpFlag = 1;
            }

            var str = YmtApi.utils.addAuth(YmtApi.utils.addParam(options.url, _param));
            window.location.href = str;
        }
        else if (YmtApi.isSaohuoApp) {
            //是否显示原生分享按钮
            if (options.showShareBtn || options.shareFlag) {
                // 显示右上角原生分享按钮,
                // 注:聚洋货会将该属性视为触发原生分享,故不能放到前面公共部分
                _param.shareFlag = 1;

                var shareLinkUrl = String(options.shareLinkUrl || options.shareUrl || options.url);
                shareLinkUrl = shareLinkUrl.replace(/&?AccessToken=[^&#]*/ig, '').replace(/&?UserId=[^&#]*/ig, '');
                shareLinkUrl = shareLinkUrl.replace(/&?IDFA=[^&#]*/ig, '').replace(/&?DeviceId=[^&#]*/ig, '').replace(/&?DeviceToken=[^&#]*/ig, '');
                options.shareLinkUrl = shareLinkUrl;

                _param.ShareTitle = encodeURIComponent(options.shareTitle);
                _param.ShareLinkUrl = encodeURIComponent(YmtApi.utils.addParam(options.shareLinkUrl, {
                    shareSource: 'saohuoApp'
                }));
                _param.SharePicUrl = encodeURIComponent(options.sharePicUrl);
                _param.ShareContent = encodeURIComponent(options.shareContent);

                _param.showWeiboFlag = +!!options.showWeiboBtn || +!!options.showWeiboFlag;
            }

            if (options.needJumpFlag || options.isNew) {
                _param.forBuyerApp_needJumpFlag = 1;
            }
            var str = YmtApi.utils.addAuth(YmtApi.utils.addParam(options.url, _param));
            window.location.href = str;
        }
        else if (YmtApi.isWechat) {
            if (options.addAuth) {
                _param.addAuth = 1;
            }
            window.location.href = YmtApi.utils.addAuth(YmtApi.utils.addParam(options.url, _param));
        }
        else {
            for (var i in _param) {
                _param[i] = encodeURIComponent(_param[i]);
            }
            window.location.href = YmtApi.utils.addAuth(YmtApi.utils.addParam(options.url, _param));
        }
    };

    /**
     * @method YmtApi.openConfirmOrder
     * @description 打开确认订单页
     * @param 查考open参数
     */
    YmtApi.openConfirmOrder = function (options) {
        options = options || {};
        options.url = 'http://matouapp.ymatou.com/forYmatouApp/orders?directBuy=1';
        //默认新窗口打开
        if (options.needJumpFlag === undefined) {
            options.needJumpFlag = true;
        }
        YmtApi.open(options);
    };

    /**
     * @method YmtApi.openShare
     * @description 打开聊天列表
     * @param  {Object} options 分享标题文案图标等参数
     * @example
     * YmtApi.openShare({
     *     title: 'hy test share title',
     *     shareTitle: 'hy test shareTitle',
     *     sharePicUrl: 'http://static.ymatou.com/images/sprites/logo.png',
     *     shareUrl: 'http://static.ymatou.com/images/sprites/logo.png',
     *     shareTip: 'hy test shareTip'
     * });
     *
     */
    YmtApi.openShare = function (options) {
        options = YmtApi.configShare(options);

        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/share?' + YmtApi.utils.param({
                title: '分享',
                shareTitle: options.shareTitle,
                sharePicUrl: options.sharePicUrl,
                shareTip: options.shareTip,
                shareUrl: YmtApi.utils.addParam(options.shareUrl, {
                    shareSource: 'ymtapp'
                }),
                shareFlag: 1
            });
        }
        else if (YmtApi.isSaohuoApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/share?' + YmtApi.utils.param({
                title: '分享',
                ShareTitle: options.shareTitle,
                SharePicUrl: options.sharePicUrl,
                ShareContent: options.shareContent || options.shareTip,
                ShareLinkUrl: YmtApi.utils.addParam(options.shareUrl, {
                    shareSource: 'saohuoApp'
                }),
                showWeiboFlag: +!!options.showWeiboBtn || +!!options.showWeiboFlag,
                ShareFlag: 1
            });
        }
        else if (YmtApi.isWechat) {
            YmtApi.showShareMask();
        }
    };
    YmtApi.configShare = function (options) {
        options = options || {};
        // 容错处理
        (options.ShareTitle || options.shareTitle) && (options.shareTitle = options.ShareTitle || options.shareTitle);
        (options.ShareContent || options.shareContent) && (options.shareContent = options.ShareContent || options.shareContent);
        (options.SharePicUrl || options.sharePicUrl) && (options.sharePicUrl = options.SharePicUrl || options.sharePicUrl);
        (options.ShareLinkUrl || options.shareLinkUrl) && (options.shareLinkUrl = options.ShareLinkUrl || options.shareLinkUrl);
        (options.ShareUrl || options.shareUrl) && (options.shareUrl = options.ShareUrl || options.shareUrl);
        (options.ShareTip || options.shareTip || options.shareContent) && (options.shareTip = options.ShareTip || options.shareTip || options.shareContent);

        var shareUrl = String(options.shareLinkUrl || options.shareUrl || options.url || window.location.href);
        shareUrl = shareUrl.replace(/&?AccessToken=[^&#]*/ig, '').replace(/&?UserId=[^&#]*/ig, '');
        shareUrl = shareUrl.replace(/&?IDFA=[^&#]*/ig, '').replace(/&?DeviceId=[^&#]*/ig, '').replace(/&?DeviceToken=[^&#]*/ig, '');

        options.shareUrl = shareUrl;
        options.shareTitle = options.shareTitle || '洋码头';
        options.shareTip = options.shareTip || '购在全球,我们只做洋货';
        options.sharePicUrl = options.sharePicUrl || 'http://static.ymatou.com/images/home/zbuy-logo-n.png';

        if (YmtApi.isYmtApp) {
            // Todo
        }
        else if (YmtApi.isSaohuoApp) {
            // Todo
        }
        else if (YmtApi.isWechat) {
            hui.require(['jweixin_share'], function () {
                var shareConf = {};

                var urlObj = YmtApi.utils.getUrlObj(),
                    otherSource = urlObj['shareSource'];

                shareConf.title = options.shareTitle;
                shareConf.link = YmtApi.utils.addParam(options.shareUrl, {
                    shareSource: otherSource
                });
                shareConf.desc = options.shareTip;
                shareConf.imgUrl = options.sharePicUrl;

                YmtApi.onWeixinReady(function () {
                    wx.onMenuShareTimeline(shareConf);
                    wx.onMenuShareAppMessage(shareConf);
                });

                // YmtApi.showShareMask();
            });
        }

        return options;
    };
    /**
     * @method YmtApi.openChatList
     * @description 打开聊天列表
     * @param  {object} options
     * @example
     * YmtApi.openChatList();
     */
    YmtApi.openChatList = function (options) {
        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/chatList';
        }
    };
    /**
     * @method YmtApi.openChatDetail
     * @description 打开聊天详情
     * @param  {object} options 对话参数
     * @example 
     * YmtApi.openChatDetail({
     *     'SessionId': '1618229_1097476',
     *     'ToId': 1097476,
     *     'ToLoginId': 'foreverprince',
     *     'ToLogoUrl': 'http://p5.img.ymatou.com/upload/userlogo/big/1097476_cce6d77caa524c1f86b1e6dc5696a89a_b.jpg',
     *     'param': {
     *         'ProductModel': {
     *             'ProductId': '2b14bb1c-b734-4b52-b909-9c497365f12d',
     *             'Price': 92,
     *             'replayTag': 0,
     *             'ProductDesc': '美国进口Childlife钙镁锌补充液 婴儿幼儿童液体钙 474ml 现货',
     *             'ProductPics': ['http://p9.img.ymatou.com/G02/upload/product/big/M0A/39/63/CgvUBFXvLNCAFN3_AAD_TXljT4s321_b.jpg']
     *         }
     *     }
     * }
     *
     */
    YmtApi.openChatDetail = function (options) {
        var param = {
            SessionId: options.SessionId,
            ToId: options.ToId,
            ToLoginId: options.ToLoginId,
            ToLogoUrl: options.ToLogoUrl
        };
        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/chatDetail?param=' + JSON.stringify(param);
        }
        else if (YmtApi.isSaohuoApp) {
            param.param = JSON.stringify(options.param || options.exts);
            var str = YmtApi.utils.param(param);
            window.location.href = '/forBuyerApp/contactSeller?' + str;
        }
    };
    /**
     * @method YmtApi.previewImage
     * @description 预览图片接口
     * @param  {object} options
     *         urls     {array}  图片地址
     *         current  {number} 当前图片的索引值,对应urls中的数组坐标
     * @example
     * YmtApi.previewImage({
     *     urls: [
     *         'http://p9.img.ymatou.com/G02/upload/product/big/M0A/39/63/CgvUBFXvLNCAFN3_AAD_TXljT4s321_b.jpg',
     *         'http://p5.img.ymatou.com/upload/userlogo/big/1097476_cce6d77caa524c1f86b1e6dc5696a89a_b.jpg'
     *     ],
     *     current: 1
     * });
     */
    YmtApi.previewImage = function (options) {
        var param = '{"images":' + JSON.stringify(options.urls) + ',"currentInx":' + options.current + '}';
        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/imagePreview?param=' + param;
        }
        else if (YmtApi.isSaohuoApp) {}
        else if (YmtApi.isWechat) {
            hui.require(['jweixin_share'], function () {
                YmtApi.onWeixinReady(function () {
                    //微信图片预览
                    wx.previewImage({
                        current: options.urls[options.current], // 当前显示的图片链接
                        urls: options.urls // 需要预览的图片链接列表
                    });
                });

            });
        }
    };
    /**
     * @method YmtApi.openPay
     * @description 打开支付面板
     *  trandingIds       交易号(微信下trandingId支付不管成功失败,只一次有效)
     *  isIncludeBonded   是否包含杭保订单
     *  orderId          订单号
     * @example
     * YmtApi.openPay({
     *     trandingIds: 208340912,
     *     orderId: 106960422,
     *     isIncludeBonded: 1,
     *     param: {
     *         AccessToken: '855A2FC3EDC3D10831518774E90FB853CA1EF15E4E1686DDCBCD5505C0E09AA44B133A574D0BA115D9A2A038A72124C61365CB4414AED5FC'
     *     }
     * });
     */
    YmtApi.openPay = function (options) {
        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/orders/toPay?tid=' + options.trandingIds + (options.isIncludeBonded ? '&useBalance=disable&balanceTip=杭保商品不能使用余额支付' : '');
        }
        else if (YmtApi.isSaohuoApp) {
            window.location.href = 'http://sq0.ymatou.com/forBuyerApp/payMOrder?OrderId=' + options.orderId;
        }
        else if (YmtApi.isWechat) {
            var urlObj = YmtApi.utils.getUrlObj(),
                otherSource = urlObj['shareSource'];
            var url = options.url || 'http://matouapp.ymatou.com/forYmatouApp/orders/successful?tids=' + options.trandingIds;
            var exts = options.param || options.exts || {};
            //扫货成功回调页
            if (/saohuoApp/i.test(otherSource)) {
                url = 'http://matouapp.ymatou.com/forYmatouApp/payment/success?AccessToken=' + exts.AccessToken;
            }
            url = YmtApi.utils.addAuth(url);
            var str = 'http://wx.ymatou.com/Pay/wechat.html?tradingId=' + options.trandingIds + '&ret=' + encodeURIComponent(url);

            window.location.href = YmtApi.utils.addAuth(str);
        }
    };
    /**
     * @method YmtApi.toLogin
     * @description 唤出原生登录
     * @example
     * YmtApi.toLogin();
     */
    YmtApi.toLogin = function (url) {
        if (YmtApi.isYmtApp) {
            window.location.href = 'http://matouapp.ymatou.com/forYmatouApp/loginStatus?hasLogin=0';
        }
        else if (YmtApi.isSaohuoApp) {
            window.location.href = 'http://sq0.ymatou.com/forBuyerApp/loginStatus?hasLogin=0';
        }
        else if (YmtApi.isWechat) {
            url = url || window.location.href;
            window.location.href = 'http://login.ymatou.com/WeChatLogin?ret=' + encodeURIComponent(url);
        }
    };

    /**
     * @method YmtApi.openProductDetail
     * @description 打开C的商品详情(原生)
     * @example
     * YmtApi.openProductDetail({
     *     SellerName: 'bighero',
     *     param: {
     *         SellerModel: {
     *             Logo: 'http://static.ymatou.com/images/sprites/logo.png'
     *             Seller: 'bighero'
     *             SellerId: 100066
     *         },
     *         ProductModel: {
     *             ProductId: '66a92b97-2903-4927-a931-8a5045058742'
     *         }
     *     }
     * });
     */
    YmtApi.openProductDetail = function (options) {
        var param = {};
        if (YmtApi.isSaohuoApp) {
            param.SellerName = options.SellerName;
            param.param = JSON.stringify(options.param || options.exts);
            var str = YmtApi.utils.param(param);
            window.location.href = 'http://sq0.ymatou.com/forBuyerApp/productDetail?' + str;
        }
    };

    /**
     * @method YmtApi.diaryOpenComment
     * @description [社区]唤出原生评论
     * @param {Object} options 新加评论初始参数
     * @param {String} ObjectId 
     * @param {Number} ObjectType 
     * @param {String} replyCommentId 
     * @example
     * YmtApi.diaryOpenComment({
     *     ObjectId:'209--99232',
     *     ObjectType:4,
     *     replyCommentId: 209
     * });
     */
    YmtApi.diaryOpenComment = function (options) {
        if (YmtApi.isSaohuoApp) {
            //window.location.href = 'http://sq0.ymatou.com/forBuyerApp/payMOrder?OrderId=' + options.orderId;
            //http://sq0.alpha.ymatou.com/forBuyerApp/comment?ObjectId=209--99232&ObjectType=4&UserId=nil&DeviceToken=nil&AccessToken=nil&IDFA=nil&Wifi=1
            var str = 'http://diary.ymatou.com/forBuyerApp/comment?ObjectId=' + options.ObjectId + '&ObjectType=' + options.ObjectType;
            window.location.href = YmtApi.utils.addAuth(str);
        }
    };

    /**
     * @method YmtApi.diaryPublishReply
     * @description [社区]唤出原生回复
     * @param {Object} options 新加评论初始参数
     * @param {String} ObjectId 
     * @param {Number} ObjectType 
     * @example
     * YmtApi.diaryPublishReply({ObjectId:'209--99232',ObjectType:4});
     */
    YmtApi.diaryPublishReply = function (options) {
        if (YmtApi.isSaohuoApp) {
            //window.location.href = 'http://sq0.ymatou.com/forBuyerApp/payMOrder?OrderId=' + options.orderId;
            //http://sq0.alpha.ymatou.com/forBuyerApp/replyComment?ObjectId=209--99232&ObjectType=4&UserId=nil&DeviceToken=nil&AccessToken=nil&IDFA=nil&Wifi=1
            var str = 'http://diary.ymatou.com/forBuyerApp/replyComment?ObjectId=' + options.ObjectId + '&ObjectType=' + options.ObjectType;
            window.location.href = YmtApi.utils.addAuth(str);
        }
    };

    /**
     * @method YmtApi.diaryPublishNote
     * @description [社区]发表日记
     * @param {Object} options 发表日记初始参数
     * @example
     * YmtApi.diaryPublishNote({});
     */
    YmtApi.diaryPublishNote = function (options) {
        if (YmtApi.isSaohuoApp) {
            var str = 'http://diary.ymatou.com/forBuyerApp/publishNote';
            window.location.href = YmtApi.utils.addAuth(str);
        }
    };

    // 添加认证监听
    YmtApi.on('userStatusChange', function (ret) {
        YmtApi.auth = {
            AccessToken: ret.AccessToken,
            UserId: ret.UserId
        };
    });

    YmtApi.sendEvent = function (eventName, data) {
        if (Object.prototype.toString.call(data) === '[object String]') {
            data = JSON.parse(data);
        }
        YmtApi.trigger(eventName, data);
        return YmtApi;
    };
    /**
     * @method YmtApi.sendEvent
     * @description 触发事件
     * @example 
     * // 刷新页面
     * YmtApi.sendEvent('refreshPageEvent', {
     *     'PageType': 1,
     *     'Status': 1
     * });
     * // 用户登录态变更
     * YmtApi.sendEvent('userStatusChange', {
     *     'UserId': '1',
     *     'AccessToken ': 'AFEEEAAA'
     * });
     * // 用户点我喜欢
     * YmtApi.sendEvent('clickFavoriteEvent', {
     *     'Status': 1
     * });
     *
     * // 监听页面刷新事件
     * YmtApi.on('refreshPageEvent', function (res) {
     *     // res => {
     *     //     'PageType': 1,
     *     //     'Status': 1
     *     // };
     *     // Todo
     * });
     * // 监听用户登录态变更
     * YmtApi.on('userStatusChange', function (res) {
     *     // res => {
     *     //     'UserId': '1',
     *     //     'AccessToken ': 'AFEEEAAA'
     *     // };
     *     // Todo
     * });
     * // 监听用户点我喜欢
     * YmtApi.on('clickFavoriteEvent', function (res) {
     *     // res => {
     *     //     'Status': 1
     *     // };
     *     // Todo
     * });
     */


});