Commit 1f4a18ea by chenwq

重构系统配置,优化获取配置逻辑,增加无分享页面支持

1 parent 67b3f590
......@@ -6,51 +6,41 @@ const serverConfig = {
mockTimer: {},
mockCache: null,
};
const configModule = 'uplus-fapai-mp'
const configModule = "uplus-fapai-mp";
const configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`;
/**获取mock数据 */
const getMockData = async () => {
const MOCKDATA = wx.p.storage.get("mock_data");
try {
if (MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) {
return Promise.resolve(MOCKDATA);
} else {
if (!serverConfig.mockRequestCount) {
serverConfig.mockCache = null;
serverConfig.mockRequestCount = Date.now();
const data = await http.wx_request({ url:configUrl });;
data.createTime = Date.now();
serverConfig.mockCache = data;
wx.p.storage.set("mock_data", data);
return Promise.resolve(data);
} else {
const key = Date.now();
return new Promise((resolve) => {
serverConfig.mockTimer[key] = setInterval(() => {
if (serverConfig.mockCache) {
clearInterval(serverConfig.mockTimer[key]);
serverConfig.mockRequestCount = null;
resolve(serverConfig.mockCache);
}
}, 1e3);
});
}
}
} catch (error) {
if (serverConfig.mockTimer[key]) clearInterval(serverConfig.mockTimer[key]);
serverConfig.mockRequestCount = null;
return Promise.reject(error);
}
const getFrontConfig = async () => {
return new Promise((resolve, reject) => {
wx.showLoading({ title: "加载中..." });
wx.request({
// url: `${domain}${path}?method=${method}`,
url: configUrl,
// data,
method: "GET",
// header,
dataType: "json",
responseType: "text",
success(response) {
resolve(response.data);
},
fail(error) {
console.log(error, "error");
},
complete() {
wx.hideLoading();
},
})
});
};
// 图片版本号
const getImageVersion = async () => {
const accountInfo = await getMockData()
return accountInfo?.version || Date.now()
}
const getImageVersion = async () => {
const accountInfo = await getFrontConfig();
return accountInfo?.version || Date.now();
};
module.exports={
module.exports = {
getImageVersion,
getMockData
}
\ No newline at end of file
getFrontConfig,
};
......@@ -4,7 +4,8 @@
"pages/tab/index/index",
"pages/tab/mine/index",
"pages/webView/webView",
"pages/Login/Login"
"pages/Login/Login",
"pages/webView/h5FullNoShare/h5FullNoShare"
],
"requiredPrivateInfos": [
"getLocation"
......
......@@ -28,7 +28,7 @@ module.exports = Behavior({
widgetStatus
} = this.data, {
corpId
} = await wx.p.api.systemApi.getMockData()
} = await wx.p.api.systemApi.getFrontConfig()
if (kfUrl)
wx.openCustomerServiceChat({
extInfo: {
......
......@@ -11,14 +11,29 @@ Page({
userInfo: null,
firstChar: "",
scoreSummary: {
publishCount: '',
soldCount: '',
transactionRate: ''
publishCount: "",
soldCount: "",
transactionRate: "",
},
statConfig: [
{ icon: '/mine/icon-total.png', label: '发拍总数', key: 'publishCount', valueClass: 'text-black' },
{ icon: '/mine/icon-count.png', label: '成交数量', key: 'soldCount', valueClass: 'text-green' },
{ icon: '/mine/icon-rate.png', label: '成交率', key: 'transactionRate', valueClass: 'text-orange' }
{
icon: "/mine/icon-total.png",
label: "发拍总数",
key: "publishCount",
valueClass: "text-black",
},
{
icon: "/mine/icon-count.png",
label: "成交数量",
key: "soldCount",
valueClass: "text-green",
},
{
icon: "/mine/icon-rate.png",
label: "成交率",
key: "transactionRate",
valueClass: "text-orange",
},
],
showLogoutDialog: false,
logoutButtons: [
......@@ -87,9 +102,13 @@ Page({
});
},
goToInspection() {
async goToInspection() {
console.log(wx.p.api.systemApi)
const { report_webview } = await wx.p.api.systemApi.getFrontConfig()
console.log("获取的mock数据:", report_webview);
// TODO: 跳转到检测管理页面
// wx.p.router.go("/pages/inspection/index");
const targetUrl = `/pages/webView/h5FullNoShare/h5FullNoShare?url=${encodeURIComponent(report_webview)}&openType=miniApp`;
wx.navigateTo({ url: targetUrl });
},
onShow: function () {
......
......@@ -45,7 +45,7 @@
</glsx-image>
<text>账号ID</text>
</view>
<view class="info-value">D0001</view>
<view class="info-value">{{userInfo.userId}}</view>
</view>
<view class="info-item border-none">
<view class="info-label">
......
// pages/webView/h5FullNoShare/h5FullNoShare.js
import { createWebViewPageNoShare } from './webViewCommon'
Page(createWebViewPageNoShare())
{
"navigationStyle": "custom",
"usingComponents": {}
}
\ No newline at end of file
/* pages/webView/h5FullNoShare/h5FullNoShare.wxss */
\ No newline at end of file
<!--pages/webView/h5FullNoShare/h5FullNoShare.wxml-->
<block wx:if="{{flag}}">
<web-view src="{{url}}" bindmessage="handleMessage"></web-view>
</block>
\ No newline at end of file
// pages/webView/webViewCommon.js — 与 webView、h5Full(全屏 web-view)共用逻辑
import commonApi from '~/api/api'
const WEBVIEW_H5_TOKENS_KEY = 'dj_boutique_webview_h5_tokens'
let time
export function createWebViewPage(sharePagePath) {
return {
data: {
flag: true,
isH5Bind: false,
shareTitle: '报告详情',
// isH5Bind: false,
shareDisabled: false
},
getBaseUrl(url) {
if (!url || typeof url !== 'string') return ''
const idx = url.indexOf('?')
return idx >= 0 ? url.slice(0, idx) : url
},
appendParamsToUrl(url, params) {
if (!params || typeof params !== 'object' || Object.keys(params).length === 0)
return url
const searchParams = Object.entries(params)
.filter(([, v]) => v != null && v !== '')
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
.join('&')
if (!searchParams) return url
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}${searchParams}`
},
getParams(str) {
let params = str.split('?')
if (params.length < 2) return {}
let param = params[1].split('&')
let obj = {}
for (let i = 0; i < param.length; i++) {
let paramsA = param[i].split('=')
let key = paramsA[0]
let value = paramsA[1]
obj[key] = value
}
return obj
},
onLoad: function (options) {
const shareDisabled = options.noShare === '1' || options.noShare === 'true'
this.setData({ shareDisabled })
wx.p.wxApi.showLoading('加载中...')
let decodeUrl = decodeURIComponent(options.url)
const baseUrl = this.getBaseUrl(decodeUrl)
if (
options.openType &&
!/[?&#]openType=/.test(decodeUrl)
) {
decodeUrl = this.appendParamsToUrl(decodeUrl, {
openType: options.openType
})
}
// const baseUrl = this.getBaseUrl(decodeUrl)
try {
const stored = wx.getStorageSync(WEBVIEW_H5_TOKENS_KEY)
if (stored) {
const tokens = JSON.parse(stored)
const storedData = tokens[baseUrl]
if (storedData && typeof storedData === 'object') {
decodeUrl = this.appendParamsToUrl(decodeUrl, storedData)
}
}
} catch (e) {}
let param = this.getParams(decodeUrl)
if (param.urlParam) {
let query = JSON.parse(param.urlParam)
this.refresh = query.refresh
}
console.log(decodeUrl)
this.setData({
url: decodeUrl
})
wx.hideLoading()
if (shareDisabled) {
// 无参 hideShareMenu 全端隐藏「转发」;带 menus 的能力在部分系统上为 Beta/仅 Android,不能单独依赖
wx.hideShareMenu()
wx.hideShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
})
} else {
wx.showShareMenu({
withShareTicket: true,
menus: ['shareAppMessage', 'shareTimeline']
})
}
if (param.needIntercept) {
wx.enableAlertBeforeUnload &&
wx.enableAlertBeforeUnload({
message: '您还没有完成本次短课程学习,是否确定退出?',
success: modalRes => {
if (modalRes.confirm) {
wx.navigateBack()
}
}
})
this.setTime(param)
}
// AI收车报告,特殊处理跳转,将登录人名称带入
if (decodeUrl.includes('/ai-purchase') && options?.pushed) {
let userInfo = wx.p.wxApi.getUserInfo()
this.setData({
url: `${decodeUrl}?pushed=${options.pushed}&source=${options.source}&carConditionCode=${options.carConditionCode}&operator=${userInfo.name}`
})
}
if (decodeUrl.includes('/vehicle-detail')) this.setData({shareTitle: '车况信息'})
},
setTime(param) {
time = setTimeout(() => {
commonApi
.getShortCourseDetail({
id: param?.studyId
})
.then(res => {
let { code, data } = res
this.setTime()
if (code == 0) {
let flag = data?.aiReviewReport.every(item => item.examStatus === 2)
if (flag) wx.disableAlertBeforeUnload()
}
})
}, 5 * 1000)
},
onReady: function () {},
onShow: function () {
if (this.data.shareDisabled) {
wx.hideShareMenu()
wx.hideShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
})
}
if (this.refresh) {
this.setData(
{
flag: true
},
() => {
this.setData({
url: this.data.url
})
}
)
}
},
onHide: function () {
if (this.refresh) {
this.setData({
flag: false
})
}
},
handleMessage(e) {
const { data } = e.detail
console.log(data, 'handleMessage')
if (data) {
const eventChannel = this.getOpenerEventChannel()
eventChannel.emit('webViewMessage', data[0])
this.setData({
isH5Bind: true
})
const msgData = data[0]
if (msgData && typeof msgData === 'object' && msgData !== null) {
const baseUrl = this.getBaseUrl(this.data.url)
if (baseUrl) {
try {
const stored = wx.getStorageSync(WEBVIEW_H5_TOKENS_KEY)
const tokens = stored ? JSON.parse(stored) : {}
tokens[baseUrl] = msgData
wx.setStorageSync(WEBVIEW_H5_TOKENS_KEY, JSON.stringify(tokens))
} catch (err) {}
}
}
}
},
onUnload: function () {
let { url } = this.data
if (this.refresh) {
this.setData({
flag: false
})
}
if (url.includes('zyUpload')) {
const eventChannel = this.getOpenerEventChannel()
if (!this.data.isH5Bind) {
eventChannel.emit('webViewMessage', 'cancel')
}
}
if (url.includes('LearningExamTraineePage')) {
wx.setStorageSync('FROM_BEISENWEBVIEW', '1')
}
time && clearTimeout(time)
},
onPullDownRefresh: function () {},
onReachBottom: function () {},
onShareAppMessage(options) {
const { url, shareTitle } = this.data
if (options?.webviewUrl?.includes('/vehicle-detail')) shareTitle = '车况信息'
// onShareAppMessage() {
if (this.data.shareDisabled) return
// const { url } = this.data
const encoded = encodeURIComponent(url || '')
return {
title: shareTitle,
path: `${sharePagePath}?url=${encoded}`
}
},
onShareTimeline() {
const { url, shareTitle } = this.data
if (options?.webviewUrl?.includes('/vehicle-detail')) shareTitle = '车况信息'
if (this.data.shareDisabled) return
// const { url } = this.data
const encoded = encodeURIComponent(url || '')
return {
title: shareTitle,
query: `url=${encoded}`
}
}
}
}
/**
* 全屏 web-view,且不注册 onShareAppMessage / onShareTimeline。
* 微信规则:只有定义了这两个回调,右上角才会出现「转发 / 朋友圈」;
* 仅靠 return {} 或 hideShareMenu 在部分环境下仍可能可转发。
*/
export function createWebViewPageNoShare() {
const page = createWebViewPage('/pages/webView/h5FullNoShare')
delete page.onShareAppMessage
delete page.onShareTimeline
const origOnLoad = page.onLoad
page.onLoad = function (options) {
return origOnLoad.call(this, { ...options, noShare: '1' })
}
return page
}
......@@ -2,7 +2,7 @@
"libVersion": "3.15.2",
"projectname": "uplus-fapai-mp",
"setting": {
"urlCheck": true,
"urlCheck": false,
"coverView": true,
"lazyloadPlaceholderEnable": false,
"skylineRenderEnable": false,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!