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