Files
lucky_shop/common/js/diy.js

833 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import WxMap from 'common/js/map-wx-jssdk.js';
import Config from '@/common/js/config.js';
import util from '@/common/js/util.js';
import { classifyHttpError, httpErrorKey } from '@/common/js/http-error.js';
import { consumeNeedStartupAd, isColdLaunchPending } from '@/common/js/startup-ad.js';
let systemInfo = util.getDeviceInfo();
export default {
data() {
return {
// 自定义页面的数据,数据来源于后台配置
diyData: {
global: {
title: '',
popWindow: {
imageUrl: '',
count: -1,
link: {},
imgWidth: '',
imgHeight: ''
}
}
},
id: 0,
name: '',
topIndexValue: null,
statusBarHeight: systemInfo.statusBarHeight,
collectTop: 44,
showTip: false,
mpCollect: false,
mpShareData: null, //小程序分享数据
scrollTop: 0, // 滚动位置
paddingTop: (44 + systemInfo.statusBarHeight) + 'px',
marginTop: -(44 + systemInfo.statusBarHeight) + 'px',
followOfficialAccount: null, // 关注公众号组件
latitude: null, // 纬度
longitude: null, // 经度
currentPosition: '', // 当前位置
nearestStore: null, // 离自己最近的门店
storeTimeOut: null, // 没有获取到定位,则获取默认门店
locationModule: '', // 模式,locationPicker H5选择地图
diyRoute: '', // 页面路由
openBottomNav: false,
isShowCopyRight: false,
// getDiyInfo 节流
diyInfoLoading: false, // 是否正在请求
lastDiyInfoTime: 0, // 上次成功加载的时间戳
lastDiyInfoLang: '', // 上次加载时的语言,语言切换时强制刷新
diyInfoTtl: 3 * 60 * 1000, // 3分钟内不重复请求
// diy 数据网络加载失败时的页面内错误提示(比 showModal 在各端更可靠)
diyLoadError: false,
diyLoadErrorMsg: '',
diyLoadErrorUrl: '', // 出错的网络请求地址
//启动广告
adv: {},
};
},
onLoad(option) {
uni.hideTabBar();
if (option.source_member) uni.setStorageSync('source_member', option.source_member);
// 小程序扫码进入
if (option.scene) {
var sceneParams = decodeURIComponent(option.scene);
sceneParams = sceneParams.split('&');
if (sceneParams.length) {
sceneParams.forEach(item => {
if (item.indexOf('m') != -1) uni.setStorageSync('source_member', item.split('-')[1]);
});
}
}
// #ifdef H5
// H5地图选择位置回调数据
if (option.module && option.module == 'locationPicker') {
option.name = ''; // 清空地址
this.locationModule = option.module;
this.latitude = option.latng.split(',')[0];
this.longitude = option.latng.split(',')[1];
}
// #endif
this.id = option.id || 0;
this.name = option.name || '';
uni.removeStorageSync('manual_store_info'); // 清除手动切换门店缓存
uni.removeStorageSync('manual_change_store'); // 清楚手动切换门店标识
// H5才会执行
if (this.locationModule == 'locationPicker') {
// H5地图选址后的回调
this.getNearestStore();
this.getCurrentLocation();
} else if (this.mapConfig.wap_is_open == 1) {
// 每次都要定位,获取当前位置
/*this.$util.getLocation({
fail: (res) => {
// 拒绝定位,进入默认总店
this.enterDefaultStore();
}
});*/
// 如果3秒没有获取到定位,则获取默认门店,H5使用
// #ifdef H5
this.storeTimeOut = setTimeout(() => {
this.enterDefaultStore();
}, 1000 * 3);
// #endif
} else {
// 关闭定位
this.enterDefaultStore();
}
},
onShow() {
this.init();
},
onHide() {
if (this.storeTimeOut) {
clearTimeout(this.storeTimeOut);
}
// 跳转页面要关闭门店弹出框
this.closeChooseStorePopup();
// 清除限时秒杀定时器
this.$store.commit('setDiySeckillInterval', 0);
},
computed: {
bgColor() {
let str = '';
if (this.diyData && this.diyData.global) {
str = this.diyData.global.pageBgColor;
}
return str;
},
bgImg() {
let str = '';
if (this.diyData && this.diyData.global) {
str = this.diyData.global.topNavBg ? 'url(' + this.$util.img(this.diyData.global.bgUrl) + ')' : this.diyData.global.pageBgColor;
}
return str;
},
bgUrl() {
let str = '';
if (this.diyData && this.diyData.global) {
str = this.diyData.global.topNavBg ? 'transparent' : this.diyData.global.bgUrl;
}
return str;
},
backgroundUrl() {
var str = this.diyData.global.bgUrl && this.diyData.global.bgUrl != 'transparent' ? 'url(' + this.$util.img(this.diyData.global.bgUrl) + ') ' : '';
return str;
},
textNavColor() {
if (this.diyData && this.diyData.global && this.diyData.global.textNavColor) {
return this.diyData.global.textNavColor;
} else {
return '#ffffff';
}
},
//计算首页弹框的显示宽高
popWindowStyle() {
// 做大展示宽高
let max_width = 290;
let max_height = 410;
// 参照宽高
let refer_width = 290;
let refer_height = 290;
let scale = this.diyData.global.popWindow.imgHeight / this.diyData.global.popWindow.imgWidth;
let width, height;
if (scale < refer_height / refer_width) {
width = max_width;
height = width * scale;
} else {
height = max_height;
width = height / scale;
}
let obj = '';
if (this.diyData.global.popWindow && this.diyData.global.popWindow.count != -1 && this.diyData.global.popWindow.imageUrl) {
obj += 'height:' + (height * 2) + 'rpx;';
obj += 'width:' + (width * 2) + 'rpx;';
}
return obj;
}
},
watch: {
location: function (nVal) {
if (nVal) {
this.latitude = nVal.latitude;
this.longitude = nVal.longitude;
this.getNearestStore();
this.getCurrentLocation();
}
}
},
methods: {
play() {
},
async init() {
// 定位信息过期后,重新获取定位
if (this.mapConfig.wap_is_open == 1 && this.locationStorage && this.locationStorage.is_expired) {
this.$util.getLocation({
fail: (res) => {
// 拒绝定位,进入默认总店
this.enterDefaultStore();
}
});
}
if (this.storeToken) {
//记录分享关系
if (uni.getStorageSync('source_member')) {
this.$util.onSourceMember(uni.getStorageSync('source_member'));
}
}
console.log('[DIY][init] calling getDiyInfo, storeToken=', !!this.storeToken);
await this.getDiyInfo();
//获取启动广告
await this.getDiyAdv();
this.$store.commit('setDiySeckillInterval', 1);
//小程序分享
// #ifdef MP-WEIXIN
this.$util.getMpShare().then(res => {
this.mpShareData = res;
});
// #endif
let manualChangeStore = uni.getStorageSync('manual_change_store'); // 手动切换门店
if (manualChangeStore) {
uni.removeStorageSync('manual_change_store');
// 滚动至顶部
uni.pageScrollTo({
duration: 200,
scrollTop: 0
});
}
},
callback() {
if (this.$refs.indexPage) {
this.$refs.indexPage.initPageIndex();
}
},
//计算高度
getHeight() {
// #ifdef H5
if (this.diyData && this.diyData.global && this.diyData.global.navBarSwitch) {
// H5端,导航栏样式1 2 3不显示,要减去高度
if ([1, 2, 3].indexOf(parseInt(this.diyData.global.navStyle)) != -1) {
this.paddingTop = 0;
this.marginTop = 0;
}
}
// #endif
// #ifdef MP || APP-PLUS
let time = setInterval(() => {
this.$nextTick(() => {
const query = uni.createSelectorQuery().in(this);
query.select('.page-header').boundingClientRect(data => {
if (data && data.height) {
// 从状态栏高度开始算
this.paddingTop = data.height + 'px';
this.marginTop = -data.height + 'px';
clearInterval(time);
}
}).exec();
});
}, 50);
// #endif
},
async getDiyAdv() {
//启动广告
let res = await this.$api.sendRequest({
url: '/api/diyview/getstartadv',
data: {},
async: false
});
// 接口把启动广告配置放在 data 字段(少数环境也可能放在 value), 两者兼容,
// 避免取到 undefined 后模板 v-if 抛错导致 uni-popup 不渲染、真机广告弹不出来
let advData = (res && (res.data != null ? res.data : res.value)) || {};
this.adv = advData;
// 后台配置: advshow=1 开启启动广告; advtype 决定弹出策略
// advtype == 1: 首次弹出 —— 仅第一次进入小程序弹出(持久化标记, 清缓存后可再弹)
// advtype == 0: 每次弹出 —— 每次"重新进入小程序"都弹出(不含 Tab 切换回首页)
if (this.adv.advshow == 1) {
setTimeout(async () => {
// 隐私协议未同意时, 先等用户点击隐私协议(同意/拒绝)关闭弹窗,
// 否则广告弹窗会被隐私弹窗(z-index:5000)盖住, 真机上表现为"点了隐私协议后广告不弹"
await this._waitPrivacyResolved();
if (!this.$refs.uniPopupWindow) return;
// 先判定本次是否需要弹出, 避免无谓的图片预加载
let shouldOpen = false;
let isFirstType = false;
if (this.adv.advtype == 1) {
// 首次弹出: 从未展示过才弹
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if (popwindow_count == '' || popwindow_count == 0) {
shouldOpen = true;
isFirstType = true;
}
} else {
// 每次弹出: 冷启动首次 或 真正"重新进入小程序"(App 前后台切换)时弹出,
// 由 App.onShow 在重新进入时置位的信号驱动, 切 Tab 不会触发 App.onShow 故不弹
if (consumeNeedStartupAd() || isColdLaunchPending()) {
shouldOpen = true;
}
}
if (!shouldOpen) return;
// 关键: 广告图片是网络图, 而 uni-popup 用 v-if 在 open() 时才渲染 slot,
// 图片要等弹窗打开后才开始请求/解码, 真机网络慢时就会"一截一截"逐步显示。
// 先把所有广告图片预加载进本地缓存, 全部就绪后再 open, 使弹窗一次性完整出现。
await this._preloadAdvImages(this.adv.list);
if (!this.$refs.uniPopupWindow) return;
this.$refs.uniPopupWindow.open();
if (isFirstType) {
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
}
}, 500);
}
},
/**
* 等待隐私协议流程结束后再弹启动广告
* - 鸿蒙元服务: 隐私由系统托管, 应用层不弹自建弹窗, 直接放行
* - 已同意过(storage privacyAgreed): 无需等待, 直接放行
* - 未同意: 监听 PrivacyManager 广播的 privacy:agreed / privacy:disagreed,
* 用户点击隐私协议(同意/拒绝)关闭弹窗后放行
* - 兜底超时: 隐私协议因规则未弹等情况永不 emit 时也要弹广告, 避免卡死
* @param {number} [maxWait=15000]
* @returns {Promise<void>}
*/
_waitPrivacyResolved(maxWait = 15000) {
// 鸿蒙元服务: 隐私协议由系统托管, 应用层不弹自建隐私弹窗, 无需等待
// #ifdef MP-HARMONY
return Promise.resolve();
// #endif
// 已经同意过 → 隐私弹窗不会再出现, 直接放行
if (uni.getStorageSync('privacyAgreed')) return Promise.resolve();
return new Promise((resolve) => {
let done = false;
const finish = () => {
if (done) return;
done = true;
uni.$off('privacy:agreed', finish);
uni.$off('privacy:disagreed', finish);
clearTimeout(timer);
resolve();
};
uni.$on('privacy:agreed', finish);
uni.$on('privacy:disagreed', finish);
// 兜底: 隐私协议因规则未弹 / 一直未处理时, 超时后也要弹广告
const timer = setTimeout(finish, maxWait);
});
},
// 无法从网络获取 diy 数据时:在页面内渲染错误横幅(各端可靠、一定可见)
// 同时通过 uni.$emit 通知 splash-state 关闭启动屏 (否则 strict 模式永远不关)
// @param {Object|string} [err] 网络异常对象 {errMsg, statusCode} / 服务端消息字符串
// @param {string} [url] 出错的请求地址(完整 URL),用于横幅展示
// @param {string} [errorType] 错误类型: 'network' | 'no-response' | 'business'
_showDiyLoadError(err, url, errorType) {
this.diyLoadErrorMsg = this._buildDiyErrorMsg(err);
this.diyLoadErrorUrl = url || '';
this.diyLoadError = true;
// 通知 splash: diy 加载失败, 启动屏应该让位给错误横幅
// 用 uni.$emit 而非直接 import splash-state, 避免循环依赖
// reason 拼成 'diy-{errorType}-error' 方便业务方区分 (splash:diy-error 事件)
const reason = errorType ? `diy-${errorType}-error` : 'diy-load-error'
try { uni.$emit && uni.$emit('diy:load-error', { reason, errorType, err, url }); } catch (e) { }
},
// 根据错误信息组织更详细的提示文案
// 说明:remote-only 模式下 $lang 可能返回空串,故统一用 `|| 中文兜底` 保证非空
_buildDiyErrorMsg(err) {
const info = classifyHttpError(err);
// 服务端明确返回的业务消息(字符串):直接透传
if (info.type === 'business') return info.raw;
const key = httpErrorKey(info.type);
let reason = this.$lang(key);
// HTTP 状态码类错误:把 statusCode 拼到 reason 后面
if (info.statusCode) reason += '(' + info.statusCode + ')';
// empty / unknown 不走模板,直接返回通用网络异常
if (info.type === 'empty' || info.type === 'unknown') return reason;
const tpl = this.$lang('diy.loadFailTpl', { reason });
return tpl;
},
// 错误横幅「重试」入口
retryDiyInfo() {
this.diyLoadError = false;
this.diyLoadErrorMsg = '';
this.diyLoadErrorUrl = '';
this.getDiyInfo(true);
},
async getDiyInfo(force = false) {
// 节流:正在请求 / N 秒内已加载过 / 语言未变 -> 跳过
const now = Date.now();
const currentLang = uni.getStorageSync("lang") || '';
console.log('[DIY][getDiyInfo] start', 'force=', force, 'id=', this.id, 'name=', this.name, 'lang=', currentLang, 'loading=', this.diyInfoLoading, 'lastAt=', this.lastDiyInfoTime, 'lastLang=', this.lastDiyInfoLang);
if (!force) {
if (this.diyInfoLoading) {
console.log('[DIY][getDiyInfo] skip: already loading');
return;
}
if (this.lastDiyInfoTime && (now - this.lastDiyInfoTime) < this.diyInfoTtl
&& this.lastDiyInfoLang === currentLang) {
console.log('[DIY][getDiyInfo] skip: throttled by ttl');
return;
}
}
this.diyInfoLoading = true;
let res;
// 出错时用于展示的完整请求地址(Request URL),与 http.js 拼接/归一化方式保持一致
const diyInfoUrl = '/api/diyview/info';
const diyInfoFullUrl = ((Config.baseUrl || '') + diyInfoUrl).replace(/(?<!:)\/+/g, '/');
try {
res = await this.$api.sendRequest({
url: diyInfoUrl,
data: {
id: this.id,
name: this.name,
en_type: currentLang,
},
async: false
});
} catch (e) {
console.error('[DIY][getDiyInfo] request failed', e);
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
this.diyInfoLoading = false;
// 无法从网络获取数据时,页面内显示错误横幅并提供重试(带详细原因 + 请求地址)
// errorType='network': 网络异常 (uni.request catch)
this._showDiyLoadError(e, diyInfoFullUrl, 'network');
return;
}
this.diyInfoLoading = false;
console.log('[DIY][getDiyInfo] got response', 'code=', res && res.code, 'hasData=', !!(res && res.data), 'valueType=', res && res.data && typeof res.data.value, 'valueLen=', res && res.data && (typeof res.data.value === 'string' ? res.data.value.length : (res.data.value ? res.data.value.length : null)));
if (!res || res.code != 0 || !res.data) {
console.warn('[DIY][getDiyInfo] invalid response', JSON.stringify(res));
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
// 完全没有拿到网络响应,视为无法从网络获取数据,页面内显示错误横幅
if (!res) {
// errorType='no-response': 完全没有 res 对象
this._showDiyLoadError(null, diyInfoFullUrl, 'no-response');
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
if (res && res.code == -3) {
this.$util.showToast({
title: res.message
});
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
// 拿到响应但业务失败 / 无数据(如接口 404 返回 200+错误码、code!=0)
// 同样视为无法获取到 diy 数据,页面内显示错误横幅
// errorType='business': 业务失败 (code!=0 / 消息提示)
this._showDiyLoadError(res && res.message, diyInfoFullUrl, 'business');
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
this.lastDiyInfoTime = now;
this.lastDiyInfoLang = currentLang;
// 成功加载后清除错误提示
this.diyLoadError = false;
this.diyLoadErrorMsg = '';
this.diyLoadErrorUrl = '';
let diyDataValue = res.data;
if (diyDataValue.value) {
try {
this.diyData = JSON.parse(diyDataValue.value);
} catch (parseErr) {
console.error('[DIY][getDiyInfo] JSON.parse(value) failed', parseErr, 'value preview=', String(diyDataValue.value).slice(0, 200));
throw parseErr;
}
console.log('[DIY][getDiyInfo] parsed diyData', 'globalKeys=', this.diyData && this.diyData.global ? Object.keys(this.diyData.global) : null, 'valueCount=', this.diyData && this.diyData.value && this.diyData.value.length, 'topIndexValue before=', this.topIndexValue);
// 导航栏标题要根据语言环境切换
// 优先使用 title_map 多语言 map,没有则回退到 title / en_title
const title = this.$langConfig.getField(this.diyData?.global, 'title');
if (title) this.$langConfig.title(title);
this.mpCollect = this.diyData.global.mpCollect;
this.setPublicShare();
/* if (this.diyData.global.popWindow && this.diyData.global.popWindow.imageUrl) {
// 弹框形式,首次弹出 1,每次弹出 0
setTimeout(() => {
if (this.diyData.global.popWindow.count == 1) {
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
this.$refs.uniPopupWindow && popwindow_count == 1)) {
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
}
} else if (this.diyData.global.popWindow.count == 0) {
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
}
}, 500);
}*/
// 修改diy数据结构排序
let searchIndex = -1;
let topCategoryIndex = -1;
this.diyData.value.forEach((item, index) => {
if (item.componentName == 'Search') {
if (item.positionWay == 'fixed') {
searchIndex = index;
}
}
if (item.componentName == 'TopCategory') {
topCategoryIndex = index;
}
})
if (searchIndex != -1 && topCategoryIndex != -1) {
let searchData = this.diyData.value.slice(searchIndex, searchIndex + 1);
let topCategoryData = this.diyData.value.slice(topCategoryIndex, topCategoryIndex + 1);
this.diyData.value.splice(searchIndex, 1);
if (searchIndex > topCategoryIndex) {
this.diyData.value.splice(topCategoryIndex, 1);
this.diyData.value.splice(0, 0, ...topCategoryData);
this.diyData.value.splice(1, 0, ...searchData);
} else
this.diyData.value.splice(0, 0, ...searchData);
} else if (searchIndex != -1 && topCategoryIndex == -1) {
let searchData = this.diyData.value.slice(searchIndex, searchIndex + 1);
this.diyData.value.splice(searchIndex, 1);
this.diyData.value.splice(0, 0, ...searchData);
}
for (var i = 0; i < this.diyData.value.length; i++) {
// 分类导航组件
if (this.diyData.value[i].componentName == 'TopCategory') {
this.topIndexValue = this.diyData.value[i];
this.topIndexValue.moduleIndex = i; //设置定位索引,根据此来确定定位顺序
this.diyData.value.splice(i, 1);
continue;
}
// 关注公众号组件
if (this.diyData.value[i].componentName == 'FollowOfficialAccount') {
this.followOfficialAccount = this.diyData.value[i];
// #ifdef H5
this.diyData.value.splice(i, 1);
// #endif
continue;
}
}
// #ifdef MP
//小程序收藏
if (!uni.getStorageSync('isCollect') && this.diyData.global.mpCollect) {
this.$refs.collectPopupWindow.open();
this.showTip = true;
}
// #endif
this.getHeight();
if (this.diyData && this.diyData.global) {
this.openBottomNav = this.diyData.global.openBottomNav;
}
this.isShowCopyRight = true;
console.log('[DIY][getDiyInfo] done', 'topIndexValue after=', this.topIndexValue && this.topIndexValue.componentName, 'valueCount=', this.diyData.value.length, 'openBottomNav=', this.openBottomNav, 'isShowCopyRight=', this.isShowCopyRight);
} else {
console.warn('[DIY][getDiyInfo] no value in res.data', JSON.stringify(diyDataValue).slice(0, 200));
}
},
/**
* 预加载启动广告图片
* 广告弹窗由 uni-popup 在 open() 时才用 v-if 渲染内容, 图片是网络图,
* 若等到弹窗打开后才开始加载, 真机网络慢时会出现"一截一截"逐步显示。
* 这里提前把图片下载进本地缓存, 等全部加载完成(或超时)后再弹出,
* 使弹窗一次性完整呈现。
* @param {Array} list - adv.list, 元素形如 { imageUrl, link }
* @param {number} [timeout=4000] - 单张兜底超时, 避免个别图片卡住导致广告永不弹出
* @returns {Promise<void>}
*/
_preloadAdvImages(list, timeout = 4000) {
if (!list || !list.length) return Promise.resolve();
const tasks = list.map((item) => {
return new Promise((resolve) => {
const url = (item && item.imageUrl) ? this.$util.img(item.imageUrl) : '';
if (!url) return resolve();
let done = false;
const finish = () => {
if (done) return;
done = true;
clearTimeout(timer);
resolve();
};
const timer = setTimeout(finish, timeout);
try {
// getImageInfo 会下载图片并写入本地缓存, 之后 image 组件可直接命中缓存
uni.getImageInfo({
src: url,
success: finish,
fail: finish
});
} catch (e) {
finish();
}
});
});
return Promise.all(tasks).then(() => {});
},
closePopupWindow() {
this.$refs.uniPopupWindow.close();
},
closeCollectPopupWindow() {
this.$refs.collectPopupWindow.close();
uni.setStorageSync('isCollect', true);
},
uniPopupWindowFn() {
this.$util.diyRedirectTo(this.diyData.global.popWindow.link);
this.closePopupWindow();
},
openChooseStorePopup() {
if (this.globalStoreConfig && this.globalStoreConfig.confirm_popup_control == 1) {
let storeInfo = this.globalStoreInfo;
// 首次进入门店,没有门店信息 || 当前位置的门店和缓存门店不一致要弹框
if (!storeInfo || storeInfo && this.nearestStore && storeInfo.store_id != this.nearestStore.store_id) {
if (this.$refs.chooseStorePopup) this.$refs.chooseStorePopup.open();
}
}
let manualStoreInfo = uni.getStorageSync('manual_store_info'); // 手动选择门店
if (manualStoreInfo) {
this.nearestStore = manualStoreInfo;
}
this.changeStore(this.nearestStore); // 切换门店数据
},
closeChooseStorePopup() {
if (this.$refs.chooseStorePopup) this.$refs.chooseStorePopup.close();
},
// 确认进入门店
enterStore() {
this.closeChooseStorePopup();
},
// 选择其他门店
chooseOtherStore() {
this.$util.redirectTo('/pages_tool/store/list');
this.closeChooseStorePopup();
},
// 打开地图重新选择位置
reposition() {
// #ifdef MP
/*uni.chooseLocation({
success: res => {
this.latitude = res.latitude;
this.longitude = res.longitude;
this.currentPosition = res.name;
this.getNearestStore();
this.getCurrentLocation();
},
fail(res) {
uni.getSetting({
success: function (res) {
var statu = res.authSetting;
if (!statu['scope.userLocation']) {
uni.showModal({
title: '是否授权当前位置',
content: '需要获取您的地理位置,请确认授权,否则地图功能将无法使用',
success(tip) {
if (tip.confirm) {
uni.openSetting({
success: function (data) {
if (data.authSetting['scope.userLocation'] === true) {
this.$util.showToast({
title: '授权成功'
});
//授权成功之后,再调用chooseLocation选择地方
setTimeout(function () {
uni.chooseLocation({
success: data => {
this.latitude = res.latitude;
this.longitude = res.longitude;
this.currentPosition = res.name;
this.getNearestStore();
this.getCurrentLocation();
}
});
}, 1000);
}
}
});
} else {
this.$util.showToast({
title: '授权失败'
});
}
}
});
}
}
});
}
});*/
// #endif
// #ifdef H5
let backurl = Config.h5Domain; // 地图选择位置后的回调页面路径
window.location.href = 'https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=' +
encodeURIComponent(backurl) + '&key=' + Config.mpKey + '&referer=myapp';
// #endif
},
// 获取离自己最近的一个门店
getNearestStore() {
let data = {};
if (this.latitude && this.longitude) {
data.latitude = this.latitude;
data.longitude = this.longitude;
}
this.$api.sendRequest({
url: '/api/store/nearestStore',
data: data,
success: res => {
if (res.code == 0 && res.data) {
this.nearestStore = res.data;
this.nearestStore.show_address = this.nearestStore.full_address.replace(/,/g, ' ') + ' ' + this.nearestStore.address;
this.openChooseStorePopup();
}
}
});
},
// 根据经纬度获取位置
getCurrentLocation() {
var _this = this;
let data = {};
if (this.latitude && this.longitude) {
data.latitude = this.latitude;
data.longitude = this.longitude;
}
this.$api.sendRequest({
url: '/api/store/getLocation',
data: data,
success: res => {
if (res.code == 0 && res.data) {
this.currentPosition = res.data.formatted_addresses.recommend; // 结合知名地点形成的描述性地址,更具人性化特点
} else {
this.currentPosition = this.$lang('diy.locationNotAvailable');
}
}
});
},
// 定位失败,进入默认门店
enterDefaultStore() {
if (this.defaultStoreInfo) {
if (!this.nearestStore) {
this.nearestStore = this.defaultStoreInfo;
this.nearestStore.show_address = this.nearestStore.full_address.replace(/,/g, ' ') + ' ' + this.nearestStore.address;
}
if (this.currentPosition == '') this.currentPosition = this.$lang('diy.locationNotAvailable');
this.openChooseStorePopup();
}
},
// 设置公众号分享
setPublicShare() {
let shareUrl = this.$config.h5Domain + this.diyRoute;
if (this.id) shareUrl += '?id=' + this.id;
else if (this.name) shareUrl += '?name=' + this.name;
this.$util.setPublicShare({
title: this.$langConfig.getField(this.diyData.global, 'title'),
desc: '',
link: shareUrl,
imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''
});
}
},
onPageScroll(e) {
this.scrollTop = e.scrollTop;
if (this.$refs.topNav) {
if (e.scrollTop >= 20) {
this.$refs.topNav.navTopBg();
} else {
this.$refs.topNav.unSetnavTopBg();
}
}
},
// 下拉刷新
onPullDownRefresh() {
this.$store.commit('setComponentRefresh');
setTimeout(() => {
uni.stopPullDownRefresh();
}, 50);
},
// 分享给好友
onShareAppMessage() {
return this.mpShareData?.appMessage;
},
// 分享到朋友圈
onShareTimeline() {
return this.mpShareData?.timeLine;
}
}