This commit is contained in:
2025-10-27 15:55:29 +08:00
commit 6632080b83
513 changed files with 117442 additions and 0 deletions

BIN
common/css/custom.ttf Normal file

Binary file not shown.

234
common/css/diy.scss Normal file
View File

@@ -0,0 +1,234 @@
.collectPopupWindow {
position: relative;
height: 113rpx;
width: 510rpx;
margin-left: calc(100% - 530rpx);
image {
width: 100%;
height: 100%;
}
text {
color: #ff4544 !important;
font-size: 24rpx !important;
position: absolute;
top: 48rpx;
right: 25rpx;
}
}
.zhezhao {
width: 100vw;
height: 100vh;
background-color: transparent;
}
image {
max-width: 100% !important;
max-height: 100% !important;
}
.diy-wrap {
/* #ifdef H5 */
height: calc(100vh - 88rpx);
/* #endif */
/* #ifdef MP-WEIXIN */
height: 100vh;
/* #endif */
}
.page-img {
background-size: contain !important;
background-repeat: no-repeat !important;
}
.page-header {
background-size: 100% !important;
background-repeat: no-repeat !important;
background-position: top center;
background-attachment: fixed;
}
.bg-index {
width: 100%;
height: 100%;
box-sizing: border-box;
background-size: 100% !important;
background-repeat: no-repeat !important;
}
.wap-floating {
text {
display: block;
font-size: 60rpx;
color: #ffffff;
text-align: center;
}
}
.wap-floating-collect .uni-popup__mask {
background: transparent;
}
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}
.popup-box {
width: 450rpx;
background: #ffffff;
border-radius: $border-radius;
overflow: hidden;
.close_title {
width: 100%;
text-align: center;
height: 70rpx;
line-height: 70rpx;
font-size: $font-size-base;
}
.close_content {
width: 100%;
max-height: 500rpx;
padding: $padding;
box-sizing: border-box;
}
.close_content_box {
width: 100%;
max-height: 460rpx;
line-height: 1.3;
}
}
.noStore-text {
color: #000000 !important;
}
.isStore-top {
margin-bottom: 10rpx;
}
.keep-on-record {
text-align: center;
padding-bottom: 20rpx;
image {
width: 150rpx;
height: 60rpx;
}
}
.padding-bottom {
padding-bottom: 40rpx !important;
}
.choose-store {
/deep/ .uni-popup__wrapper{
background: none!important;
}
}
.choose-store-popup {
padding: 30rpx;
background-color: #fff;
.head-wrap {
font-weight: bold;
font-size: $font-size-toolbar;
text-align: center;
margin-bottom: 20rpx;
color: #202021;
}
.position-wrap {
display: flex;
color: #202021;
align-items: center;
margin-bottom: 20rpx;
.icon-dizhi {
font-weight: bold;
font-size: $font-size-tag;
margin-right: 10rpx;
}
.address {
font-weight: bold;
font-size: $font-size-tag;
margin-right: 10rpx;
flex: 1;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
}
.reposition {
display: flex;
align-items: center;
.iconfont {
font-size: $font-size-base;
margin-right: 6rpx;
}
text {
font-size: $font-size-tag;
color: #fd463e;
}
}
}
.store-wrap {
border: 1px solid $base-color;
border-radius: 16rpx;
padding: 20rpx 30rpx;
margin-bottom: 30rpx;
.tag {
background-color: #fee9ea;
color: #fd463e;
font-size: $font-size-activity-tag;
display: inline-block;
border-radius: 6rpx;
padding: 4rpx 12rpx;
// #ifdef H5
transform: scale(0.8);
margin-left: -10rpx;
// #endif
}
.store-name {
margin: 10rpx 0;
font-weight: bold;
color: #202021;
font-size: $font-size-toolbar;
}
.address {
color: #5f6067;
font-size: $font-size-tag;
margin-bottom: 10rpx;
}
.distance {
display: flex;
align-items: center;
color: #5f6067;
font-size: $font-size-tag;
.iconfont {
font-size: $font-size-base;
margin-right: 10rpx;
}
}
}
button {
border-radius: 40rpx;
}
.other-store {
display: flex;
align-items: center;
color: #5e6066;
font-weight: bold;
justify-content: center;
margin-top: 20rpx;
margin-bottom: 20rpx;
.iconfont {
margin-left: 10rpx;
font-size: $font-size-tag;
}
}
}
.page-bottom {
margin-top: 20rpx;
}

1562
common/css/goods_detail.scss Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
/* 扩展图标库文件 */

5731
common/css/icondiy.css Normal file

File diff suppressed because one or more lines are too long

463
common/css/iconfont.css Normal file

File diff suppressed because one or more lines are too long

876
common/css/main.scss Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

103
common/js/auth.js Normal file
View File

@@ -0,0 +1,103 @@
export default {
data() {
return {
authInfo: {}
}
},
methods: {
/**
* 获取用户登录凭证code
*/
getCode(callback) {
// 微信小程序
// #ifdef MP-WEIXIN
uni.login({
provider: 'weixin',
timeout: 3000,
success: res => {
if (res.code) {
this.$api.sendRequest({
url: '/weapp/api/weapp/authcodetoopenid',
data: {
code: res.code
},
success: res => {
if (res.code >= 0) {
if (res.data.openid) this.authInfo.weapp_openid = res.data
.openid;
if (res.data.unionid) this.authInfo.wx_unionid = res.data
.unionid;
typeof callback == 'function' && callback(this.authInfo);
} else {
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
}
}
})
}
},
fail: (res) => {
// #ifdef MP-WEIXIN
let scene = wx.getLaunchOptionsSync().scene;
if ([1154, 1155].indexOf(scene) == -1) {
this.$util.showToast({
title: res.errMsg
});
}
// #endif
}
})
// #endif
// #ifdef MP-ALIPAY
uni.login({
timeout: 3000,
success: res => {
if (res.code) {
this.$api.sendRequest({
url: '/aliapp/api/aliapp/authcodetouserid',
data: {
code: res.code
},
success: res => {
if (res.code >= 0) {
if (res.data.user_id) this.authInfo.ali_openid = res.data
.user_id;
typeof callback == 'function' && callback(this.authInfo);
} else {
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
}
}
})
}
},
fail: (err) => {
this.$util.showToast({
title: res.errMsg
});
}
})
// #endif
// #ifdef H5
if (this.$util.isWeiXin()) {
this.$api.sendRequest({
url: '/wechat/api/wechat/authcode',
data: {
redirect_url: location.href,
scopes: 'snsapi_userinfo'
},
success: res => {
if (res.code >= 0) {
location.href = res.data;
}
}
});
}
// #endif
}
}
}

50
common/js/config.js Normal file
View File

@@ -0,0 +1,50 @@
var config = {
// baseUrl: site.baseUrl,
// imgDomain: site.baseUrl,
// h5Domain: site.baseUrl,
//api请求地址
baseUrl: 'https://xcx30.5g-quickapp.com/',
// 图片域名
imgDomain: 'https://xcx30.5g-quickapp.com/',
// H5端域名
h5Domain: 'https://xcx30.5g-quickapp.com/',
// // api请求地址
// baseUrl: 'https://tsaas.liveplatform.cn/',
// // 图片域名
// imgDomain: 'https://tsaas.liveplatform.cn/',
// // H5端域名
// h5Domain: 'https://tsaas.liveplatform.cn/',
// api请求地址
// baseUrl: 'http://saas.cn/',
// // 图片域名
// imgDomain: 'http://saas.cn/',
// // H5端域名
// h5Domain: 'http://saas.cn/',
// 腾讯地图key
mpKey: 'TUHBZ-CNWKU-UHAVP-GZQ26-HNZFO-3YBF4',
//客服地址
webSocket: '{{$webSocket}}',
//本地端主动给服务器ping的时间, 0 则不开启 , 单位秒
pingInterval: 1500,
uniacid:305,//825
// uniacid:site.uniacid,//825
// 版本号
version: '1.0'
};
export default config;

611
common/js/diy.js Normal file
View File

@@ -0,0 +1,611 @@
import WxMap from 'common/js/map-wx-jssdk.js';
import Config from '@/common/js/config.js';
let systemInfo = uni.getSystemInfoSync();
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,
//启动广告
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(){
console.log(123)
},
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'));
}
}
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
});
this.adv = res.value
// 弹框形式,首次弹出 1每次弹出 0
if(this.adv.advshow == 1){
setTimeout(() => {
if (res.value.advtype == 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 (res.value.advtype == 0) {
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
}
}, 500);
}
},
async getDiyInfo() {
let res = await this.$api.sendRequest({
url: '/api/diyview/info',
data: {
id: this.id,
name: this.name,
en_type:uni.getStorageSync("lang"),//获取语言底部
},
async: false
});
if (res.code != 0 || !res.data) {
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
if (res.code == -3) {
this.$util.showToast({
title: res.message
});
this.diyData = {};
return;
}
this.$util.showToast({
title: '未配置自定义页面数据'
});
this.diyData = {};
return;
}
let diyDataValue = res.data;
if (diyDataValue.value) {
this.diyData = JSON.parse(diyDataValue.value);
this.$langConfig.title(this.diyData.global.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;
}
},
closePopupWindow() {
this.$refs.uniPopupWindow.close();
uni.setStorageSync(this.id + this.name + '_popwindow_count', -1);
},
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 = '未获取到定位';
}
}
});
},
// 定位失败,进入默认门店
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.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.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;
}
}

55
common/js/emjoy.js Normal file
View File

@@ -0,0 +1,55 @@
export default {
emjoyList: {
"[emjoy_01]": 'public/static/img/emjoy/emjoy_01.gif',
"[emjoy_02]": 'public/static/img/emjoy/emjoy_02.gif',
"[emjoy_03]": 'public/static/img/emjoy/emjoy_03.gif',
"[emjoy_04]": 'public/static/img/emjoy/emjoy_04.gif',
"[emjoy_05]": 'public/static/img/emjoy/emjoy_05.gif',
"[emjoy_06]": 'public/static/img/emjoy/emjoy_06.gif',
"[emjoy_07]": 'public/static/img/emjoy/emjoy_07.gif',
"[emjoy_08]": 'public/static/img/emjoy/emjoy_08.gif',
"[emjoy_09]": 'public/static/img/emjoy/emjoy_09.gif',
"[emjoy_10]": 'public/static/img/emjoy/emjoy_10.gif',
"[emjoy_11]": 'public/static/img/emjoy/emjoy_11.gif',
"[emjoy_12]": 'public/static/img/emjoy/emjoy_12.gif',
"[emjoy_13]": 'public/static/img/emjoy/emjoy_13.gif',
"[emjoy_14]": 'public/static/img/emjoy/emjoy_14.gif',
"[emjoy_15]": 'public/static/img/emjoy/emjoy_15.gif',
"[emjoy_16]": 'public/static/img/emjoy/emjoy_16.gif',
"[emjoy_17]": 'public/static/img/emjoy/emjoy_17.gif',
"[emjoy_18]": 'public/static/img/emjoy/emjoy_18.gif',
"[emjoy_19]": 'public/static/img/emjoy/emjoy_19.gif',
"[emjoy_20]": 'public/static/img/emjoy/emjoy_20.gif',
"[emjoy_21]": 'public/static/img/emjoy/emjoy_21.gif',
"[emjoy_22]": 'public/static/img/emjoy/emjoy_22.gif',
"[emjoy_23]": 'public/static/img/emjoy/emjoy_23.gif',
"[emjoy_24]": 'public/static/img/emjoy/emjoy_24.gif',
"[emjoy_25]": 'public/static/img/emjoy/emjoy_25.gif',
"[emjoy_26]": 'public/static/img/emjoy/emjoy_26.gif',
"[emjoy_27]": 'public/static/img/emjoy/emjoy_27.gif',
"[emjoy_28]": 'public/static/img/emjoy/emjoy_28.gif',
"[emjoy_29]": 'public/static/img/emjoy/emjoy_29.gif',
"[emjoy_30]": 'public/static/img/emjoy/emjoy_30.gif',
"[emjoy_31]": 'public/static/img/emjoy/emjoy_31.gif',
"[emjoy_32]": 'public/static/img/emjoy/emjoy_32.gif',
"[emjoy_33]": 'public/static/img/emjoy/emjoy_33.gif',
"[emjoy_34]": 'public/static/img/emjoy/emjoy_34.gif',
"[emjoy_35]": 'public/static/img/emjoy/emjoy_35.gif',
"[emjoy_36]": 'public/static/img/emjoy/emjoy_36.gif',
"[emjoy_37]": 'public/static/img/emjoy/emjoy_37.gif',
"[emjoy_38]": 'public/static/img/emjoy/emjoy_38.gif',
"[emjoy_39]": 'public/static/img/emjoy/emjoy_39.gif',
"[emjoy_40]": 'public/static/img/emjoy/emjoy_40.gif',
"[emjoy_41]": 'public/static/img/emjoy/emjoy_41.gif',
"[emjoy_42]": 'public/static/img/emjoy/emjoy_42.gif',
"[emjoy_43]": 'public/static/img/emjoy/emjoy_43.gif',
"[emjoy_44]": 'public/static/img/emjoy/emjoy_44.gif',
"[emjoy_45]": 'public/static/img/emjoy/emjoy_45.gif',
"[emjoy_46]": 'public/static/img/emjoy/emjoy_46.gif',
"[emjoy_47]": 'public/static/img/emjoy/emjoy_47.gif',
}
}

View File

@@ -0,0 +1,24 @@
export default {
data() {
return {
fenxiaoWords: {}
}
},
methods: {
getFenxiaoWrods() {
this.$api.sendRequest({
url: '/fenxiao/api/config/words',
success: res => {
if (res.code >= 0 && res.data) {
this.fenxiaoWords = res.data;
uni.setStorageSync('fenxiaoWords', res.data);
}
}
})
}
},
onShow() {
if (uni.getStorageSync('fenxiaoWords')) this.fenxiaoWords = uni.getStorageSync('fenxiaoWords');
this.getFenxiaoWrods();
}
}

186
common/js/golbalConfig.js Normal file
View File

@@ -0,0 +1,186 @@
export default {
data() {
return {
// 页面样式,动态设置主色调
themeColor: '' //''--base-color:#fa5d14;--base-help-color:#ff7e00;'
}
},
onLoad() {},
onShow() {
// 刷新多语言
this.$langConfig.refresh();
let time = setInterval(() => {
let theme = this.themeStyle;
if (theme && theme.main_color) {
this.themeColorSet();
clearInterval(time);
}
}, 50);
},
computed: {
themeStyle() {
return this.$store.state.themeStyle;
},
// 插件是否存在
addonIsExist() {
return this.$store.state.addonIsExist;
},
tabBarList() {
return this.$store.state.tabBarList;
},
siteInfo() {
return this.$store.state.siteInfo;
},
memberInfo() {
return this.$store.state.memberInfo;
},
storeToken() {
return this.$store.state.token;
},
bottomNavHidden() {
return this.$store.state.bottomNavHidden;
},
globalStoreConfig() {
return this.$store.state.globalStoreConfig;
},
globalStoreInfo() {
return this.$store.state.globalStoreInfo;
},
// 定位信息
location() {
return this.$store.state.location;
},
// 定位信息(缓存)
locationStorage() {
let data = uni.getStorageSync('location');
if (data) {
var date = new Date();
if (this.mapConfig.wap_valid_time > 0) {
data.is_expired = (date.getTime() / 1000) > data.valid_time; // 是否过期
} else {
data.is_expired = false;
}
}
return data;
},
// 默认总店(定位失败后使用)
defaultStoreInfo() {
return this.$store.state.defaultStoreInfo;
},
// 组件刷新计数
componentRefresh() {
return this.$store.state.componentRefresh;
},
// 客服配置
servicerConfig() {
return this.$store.state.servicerConfig;
},
diySeckillInterval() {
return this.$store.state.diySeckillInterval;
},
tabBarHeight() {
return this.$store.state.tabBarHeight;
},
mapConfig() {
return this.$store.state.mapConfig;
},
copyright() {
let copyright = this.$store.state.copyright;
// 判断是否授权
if (copyright && !copyright.auth) {
copyright.logo = '';
copyright.copyright_link = '';
}
return copyright;
},
cartList() {
return this.$store.state.cartList;
},
cartIds() {
return this.$store.state.cartIds;
},
cartNumber() {
return this.$store.state.cartNumber;
},
cartMoney() {
return this.$store.state.cartMoney;
}
},
methods: {
themeColorSet() {
let theme = this.themeStyle;
this.themeColor = `--base-color:${theme.main_color};--base-help-color:${theme.aux_color};`;
if (this.tabBarHeight != '56px') this.themeColor += `--tab-bar-height:${this.tabBarHeight};`
Object.keys(theme).forEach(key => {
let data = theme[key];
if (typeof(data) == "object") {
Object.keys(data).forEach(k => {
this.themeColor += '--' + k.replace(/_/g, "-") + ':' + data[k] + ';';
});
} else if (typeof(key) == "string" && key) {
this.themeColor += '--' + key.replace(/_/g, "-") + ':' + data + ';';
}
});
for (let i = 9; i >= 5; i--) {
let color = this.$util.colourBlend(theme.main_color, '#ffffff', (i / 10));
this.themeColor += `--base-color-light-${i}:${color};`;
}
},
// 颜色变浅(>0、变深函数<0
lightenDarkenColor(color, amount) {
var usePound = false;
if (color[0] == "#") {
color = color.slice(1);
usePound = true;
}
var num = parseInt(color, 16);
var r = (num >> 16) + amount;
if (r > 255) r = 255;
else if (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amount;
if (b > 255) b = 255;
else if (b < 0) b = 0;
var g = (num & 0x0000FF) + amount;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
},
/**
* 切换门店
* @param {Object} info 门店信息
* @param {Object} isJump 是否跳转到首页
*/
changeStore(info, isJump) {
if (info) {
this.$store.commit('setGlobalStoreInfo', info);
}
let route = this.$util.getCurrRoute();
if (isJump && route != 'pages/index/index') {
uni.setStorageSync('manual_change_store', true); // 手动切换门店
this.$store.dispatch('getCartNumber'); //重新获取购物车数据
this.$util.redirectTo('/pages/index/index');
}
}
},
filters: {
/**
* 金额格式化输出
* @param {Object} money
*/
moneyFormat(money) {
if (isNaN(parseFloat(money))) return money;
return parseFloat(money).toFixed(2);
}
}
}

View File

@@ -0,0 +1,371 @@
// 商品详情业务
import htmlParser from '@/common/js/html-parser';
export default {
data() {
return {
skuId: 0,
goodsId: 0,
// 商品详情
goodsSkuDetail: {
goods_id: 0,
goods_service: []
},
preview: 0, //是否开启预览0不开启1开启
//评价
contactData: {
title: '',
path: '',
img: ''
},
shareQuery: '', // 分享参数
shareUrl: '', // 分享链接
source_member: 0, //分享人的id
chatRoomParams: {}, // 联系客服参数
isIphoneX: false, //判断手机是否是iphoneX以上
whetherCollection: 0,
posterParams: {}, //海报所需参数
shareImg: '',
navbarData: {
title: '',
topNavColor: "#ffffff",
topNavBg: false,
navBarSwitch: true, // 导航栏是否显示
textNavColor: "#333333",
moreLink: {
name: ""
},
navStyle: 1,
bgUrl: '',
textImgPosLink: 'left'
},
}
},
onLoad(data) {
//刷新多语言
this.$langConfig.refresh();
// #ifdef MP-ALIPAY
let options = my.getLaunchOptionsSync();
options.query && Object.assign(data, options.query);
// #endif
this.preview = data.preview || 0;
this.isIphoneX = this.$util.uniappIsIPhoneX();
if (data.source_member) {
uni.setStorageSync('source_member', data.source_member);
this.source_member = data.source_member;
}
//记录分享关系
if (this.storeToken && uni.getStorageSync('source_member')) {
this.$util.onSourceMember(uni.getStorageSync('source_member'));
}
// 小程序扫码进入
if (data.scene) {
var sceneParams = decodeURIComponent(data.scene);
sceneParams = sceneParams.split('&');
if (sceneParams.length) {
sceneParams.forEach(item => {
if (item.indexOf('m') != -1) uni.setStorageSync('source_member', item.split('-')[1]);
if (item.indexOf('is_test') != -1) uni.setStorageSync('is_test', 1);
});
}
}
},
onShow() {
},
methods: {
// 处理商品详情数据
handleGoodsSkuData() {
// this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
//设置标题
// this.$langConfig.title(this.navbarData.title);
if (this.goodsSkuDetail.config) {
this.navbarData.navBarSwitch = this.goodsSkuDetail.config.nav_bar_switch;
}
this.whetherCollection = this.goodsSkuDetail.is_collect; // 用户关注商品状态
this.modifyGoodsInfo();
// 初始化商品详情视图数据
if (this.$refs.goodsDetailView) this.$refs.goodsDetailView.init({
sku_id: this.skuId,
goods_id: this.goodsSkuDetail.goods_id,
preview: this.preview,
source_member: this.source_member,
posterParams: this.posterParams,
posterApi: this.posterApi,
shareUrl: this.shareUrl,
goodsRoute: this.goodsRoute,
isVirtual: this.goodsSkuDetail.is_virtual,
deliveryType: this.goodsSkuDetail.express_type,
whetherCollection: this.goodsSkuDetail.is_collect,
evaluateConfig: this.goodsSkuDetail.evaluate_config,
evaluateList: this.goodsSkuDetail.evaluate_list,
evaluateCount: this.goodsSkuDetail.evaluate_count
});
//媒体
if (this.goodsSkuDetail.video_url) this.switchMedia = "video";
if (!Array.isArray(this.goodsSkuDetail.sku_images)) {
if (this.goodsSkuDetail.sku_images) this.goodsSkuDetail.sku_images = this.goodsSkuDetail.sku_images.split(",");
else this.goodsSkuDetail.sku_images = [];
}
// 多规格时合并主图
if (this.goodsSkuDetail.goods_spec_format && this.goodsSkuDetail.goods_image) {
if (!Array.isArray(this.goodsSkuDetail.goods_image)) this.goodsSkuDetail.goods_image = this.goodsSkuDetail.goods_image.split(",");
this.goodsSkuDetail.sku_images = this.goodsSkuDetail.goods_image.concat(this.goodsSkuDetail.sku_images);
}
let maxHeight = '';
let systemInfo = uni.getSystemInfoSync();
this.goodsSkuDetail.goods_image_list.forEach((item, index) => {
if (typeof item.pic_spec == "string")
item.pic_spec = item.pic_spec.split('*');
let ratio = item.pic_spec[0] / systemInfo.windowWidth;
item.pic_spec[0] = item.pic_spec[0] / ratio;
item.pic_spec[1] = item.pic_spec[1] / ratio;
if (!maxHeight || maxHeight > item.pic_spec[1]) {
maxHeight = item.pic_spec[1];
}
});
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
// 当前商品SKU规格
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
// 商品属性
if (this.goodsSkuDetail.goods_attr_format) {
let goods_attr_format = JSON.parse(this.goodsSkuDetail.goods_attr_format);
this.goodsSkuDetail.goods_attr_format = this.$util.unique(goods_attr_format, "attr_id");
for (var i = 0; i < this.goodsSkuDetail.goods_attr_format.length; i++) {
for (var j = 0; j < goods_attr_format.length; j++) {
if (this.goodsSkuDetail.goods_attr_format[i].attr_id == goods_attr_format[j].attr_id && this.goodsSkuDetail.goods_attr_format[i].attr_value_id != goods_attr_format[j].attr_value_id) {
this.goodsSkuDetail.goods_attr_format[i].attr_value_name += "、" + goods_attr_format[j].attr_value_name;
}
}
}
}
// 商品SKU格式
if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
// 商品详情
if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content);
console.log(this.goodsSkuDetail.goods_content)
// if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content);
//商品服务
if (this.goodsSkuDetail.goods_service) {
for (let i in this.goodsSkuDetail.goods_service) {
this.goodsSkuDetail.goods_service[i]['icon'] = this.goodsSkuDetail.goods_service[i]['icon'] ? JSON.parse(this.goodsSkuDetail.goods_service[i]['icon']) : '';
}
}
this.contactData = {
title: this.goodsSkuDetail.sku_name,
path: this.shareUrl,
img: this.$util.img(this.goodsSkuDetail.sku_image, {
size: 'big'
})
};
if (this.$refs.goodsPromotion) this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
if (this.goodsRoute != '/pages/goods/detail') this.setPublicShare();
// this.getBarrageData();
if (this.addonIsExist.form) {
this.getGoodsForm();
}
},
/**
* 刷新商品详情数据
* @param {Object} data
*/
refreshGoodsSkuDetail(data) {
this.goodsSkuDetail = Object.assign({}, this.goodsSkuDetail, data);
if (this.$refs.goodsPromotion) this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
if (this.$refs.goodsDetailView) {
// 初始化商品详情视图数据
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
// 解决轮播图数量不一致时,切换到第一个
if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {
this.swiperAutoplay = true;
this.swiperCurrent = 1;
setTimeout(() => {
this.swiperAutoplay = false;
}, 40);
}
}
this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
this.$langConfig.title(this.navbarData.title);
if (this.goodsSkuDetail.membercard) {
this.membercard = this.goodsSkuDetail.membercard;
}
},
goodsDetailViewInit() {
// 初始化商品详情视图数据
if (this.$refs.goodsDetailView) this.$refs.goodsDetailView.init({
sku_id: this.skuId,
goods_id: this.goodsSkuDetail.goods_id,
preview: this.preview,
source_member: this.source_member,
posterParams: this.posterParams,
posterApi: this.posterApi,
shareUrl: this.shareUrl,
goodsRoute: this.goodsRoute,
isVirtual: this.goodsSkuDetail.is_virtual,
deliveryType: this.goodsSkuDetail.express_type,
whetherCollection: this.goodsSkuDetail.is_collect,
evaluateConfig: this.goodsSkuDetail.evaluate_config,
evaluateList: this.goodsSkuDetail.evaluate_list,
evaluateCount: this.goodsSkuDetail.evaluate_count
});
},
goHome() {
if (this.preview) return; // 开启预览,禁止任何操作和跳转
this.$util.redirectTo('/pages/index/index');
},
goCart() {
if (this.preview) return; // 开启预览,禁止任何操作和跳转
this.$util.redirectTo('/pages/goods/cart');
},
//-------------------------------------关注-------------------------------------
//更新商品信息
modifyGoodsInfo() {
if (this.preview) return; // 开启预览,禁止任何操作和跳转
//更新商品点击量
this.$api.sendRequest({
url: "/api/goods/modifyclicks",
data: {
sku_id: this.skuId
},
success: res => {
}
});
//添加足迹
this.$api.sendRequest({
url: "/api/goodsbrowse/add",
data: {
goods_id: this.goodsSkuDetail.goods_id,
sku_id: this.skuId
},
success: res => {
}
});
},
//-------------------------------------关注-------------------------------------
async editCollection() {
if (this.$refs.goodsDetailView) {
this.whetherCollection = await this.$refs.goodsDetailView.collection();
}
},
openSharePopup() {
if (this.$refs.goodsDetailView) {
this.$refs.goodsDetailView.openSharePopup();
}
},
//弹幕
getBarrageData() {
this.$api.sendRequest({
url: '/api/goods/goodsbarrage',
data: {
goods_id: this.goodsSkuDetail.goods_id
},
success: res => {
if (res.code == 0 && res.data) {
let barrageData = [];
for (let i in res.data.list) {
if (res.data.list[i]['title']) {
let title = res.data.list[i]['title'].substr(0, 1) + '*' + res.data.list[i]['title'].substr(res.data.list[i]['title'].length - 1, 1)
barrageData.push({
img: res.data.list[i]['img'] ? res.data.list[i]['img'] : this.$util.getDefaultImage().head,
title: title + '已下单'
});
}
}
this.goodsSkuDetail.barrageData = barrageData;
}
}
});
},
/**
* 设置公众号分享
*/
setPublicShare() {
let shareUrl = this.$config.h5Domain + this.shareUrl;
if (this.memberInfo && this.memberInfo.member_id) shareUrl += '&source_member=' + this.memberInfo.member_id;
this.$util.setPublicShare({
title: this.goodsSkuDetail.goods_name,
desc: '',
link: shareUrl,
imgUrl: typeof this.goodsSkuDetail.goods_image == 'object' ? this.goodsSkuDetail.goods_image[0] : this.goodsSkuDetail.goods_image.split(',')[0]
})
},
/**
* 获取商品表单
*/
getGoodsForm() {
this.$api.sendRequest({
url: "/form/api/form/goodsform",
data: {
goods_id: this.goodsSkuDetail.goods_id
},
success: res => {
if (res.code == 0 && res.data) this.$set(this.goodsSkuDetail, 'goods_form', res.data);
}
});
}
},
/**
* 自定义分享内容
* @param {Object} res
*/
onShareAppMessage(res) {
var path = this.shareUrl;
if (this.memberInfo && this.memberInfo.member_id) path += '&source_member=' + this.memberInfo.member_id;
return {
title: this.goodsSkuDetail.sku_name,
imageUrl: this.shareImg ? this.$util.img(this.shareImg) : this.$util.img(this.goodsSkuDetail.sku_image, {
size: 'big'
}),
path: path,
success: res => {
},
fail: res => {
}
};
},
// 分享到微信朋友圈
// #ifdef MP-WEIXIN
onShareTimeline() {
let query = this.shareQuery;
if (this.memberInfo && this.memberInfo.member_id) query += '&source_member=' + this.memberInfo.member_id;
return {
title: this.goodsSkuDetail.sku_name,
query: query,
imageUrl: this.$util.img(this.goodsSkuDetail.sku_image, {
size: 'big'
})
};
}
// #endif
}

440
common/js/html-parser.js Normal file
View File

@@ -0,0 +1,440 @@
import util from './util.js'
/*
* HTML5 Parser By Sam Blowes
*
* Designed for HTML5 documents
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* ----------------------------------------------------------------------------
* License
* ----------------------------------------------------------------------------
*
* This code is triple licensed using Apache Software License 2.0,
* Mozilla Public License or GNU Public License
*
* ////////////////////////////////////////////////////////////////////////////
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* ////////////////////////////////////////////////////////////////////////////
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Simple HTML Parser.
*
* The Initial Developer of the Original Code is Erik Arvidsson.
* Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
* Reserved.
*
* ////////////////////////////////////////////////////////////////////////////
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ----------------------------------------------------------------------------
* Usage
* ----------------------------------------------------------------------------
*
* // Use like so:
* HTMLParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* // or to get an XML string:
* HTMLtoXML(htmlString);
*
* // or to get an XML DOM Document
* HTMLtoDOM(htmlString);
*
* // or to inject into an existing document/DOM node
* HTMLtoDOM(htmlString, document);
* HTMLtoDOM(htmlString, document.body);
*
*/
// Regular Expressions for parsing tags and attributes
var startTag =
/^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr =
/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
var empty = makeMap(
'area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'
); // Block Elements - HTML 5
// fixed by xxx 将 ins 标签从块级名单中移除
var block = makeMap(
'a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'
); // Inline Elements - HTML 5
var inline = makeMap(
'abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'
); // Elements that you can, intentionally, leave open
// (and which close themselves)
var closeSelf = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
var fillAttrs = makeMap(
'checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'
); // Special Elements (can contain anything)
var special = makeMap('script,style');
function HTMLParser(html, handler) {
var index;
var chars;
var match;
var stack = [];
var last = html;
stack.last = function() {
return this[this.length - 1];
};
while (html) {
chars = true; // Make sure we're not in a script or style element
if (!stack.last() || !special[stack.last()]) {
// Comment
if (html.indexOf('<!--') == 0) {
index = html.indexOf('-->');
if (index >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index));
}
html = html.substring(index + 3);
chars = false;
} // end tag
} else if (html.indexOf('</') == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
} // start tag
} else if (html.indexOf('<') == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf('<');
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? '' : html.substring(index);
if (handler.chars) {
handler.chars(text);
}
}
} else {
html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function(all, text) {
text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
if (handler.chars) {
handler.chars(text);
}
return '';
});
parseEndTag('', stack.last());
}
if (html == last) {
throw 'Parse Error: ' + html;
}
last = html;
} // Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = tagName.toLowerCase();
if (block[tagName]) {
while (stack.last() && inline[stack.last()]) {
parseEndTag('', stack.last());
}
}
if (closeSelf[tagName] && stack.last() == tagName) {
parseEndTag('', tagName);
}
unary = empty[tagName] || !!unary;
if (!unary) {
stack.push(tagName);
}
if (handler.start) {
var attrs = [];
rest.replace(attr, function(match, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ?
arguments[4] : fillAttrs[
name] ? name : '';
attrs.push({
name: name,
value: value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
});
});
if (handler.start) {
handler.start(tagName, attrs, unary);
}
}
}
function parseEndTag(tag, tagName) {
// If no tag name is provided, clean shop
if (!tagName) {
var pos = 0;
} // Find the closest opened tag of the same type
else {
for (var pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] == tagName) {
break;
}
}
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (handler.end) {
handler.end(stack[i]);
}
} // Remove the open elements from the stack
stack.length = pos;
}
}
}
function makeMap(str) {
var obj = {};
var items = str.split(',');
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function removeDOCTYPE(html) {
return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
}
/**
* 忽略注释
* @param {Object} html
*/
function replaceAnnotation(html) {
var html = html.replace(/<!--[\s\S]*-->/gi, '');
return html;
}
/**
* 替换图片
* @param {Object} html
*/
function replaceImage(html) {
// #ifdef MP
let info = uni.getSystemInfoSync();
var screenWidth = info.windowWidth;
screenWidth -= 20;
screenWidth += 'px';
// #endif
// #ifdef H5
var screenWidth = '100%';
// #endif
let rep = `<img style="width:100% !important;display:block;max-width: ${screenWidth} !important;"`;
var html = html.replace(/\\/g, '').replace(/<img/g, rep);
html = html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
return rep + ' src="' + util.img(capture) + '"/>';
});
return html;
}
function replaceVideo(html){
// #ifdef MP
let info = uni.getSystemInfoSync();
var screenWidth = info.windowWidth;
screenWidth -= 20;
screenWidth += 'px';
// #endif
// #ifdef H5
var screenWidth = '100%';
// #endif
let rep = `<video style="width:100% !important;display:block;max-width: ${screenWidth} !important;"`;
var html = html.replace(/\\/g, '').replace(/<video/g, rep);
console.log(html)
html = html.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
return rep + ' src="' + util.img(capture) + '"/>';
});
// console.log(html)
return html;
}
/**
* 将style属性中的双引号改为单引号
* @param {Object} html
*/
function replaceStyleQuotes(html) {
var html = html.replace(/style\s*=\s*["][^>]*;[^"]?/gi, (match, capture) => {
match = match.replace(/[:](\s?)[\s\S]*/gi, (a, b) => {
return a.replace(/"/g, "'");
});
return match;
});
return html;
}
function parseAttrs(attrs) {
return attrs.reduce(function(pre, attr) {
var value = attr.value;
var name = attr.name;
if (pre[name]) {
pre[name] = pre[name] + " " + value;
} else {
pre[name] = value;
}
return pre;
}, {});
}
function parseHtml(html) {
html = removeDOCTYPE(html);
html = replaceAnnotation(html); //忽略注释
html = replaceImage(html); //替换图片
html = replaceStyleQuotes(html); //将style属性中的双引号改为单引号
html = replaceVideo(html); //替换视频链接
var stacks = [];
var results = {
node: 'root',
children: []
};
HTMLParser(html, {
start: function start(tag, attrs, unary) {
var node = {
name: tag
};
if (attrs.length !== 0) {
node.attrs = parseAttrs(attrs);
}
if (unary) {
var parent = stacks[0] || results;
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
stacks.unshift(node);
}
},
end: function end(tag) {
var node = stacks.shift();
if (node.name !== tag) console.error('invalid state: mismatch end tag');
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
chars: function chars(text) {
var node = {
type: 'text',
text: text
};
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
comment: function comment(text) {
var node = {
node: 'comment',
text: text
};
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
});
return results.children;
}
export default parseHtml;

255
common/js/http.js Normal file
View File

@@ -0,0 +1,255 @@
import Config from './config.js'
import Util from './util.js'
import store from '@/store/index.js'
// #ifdef H5
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
// #endif
// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif
// #ifdef MP-ALIPAY
const app_type = 'aliapp';
const app_type_name = '支付宝小程序';
// #endif
// #ifdef MP-BAIDU
const app_type = 'baiduapp';
const app_type_name = '百度小程序';
// #endif
// #ifdef MP-TOUTIAO
const app_type = 'MP-TOUTIAO';
const app_type_name = '头条小程序';
// #endif
// #ifdef MP-QQ
const app_type = 'MP-QQ';
const app_type_name = 'QQ小程序';
// #endif
// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif
export default {
sendRequest(params) {
if (!Config.baseUrl) {
uni.showToast({
title: '未配置请求域名',
'icon': 'none',
duration: 10000
});
return;
}
var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
url = Config.baseUrl + params.url, // 请求路径
data = {
app_type,
app_type_name
};
// token
data.token = store.state.token || '';
data.uniacid = Config.uniacid
// 门店id
var default_store_info = store.state.defaultStoreInfo;
if (default_store_info) {
data.store_id = default_store_info.store_id;
}
var store_info = store.state.globalStoreInfo;
if (store_info) data.store_id = store_info.store_id;
// 参数
if (params.data != undefined) Object.assign(data, params.data);
if (params.async === false) {
//同步
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: data,
header: params.header || {
// 'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded;application/json'
},
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
resolve(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
reject(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
reject(res.data);
}
});
});
} else {
//异步
uni.request({
url: url,
method: method,
data: data,
header: params.header || {
// 'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded;application/json'
},
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
typeof params.success == 'function' && params.success(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.fail == 'function' && params.fail(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.complete == 'function' && params.complete(res.data);
}
});
}
},
uploadBase64(params) {
uni.request({
url: Config.baseUrl + '/api/upload/headimgBase64',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded;application/json'
},
data: {
app_type,
app_type_name,
images: params.base64
},
dataType: 'json',
responseType: 'text',
success: res => {
typeof params.success == 'function' && params.success(res.data);
},
fail: () => {
typeof params.fail == 'function' && params.fail(res);
}
});
},
pullImage(params) {
uni.request({
url: Config.baseUrl + '/api/upload/headimgPull',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded;application/json'
},
data: {
app_type,
app_type_name,
path: params.path
},
dataType: 'json',
responseType: 'text',
success: res => {
typeof params.success == 'function' && params.success(res.data);
},
fail: () => {
typeof params.fail == 'function' && params.fail(res);
}
});
},
upload(params) {
uni.uploadFile({
url: Config.baseUrl + params.url,
filePath: params.filePath,
name: params.name || 'file',
fileType: params.fileType || 'image',
formData: {
app_type,
app_type_name,
},
header: {
'content-type': 'application/x-www-form-urlencoded;application/json'
},
success: (res) => {
typeof params.success == 'function' && params.success(JSON.parse(res.data));
},
fail: (res) => {
typeof params.fail == 'function' && params.fail(res);
}
});
}
}

129
common/js/lang.js Normal file
View File

@@ -0,0 +1,129 @@
const langList = ['zh-cn', 'en-us'];
var locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言
export default {
langList: ['zh-cn', 'en-us'],
/**
* * 解析多语言
* @param {Object} field
*/
lang(field) {
let _this = getCurrentPages()[getCurrentPages().length - 1];
if (!_this) return;
var value = '';
let newRoute;
try {
//公共语言包
var lang = require('../../lang/' + locale + '/common.js').lang;
//当前页面语言包
let route = _this.route.split("/");
newRoute = route.slice(1, route.length);
let currentPageLang = require('../../lang/' + locale + '/' + newRoute.join("/") + '.js').lang;
for (let f in currentPageLang) {
lang[f] = currentPageLang[f];
}
var arr = field.split(".");
if (arr.length > 1) {
for (let i in arr) {
var next = parseInt(i) + 1;
if (next < arr.length) {
value = lang[arr[i]][arr[next]];
}
}
} else {
value = lang[field];
}
} catch (e) {
if (field.indexOf("common.") != -1 || field.indexOf("tabBar.") != -1) {
value = lang[field];
} else {
value = field;
}
}
if (arguments.length > 1) {
//有参数,需要替换
for (var i = 1; i < arguments.length; i++) {
value = value.replace("{" + (i - 1) + "}", arguments[i]);
}
}
if (value == undefined || (value == 'title' && field == 'title')) value = ''; // field
return value;
},
//切换语言
change(value) {
let _this = getCurrentPages()[getCurrentPages().length - 1];
if (!_this) return;
uni.setStorageSync("lang", value);
locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言
this.refresh();
uni.reLaunch({
url: '/pages/member/index'
});
},
//刷新标题、tabbar
refresh() {
let _this = getCurrentPages()[getCurrentPages().length - 1];
if (!_this) return;
locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言
this.title(this.lang("title"));
//设置tabbar的文字语言
// uni.setTabBarItem({
// index: 0,
// text: this.lang("tabBar.home")
// });
// uni.setTabBarItem({
// index: 1,
// text: this.lang("tabBar.category")
// });
// uni.setTabBarItem({
// index: 2,
// text: this.lang("tabBar.cart")
// });
// uni.setTabBarItem({
// index: 3,
// text: this.lang("tabBar.member")
// });
},
title(str) {
if (str) {
uni.setNavigationBarTitle({
title: str,
success: function (res) {
},
fail: function (err) {
}
});
}
},
// 获取语言包列表
list() {
var list = [];
try {
//公共语言包
for (var i = 0; i < langList.length; i++) {
let item = require('../../lang/' + langList[i] + '/common.js').lang;
list.push({
name: item.common.name,
value: langList[i]
});
}
} catch (e) {
// "没有找到语言包:", '../../lang/' + locale + '/common.js'
}
return list;
}
}

1125
common/js/map-wx-jssdk.js Normal file

File diff suppressed because it is too large Load Diff

107
common/js/map/openMap.js Normal file
View File

@@ -0,0 +1,107 @@
import TransformCoordinate from './transformCoordinate.js'
function openMapByDefault(latitude, longitude, name) {
uni.openLocation({
latitude: latitude,
longitude: longitude,
name: name,
fail: (e) => {
uni.showModal({
content: '打开地图失败,请稍后重试'
})
},
})
}
function openMapByAndroid(latitude, longitude, name) {
let url = ''; // 回调地址
let identity = ''; // 程序名称
if (plus.runtime.isApplicationExist({
pname: 'com.baidu.BaiduMap'
})) {
url =
`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`
identity = 'com.baidu.BaiduMap'
openURL(url, identity)
} else if (plus.runtime.isApplicationExist({
pname: 'com.autonavi.minimap'
})) { // 高德
url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
identity = 'com.autonavi.minimap'
openURL(url, identity)
} else {
openMapByDefault(latitude, longitude, name)
}
}
function openMapByIos(latitude, longitude, name) {
let url = ''; // 回调地址
let errorCB = ''; // url失败的回调地址
let identity = ''; // 程序名称
if (plus.runtime.isApplicationExist({
action: 'baidumap://'
})) {
url =
`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
openURL(url, identity)
} else if (plus.runtime.isApplicationExist({
action: 'iosamap://'
})) { // 高德
url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
openURL(url, identity)
} else {
openMapByDefault(latitude, longitude, name)
}
}
function openURL(url, identity) {
let newurl = encodeURI(url);
plus.runtime.openURL(newurl, function(res) {
uni.showModal({
content: res.message
})
}, identity);
}
function getCoordByType(longitude, latitude, coord_type) {
switch (coord_type) {
case 'gcj02':
return [longitude, latitude]
break;
case 'bd09':
return TransformCoordinate.bd09togcj02(longitude, latitude)
break;
case 'wgs84':
return TransformCoordinate.wgs84togcj02(longitude, latitude)
break;
default:
return [longitude, latitude]
break;
}
}
export default {
/* 打开地图 */
openMap(latitude, longitude, name, coord_type = 'gcj02') {
let arr = getCoordByType(longitude, latitude, coord_type)
// #ifdef APP-PLUS
switch (uni.getSystemInfoSync().platform) {
case 'android':
console.log('运行Android上')
openMapByAndroid(arr[1], arr[0], name)
break;
case 'ios':
console.log('运行iOS上')
openMapByIos(arr[1], arr[0], name)
break;
default:
openMapByDefault(arr[1], arr[0], name)
console.log('运行在开发者工具上')
break;
}
// #endif
// #ifndef APP-PLUS
openMapByDefault(arr[1], arr[0], name)
// #endif
}
}

View File

@@ -0,0 +1,124 @@
/**
* Created by Wandergis on 2015/7/8.
* 提供了百度坐标BD09、国测局坐标火星坐标GCJ02、和WGS84坐标系之间的转换
*/
//定义一些常量
var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;
/**
* 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
* 即 百度 转 谷歌、高德
* @param bd_lon
* @param bd_lat
* @returns {*[]}
*/
function bd09togcj02(bd_lon, bd_lat) {
var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
var x = bd_lon - 0.0065;
var y = bd_lat - 0.006;
var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
var gg_lng = z * Math.cos(theta);
var gg_lat = z * Math.sin(theta);
return [gg_lng, gg_lat]
}
/**
* 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
* 即谷歌、高德 转 百度
* @param lng
* @param lat
* @returns {*[]}
*/
function gcj02tobd09(lng, lat) {
var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
var bd_lng = z * Math.cos(theta) + 0.0065;
var bd_lat = z * Math.sin(theta) + 0.006;
return [bd_lng, bd_lat]
}
/**
* WGS84转GCj02
* @param lng
* @param lat
* @returns {*[]}
*/
function wgs84togcj02(lng, lat) {
if (out_of_china(lng, lat)) {
return [lng, lat]
} else {
var dlat = transformlat(lng - 105.0, lat - 35.0);
var dlng = transformlng(lng - 105.0, lat - 35.0);
var radlat = lat / 180.0 * PI;
var magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
var sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
var mglat = lat + dlat;
var mglng = lng + dlng;
return [mglng, mglat]
}
}
/**
* GCJ02 转换为 WGS84
* @param lng
* @param lat
* @returns {*[]}
*/
function gcj02towgs84(lng, lat) {
if (out_of_china(lng, lat)) {
return [lng, lat]
} else {
var dlat = transformlat(lng - 105.0, lat - 35.0);
var dlng = transformlng(lng - 105.0, lat - 35.0);
var radlat = lat / 180.0 * PI;
var magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
var sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
mglat = lat + dlat;
mglng = lng + dlng;
return [lng * 2 - mglng, lat * 2 - mglat]
}
}
function transformlat(lng, lat) {
var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
return ret
}
function transformlng(lng, lat) {
var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
return ret
}
/**
* 判断是否在国内,不在国内则不做偏移
* @param lng
* @param lat
* @returns {boolean}
*/
function out_of_china(lng, lat) {
return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}
export default {
bd09togcj02: bd09togcj02, // 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
gcj02tobd09: gcj02tobd09, // 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
wgs84togcj02: wgs84togcj02, //
gcj02towgs84: gcj02towgs84,
}

10
common/js/pc.js Normal file
View File

@@ -0,0 +1,10 @@
(function() {
var u = navigator.userAgent,
w = window.innerWidth;
if (w >= 960) {
window.innerWidth = 960;
window.onload = function() {
window.innerWidth = 960;
}
}
})();

28
common/js/scroll-view.js Normal file
View File

@@ -0,0 +1,28 @@
export default {
data() {
return {
showTop: false,
scrollTop: 0,
oldLocation: 0
}
},
methods: {
scrollToTopNative() {
uni.pageScrollTo({
duration: 200,
scrollTop: 0
});
}
},
onReachBottom() {
if(this.$refs.goodrecommend) this.$refs.goodrecommend.getLikeList(10)
},
onPageScroll(e) {
this.oldLocation = e.scrollTop;
if (e.scrollTop > 400) {
this.showTop = true;
} else {
this.showTop = false;
}
}
}

207
common/js/socketTest.js Normal file
View File

@@ -0,0 +1,207 @@
import config from './config.js'
export default {
data() {
return {
timeoutObj: null, //ping定时器
servicer_id: null, //绑定
pingInterval: config.pingInterval //本地端主动给服务器ping的时间, 0 则不开启
}
},
onLoad() {
let that = this;
// 因为图片上传所以不能onhide关闭长链接但是每次打开客服都会有重复请求所以优先关闭再去打开长链接
uni.closeSocket();
// .判断是否已连接
that.checkOpenSocket();
// uni.onSocketClose(function(res) {
// console.log('WebSocket 已关闭!');
// });
},
methods: {
// 判断是否已连接
checkOpenSocket() {
console.log('判断是否已连接');
// alert('判断是否已连接')
let self = this;
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
console.log('连接成功,检查');
// alert('连接成功,检查')
// self.getChatList();
},
fail: (err) => { // 未连接打开websocket连接
console.log('连接失败');
// alert('连接失败')
self.openConnection();
}
});
},
openConnection() { // 打开连接
console.log('打开连接');
// alert('打开连接')
// uni.closeSocket(); // 确保已经关闭后再重新打开
uni.connectSocket({
url: config.webSocket,
method: 'POST',
success(res) {
console.log('连接成功 connectSocket=', res);
// alert('连接成功 connectSocket=', res);
},
fail(err) {
console.log('连接失败 connectSocket=', err);
}
});
// uni.onSocketOpen((res) => {
// console.log('连接成功', res);
// });
this.onSocketMessage(); // 打开成功监听服务器返回的消息
},
// 打开成功监听服务器返回的消息
onSocketMessage() { // 消息
console.log("开始监听");
let that = this;
this.pingInterval = config.pingInterval;
this.timeoutObj = null;
uni.onSocketMessage((res) => { //type:init,connect,close,string,order,goods
let msg = JSON.parse(res.data);
console.log("监听该服务器消息", res);
if (msg.type == 'close') {
clearInterval(that.timeoutObj);
that.timeoutObj = null;
uni.closeSocket();
return;
}
this.reset();
this.getSocketMsg(res.data); // 监听到有新服务器消息
});
},
// 监听到有新服务器消息
getSocketMsg(reData) { // 监听到服务器消息
let that = this;
// console.log(reData)
let giveMsg = JSON.parse(reData);
let data = {
isItMe: false,
};
data.contentType = giveMsg.type;
// alert(data.contentType)
if (giveMsg.type == 'init') {
// alert(123)
that.$api.sendRequest({
url: '/servicer/api/chat/bind',
data: {
client_id: giveMsg.data.client_id,
site_id: that.siteId
},
success(res) {
if (res.code == 0) {
that.servicer_id = res.data.servicer_id;
} else {
that.servicer_id = 0;
}
that.getChatList();
}
})
} else if (giveMsg.type == 'connect') {
// that.servicer_id = giveMsg.data.servicer_id;
// let NewArr = that.messageList;
// let index = null;
// for (let i = 0; i < NewArr.length; i++) {
// if (NewArr[i].contentType == 'online' || NewArr[i].contentType == 'noline') {
// index = i;
// }
// }
// NewArr.splice(index, 1)
// that.messageList = NewArr;
// let obj = {}
// if (that.servicer_id > 0) {
// obj.contentType = 'online';
// } else if (that.servicer_id == 0) {
// obj.contentType = 'noline';
// }
// that.messageList.push(obj);
return false;
} else if (giveMsg.type == 'string') {
data.content = giveMsg.data.servicer_say;
} else if (giveMsg.type == 'image') {
data.image = giveMsg.data.servicer_say;
} else if (giveMsg.type == 'order') {
data.order_id = giveMsg.data.order_id;
} else if (giveMsg.type == 'goodssku') {
data.sku_id = giveMsg.data.goods_sku_id;
}
if (giveMsg.type == 'init') return;
that.messageList.push(data);
that.$nextTick(() => {
that.setPageScrollTo()
})
},
// 检测心跳reset
reset() {
console.log("检测心跳");
clearInterval(this.timeoutObj);
this.start(); // 启动心跳
},
// 启动心跳 start
start() {
console.log("启动心跳");
let self = this;
this.timeoutObj = setInterval(function () {
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
console.log('连接中....');
},
fail: (err) => {
console.log('连接失败重新连接....');
self.openConnection();
}
});
}, this.pingInterval);
}
},
// onHide() {
// // alert("关闭")
// // 改之前的
// // console.log("我出发了")
// // this.checkOpenSocket();
// clearInterval(this.timeoutObj);
// this.timeoutObj = null;
// this.$api.sendRequest({
// url: '/servicer/api/chat/bye',
// data: {
// servicer_id: this.servicer_id,
// site_id: this.siteId
// },
// success(res) {
// uni.closeSocket();
// },
// fail: (err) => {
// uni.closeSocket();
// }
// });
// },
onUnload() {
// alert("关闭")
clearInterval(this.timeoutObj);
this.timeoutObj = null;
this.$api.sendRequest({
url: '/servicer/api/chat/bye',
data: {
servicer_id: this.servicer_id,
site_id: this.siteId
},
success(res) {
// alert("关闭1")
uni.closeSocket();
},
fail: (err) => {
// alert("关闭2")
uni.closeSocket();
}
});
}
}

51
common/js/storage.js Normal file
View File

@@ -0,0 +1,51 @@
import Config from './config.js'
const prefix = Config.baseUrl.replace(/(http:\/\/)|(https:\/\/)/g, '');
var oldPrefix = uni.getStorageSync('prefix');
// 域名不一致,清空
if (oldPrefix != prefix) {
uni.clearStorageSync();
}
uni.setStorageSync('prefix', prefix);
const handleKey = (key) => {
const storageKey = (prefix ? `${prefix}_` : '') + key;
return storageKey;
};
export function uniStorage() {
const setStorageSync = uni.setStorageSync;
const setStorage = uni.setStorage;
const getStorage = uni.getStorage;
const getStorageSync = uni.getStorageSync;
const removeStorage = uni.removeStorage;
const removeStorageSync = uni.removeStorageSync;
uni.setStorage = (options) => {
options.key = handleKey(options.key);
setStorage(options)
};
uni.setStorageSync = (key, data) => {
setStorageSync(handleKey(key), data)
};
uni.getStorage = (options) => {
options.key = handleKey(options.key);
getStorage(options)
};
uni.getStorageSync = (key) => {
return getStorageSync(handleKey(key))
};
uni.removeStorage = (options) => {
options.key = handleKey(options.key);
removeStorage(options)
};
uni.removeStorageSync = (key) => {
return removeStorageSync(handleKey(key))
}
}

419
common/js/style_color.js Normal file
View File

@@ -0,0 +1,419 @@
export default {
'default': {
//红色
name: 'default',
main_color: '#F4391c',
aux_color: '#F7B500',
bg_color: '#FF4646',//主题背景
bg_color_shallow: '#FF4646',//主题背景渐变浅色
promotion_color: '#FF4646',//活动背景
promotion_aux_color: '#F7B500',//活动背景辅色
main_color_shallow: '#FFF4F4',//淡背景
price_color: 'rgb(252,82,39)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgb(252,82,39,1)',//价格
promotion_tag: '#FF4646',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#FF4646',//按钮颜色
goods_btn_color_shallow: '#F7B500',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'green': {
name: 'green',
main_color: '#19C650',
aux_color: '#FA6400',
bg_color: '#19C650',
bg_color_shallow: '#19C650',
promotion_color: '#19C650',
promotion_aux_color: '#FA6400',
main_color_shallow: '#F0FFF5',//淡背景
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#19C650',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#19C650',//按钮颜色
goods_btn_color_shallow: '#FA6400',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'blue': {
name: 'blue',
main_color: '#36ABFF',
aux_color: '#FA6400',
bg_color: '#36ABFF',
bg_color_shallow: '#36ABFF',
promotion_color: '#36ABFF ',
promotion_aux_color: '#FA6400',
main_color_shallow: '#E2F3FF',
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#36ABFF',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#36ABFF',//按钮颜色
goods_btn_color_shallow: '#FA6400',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'pink': {
name: 'pink',
main_color: '#FF407E',
aux_color: '#F7B500',
bg_color: '#FF407E',//主题背景
bg_color_shallow: '#FF407E',//主题背景渐变浅色
promotion_color: '#FF407E',//活动背景
promotion_aux_color: '#F7B500',//活动背景辅色
main_color_shallow: '#FFF5F8',//淡背景
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#FF407E',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#FF407E',//按钮颜色
goods_btn_color_shallow: '#F7B500',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'gold': {
name: 'gold',
main_color: '#CFAF70',
aux_color: '#444444',
bg_color: '#CFAF70',//主题背景
bg_color_shallow: '#CFAF70',//主题背景渐变浅色
promotion_color: '#CFAF70',//活动背景
promotion_aux_color: '#444444',//活动背景辅色
main_color_shallow: '#FFFAF1',//淡背景
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#CFAF70',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#CFAF70',//按钮颜色
goods_btn_color_shallow: '#444444',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'purple': {
name: 'purple',
main_color: '#A253FF',
aux_color: '#222222',
bg_color: '#A253FF',//主题背景
bg_color_shallow: '#A253FF',//主题背景渐变浅色
promotion_color: '#A253FF',//活动背景
promotion_aux_color: '#222222',//活动背景辅色
main_color_shallow: '#F8F3FF',//淡背景
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#A253FF',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#A253FF',//按钮颜色
goods_btn_color_shallow: '#222222',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'yellow': {
name: 'yellow',
main_color: '#FFD009',
aux_color: '#1D262E',
bg_color: '#FFD009',//主题背景
bg_color_shallow: '#FFD009',//主题背景渐变浅色
promotion_color: '#FFD009',//活动背景
promotion_aux_color: '#1D262E',//活动背景辅色
main_color_shallow: '#FFFBEF',//淡背景
price_color: 'rgba(252,82,39,1)',//价格颜色
btn_text_color: '#303133',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(252,82,39,1)',//价格
promotion_tag: '#FFD009',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',//购物车数量角标
goods_btn_color: '#FFD009',//按钮颜色
goods_btn_color_shallow: '#1D262E',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
},
'black': {
name: 'black',
main_color: '#222222',
aux_color: '#FFFFFF',
bg_color: '#222222',//主题背景
bg_color_shallow: '#333333',//主题背景渐变浅色
promotion_color: '#222222',//活动背景
promotion_aux_color: '#FA8B00',//活动背景辅色
main_color_shallow: '#efefef',//淡背景
price_color: 'rgba(255,0,0,1)',//价格颜色
btn_text_color: '#FFFFFF',//按钮文字颜色
goods_detail: {
goods_price: 'rgba(255,0,0,1)',//价格
promotion_tag: '#222222',
goods_card_bg: '#201A18',//会员卡背景
goods_card_bg_shallow: '#7C7878',//会员卡背景浅色
goods_card_color: '#FFD792',
goods_coupon: '#222222',
goods_cart_num_corner: '#FF0000',//购物车数量角标
goods_btn_color: '#222222',//按钮颜色
goods_btn_color_shallow: '#FA8B00',//副按钮颜色
},
pintuan: {
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',//活动背景
pintuan_promotion_aux_color: '#FD9A01',//活动背景辅色
},
super_member: {
super_member_start_bg: '#fadcb5',
super_member_end_bg: '#f6bd74',
super_member_start_text_color: '#ab6126',
super_member_end_text_color: '#d19336',
},
bargain: {
bargain_promotion_color: '#F0353E',//活动背景
bargain_promotion_aux_color: '#FD9A01',//活动辅色
},
seckill: {
seckill_promotion_color: '#F83530',//活动背景
seckill_promotion_aux_color: '#FD9A01',//活动辅色
},
giftcard: {
giftcard_promotion_color: '#FF3369',//活动背景
giftcard_promotion_aux_color: '#F7B500',//活动辅色
},
groupby: {
groupby_promotion_color: '#E64136',//活动背景
groupby_promotion_aux_color: '#F7B500',//活动辅色
},
}
}

990
common/js/util.js Normal file
View File

@@ -0,0 +1,990 @@
import Config from './config.js'
import store from '@/store/index.js'
import Http from './http.js'
import {
Weixin
} from 'common/js/wx-jssdk.js';
export default {
/**
* 页面跳转
* @param {string} to 跳转链接 /pages/idnex/index
* @param {Object} param 参数 {key : value, ...}
* @param {string} mode 模式
*/
redirectTo(to, param, mode) {
let url = to;
let tabbarList = ['/pages/index/index', '/pages/goods/category', '/pages/vr/index', '/pages/contact/contact', '/pages/member/index'];
if (param != undefined) {
Object.keys(param).forEach(function (key) {
if (url.indexOf('?') != -1) {
url += "&" + key + "=" + param[key];
} else {
url += "?" + key + "=" + param[key];
}
});
}
for (let i = 0; i < tabbarList.length; i++) {
if (url.indexOf(tabbarList[i]) == 0) {
uni.switchTab({
url
});
return;
}
}
switch (mode) {
case 'tabbar':
// 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
uni.switchTab({
url
});
break;
case 'redirectTo':
// 关闭当前页面,跳转到应用内的某个页面。
uni.redirectTo({
url
});
break;
case 'reLaunch':
// 关闭所有页面,打开到应用内的某个页面。
uni.reLaunch({
url
});
break;
default:
// 保留当前页面,跳转到应用内的某个页面
uni.navigateTo({
url
});
}
},
/**
* 图片路径转换
* @param {String} img_path 图片地址
* @param {Object} params 参数针对商品、相册里面的图片区分大中小size: big、mid、small
*/
img(img_path, params) {
var path = "";
if (img_path != undefined && img_path != "") {
if (img_path.split(',').length > 1) {
img_path = img_path.split(',')[0];
}
if (params && img_path != this.getDefaultImage().goods) {
// 过滤默认图
let arr = img_path.split(".");
let suffix = arr[arr.length - 1];
arr.pop();
arr[arr.length - 1] = arr[arr.length - 1] + "_" + params.size.toUpperCase();
arr.push(suffix);
// if(img_path.indexOf('attachment') == -1){
// img_path = arr.join(".");
// }
}
if (img_path.indexOf("http://") == -1 && img_path.indexOf("https://") == -1) {
path = Config.imgDomain + "/" + img_path;
} else {
// console.log(img_path)
path = img_path;
}
}
// path += '?t=' + parseInt(new Date().getTime() / 1000);
return path;
},
/**
* 时间戳转日期格式
* @param {Object} timeStamp
*/
timeStampTurnTime(timeStamp, type = "") {
if (timeStamp != undefined && timeStamp != "" && timeStamp > 0) {
var date = new Date();
date.setTime(timeStamp * 1000);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
if (type) {
if (type == 'yearMonthDay') {
return y + '年' + m + '月' + d + '日';
}
return y + '-' + m + '-' + d;
} else {
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}
} else {
return "";
}
},
/**
* 日期格式转时间戳
* @param {Object} string
*/
timeTurnTimeStamp(string) {
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
return (new Date(
parseInt(d[0], 10) || null,
(parseInt(d[1], 10) || 1) - 1,
parseInt(d[2], 10) || null,
parseInt(t[0], 10) || null,
parseInt(t[1], 10) || null,
parseInt(t[2], 10) || null
)).getTime() / 1000;
},
/**
* 倒计时
* @param {Object} seconds 秒
*/
countDown(seconds) {
let [day, hour, minute, second] = [0, 0, 0, 0]
if (seconds > 0) {
day = Math.floor(seconds / (60 * 60 * 24))
hour = Math.floor(seconds / (60 * 60)) - (day * 24)
minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
}
if (day < 10) {
day = '0' + day
}
if (hour < 10) {
hour = '0' + hour
}
if (minute < 10) {
minute = '0' + minute
}
if (second < 10) {
second = '0' + second
}
return {
d: day,
h: hour,
i: minute,
s: second
};
},
/**
* 数值去重
* @param {Array} arr 数组
* @param {string} field 字段
*/
unique(arr, field) {
const res = new Map();
return arr.filter((a) => !res.has(a[field]) && res.set(a[field], 1));
},
/**
* 判断值是否在数组中
* @param {Object} elem
* @param {Object} arr
*/
inArray: function (elem, arr) {
return arr == null ? -1 : arr.indexOf(elem);
},
/**
* 获取某天日期
* @param {Object} day
*/
getDay: function (day) {
var today = new Date();
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds);
const doHandleMonth = function (month) {
var m = month;
if (month.toString().length == 1) {
m = "0" + month;
}
return m
}
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
var tWeek = today.getDay();
var time = parseInt(today.getTime() / 1000);
tMonth = doHandleMonth(tMonth + 1);
tDate = doHandleMonth(tDate);
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
return {
't': time,
'y': tYear,
'm': tMonth,
'd': tDate,
'w': week[tWeek]
};
},
/**
* 图片选择加上传
* @param num
* @param params
* @param callback
* @param url
*/
upload: function (num, params, callback, url) {
// #ifdef H5
var app_type = this.isWeiXin() ? 'wechat' : 'h5';
var app_type_name = this.isWeiXin() ? '微信公众号' : 'H5';
// #endif
// #ifdef MP-WEIXIN
var app_type = 'weapp';
var app_type_name = '微信小程序';
// #endif
// #ifdef MP-ALIPAY
var app_type = 'aliapp';
var app_type_name = '支付宝小程序';
// #endif
// #ifdef MP-BAIDU
var app_type = 'baiduapp';
var app_type_name = '百度小程序';
// #endif
// #ifdef MP-TOUTIAO
var app_type = 'MP-TOUTIAO';
var app_type_name = '头条小程序';
// #endif
// #ifdef MP-QQ
var app_type = 'MP-QQ';
var app_type_name = 'QQ小程序';
// #endif
var data = {
token: store.state.token,
app_type: app_type,
app_type_name: app_type_name
}
data = Object.assign(data, params);
var imgs_num = num;
var _self = this;
uni.chooseImage({
count: imgs_num,
sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], //从相册或者拍照
success: async function (res) {
const tempFilePaths = res.tempFilePaths;
var _data = data;
var imgs = [];
uni.showLoading({
title: '图片上传中'
})
for (var i = 0; i < tempFilePaths.length; i++) {
var path = await _self.upload_file_server(tempFilePaths[i], _data, params.path,
url);
imgs.push(path);
if (imgs.length == tempFilePaths.length) {
uni.hideLoading()
uni.showToast({
title: '上传成功',
icon: 'none'
})
typeof callback == 'function' && callback(imgs);
}
}
},
fail: err => {
uni.hideLoading()
uni.showToast({
title: '上传失败',
icon: 'none'
})
}
});
},
//上传
upload_file_server(tempFilePath, data, path, url = "", callback) {
if (url) {
var uploadUrl = Config.baseUrl + url
} else {
var uploadUrl = Config.baseUrl + '/api/upload/' + path
}
return new Promise((resolve, reject) => {
uni.uploadFile({
url: uploadUrl,
filePath: tempFilePath,
name: 'file',
fileType: data.fileType || 'image',
formData: data,
success: function (res) {
var path_str = JSON.parse(res.data);
if (path_str.code >= 0) {
resolve(path_str.data.pic_path);
typeof callback == 'function' && callback(path_str.data.pic_path);
} else {
reject("error");
}
}
});
});
},
/**
* 复制
* @param {Object} value
* @param {Object} callback
*/
copy(value, callback) {
// #ifdef H5
var oInput = document.createElement('input'); //创建一个隐藏input重要
oInput.value = value; //赋值
oInput.setAttribute("readonly", "readonly");
document.body.appendChild(oInput);
oInput.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
oInput.className = 'oInput';
oInput.style.display = 'none';
uni.hideKeyboard();
this.showToast({
title: '复制成功'
});
typeof callback == 'function' && callback();
// #endif
// #ifdef MP || APP-PLUS
uni.setClipboardData({
data: value,
success: () => {
typeof callback == 'function' && callback();
}
});
// #endif
},
/**
* 是否是微信浏览器
*/
isWeiXin() {
// #ifndef H5
return false;
// #endif
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
},
/**
* 显示消息提示框
* @param {Object} params 参数
*/
showToast(params = {}) {
params.title = params.title || "";
params.icon = params.icon || "none";
// params.position = params.position || 'bottom';
params.duration = params.duration || 1500;
uni.showToast(params);
if (params.success) params.success();
},
/**
* 检测苹果X以上的手机
*/
isIPhoneX() {
let res = uni.getSystemInfoSync();
if (res.model.search('iPhone X') != -1) {
return true;
}
return false;
},
//判断安卓还是iOS
isAndroid() {
let platform = uni.getSystemInfoSync().platform
if (platform == 'ios') {
return false;
} else if (platform == 'android') {
return true;
}
},
/**
* 深度拷贝对象
* @param {Object} obj
*/
deepClone(obj) {
const isObject = function (obj) {
return typeof obj == 'object';
}
if (!isObject(obj)) {
throw new Error('obj 不是一个对象!')
}
//判断传进来的是对象还是数组
let isArray = Array.isArray(obj)
let cloneObj = isArray ? [] : {}
//通过for...in来拷贝
for (let key in obj) {
cloneObj[key] = isObject(obj[key]) ? this.deepClone(obj[key]) : obj[key]
}
return cloneObj
},
/**
* 自定义模板的跳转链接
* @param {Object} link
*/
diyRedirectTo(link) {
//if (link == null || Object.keys(link).length == 1) return;
// 外部链接
if (link.wap_url && link.wap_url.indexOf('http') != -1 || link.wap_url && link.wap_url.indexOf('http') != -1) {
// #ifdef H5
window.location.href = link.wap_url;
// #endif
// #ifdef MP
this.redirectTo('/pages_tool/webview/webview', {
src: encodeURIComponent(link.wap_url)
});
// #endif
} else if (link.appid) {
// 跳转其他小程序
uni.navigateToMiniProgram({
appId: link.appid,
path: link.page
})
} else if (link.name == 'MOBILE' && !link.wap_url) {
// 拨打电话
uni.makePhoneCall({
phoneNumber: link.mobile,
success: (res) => {
},
fail: (res) => {
}
});
} else if (link.name == 'MEMBER_CONTACT') {
// 客服
let servicerConfig = store.state.servicerConfig
let config = {
type: 'none'
};
// #ifdef H5
config = servicerConfig.h5;
// #endif
// #ifdef MP-WEIXIN
config = servicerConfig.weapp;
// #endif
switch (config.type) {
case 'wxwork':
// 企业微信客服
// #ifdef H5
window.location.href = config.wxwork_url;
// #endif
// #ifdef MP-WEIXIN
wx.openCustomerServiceChat({
extInfo: {
url: config.wxwork_url
},
corpId: config.corpid,
showMessageCard: true,
sendMessageTitle: 'this.sendMessageTitle',
sendMessagePath: 'this.sendMessagePath',
sendMessageImg: 'this.sendMessageImg'
});
// #endif
break;
case 'third':
// 第三方客服
window.location.href = config.third_url;
break;
case 'niushop':
// Niushop客服
this.redirectTo('/pages_tool/chat/room');
break;
case 'weapp':
// 微信小程序,由于需要手动点击按钮触发,所以要跳转到中间页
this.redirectTo(link.wap_url);
break;
default:
// 拨打客服电话
let siteInfo = store.state.siteInfo;
if (siteInfo && siteInfo.site_tel) {
uni.makePhoneCall({
phoneNumber: siteInfo.site_tel
});
} else {
this.showToast({
title: '抱歉,商家暂无客服,请线下联系',
})
}
}
} else if (link.wap_url) {
this.redirectTo(link.wap_url);
}
},
/**
* 获取默认图
*/
getDefaultImage() {
let defaultImg = store.state.defaultImg;
defaultImg.goods = this.img(defaultImg.goods);
defaultImg.head = this.img(defaultImg.head);
defaultImg.store = this.img(defaultImg.store);
defaultImg.article = this.img(defaultImg.article);
defaultImg.kefu = this.img(defaultImg.kefu);
defaultImg.phone = this.img(defaultImg.phone);
return defaultImg;
},
/**
* 判断手机是否为iphoneX系列
*/
uniappIsIPhoneX() {
let isIphoneX = false;
let systemInfo = uni.getSystemInfoSync();
// #ifdef MP
if (systemInfo.model.search('iPhone X') != -1 || systemInfo.model.search('iPhone 11') != -1 || systemInfo.model.search('iPhone 12') != -1 || systemInfo.model.search('iPhone 13') != -1) {
isIphoneX = true;
}
// #endif
// #ifdef H5
var u = navigator.userAgent;
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isIOS) {
if (systemInfo.screenWidth == 375 && systemInfo.screenHeight == 812 && systemInfo.pixelRatio == 3) {
isIphoneX = true;
} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 3) {
isIphoneX = true;
} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 2) {
isIphoneX = true;
}
}
// #endif
return isIphoneX;
},
/**
* 判断手机是否为iphone11系列
*/
uniappIsIPhone11() {
let isIphone11 = false;
let systemInfo = uni.getSystemInfoSync();
// #ifdef MP
if (systemInfo.model.search('iPhone 11') != -1) {
isIphone11 = true;
}
// #endif
return isIphone11;
},
// #ifdef H5
//判断该浏览器是否为safaria浏览器
isSafari() {
let res = uni.getSystemInfoSync();
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('applewebkit') > -1 && ua.indexOf('mobile') > -1 && ua.indexOf('safari') > -1 &&
ua.indexOf('linux') === -1 && ua.indexOf('android') === -1 && ua.indexOf('chrome') === -1 &&
ua.indexOf('ios') === -1 && ua.indexOf('browser') === -1) {
return true;
} else {
return false;
}
},
// #endif
numberFixed(e, f) {
if (!f) {
f = 0;
}
return Number(e).toFixed(f);
},
/**
* 获取url参数
*/
getUrlCode(callback) {
var url = location.search;
var theRequest = new Object();
if (url.indexOf('?') != -1) {
var str = url.substr(1);
var strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
}
}
typeof callback == 'function' && callback(theRequest);
},
/**
* 获取当前页面路由
*/
getCurrRoute() {
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
return routes.length ? routes[routes.length - 1].route : '';
},
goBack(backUrl = '/pages/index/index') {
if (getCurrentPages().length == 1) {
this.redirectTo(backUrl);
} else {
uni.navigateBack();
}
},
/**
*
* @param val 转化时间字符串 (转化时分秒)
* @returns {string}
*/
getTimeStr(val) {
var h = parseInt(val / 3600).toString();
var m = parseInt((val % 3600) / 60).toString();
if (m.length == 1) {
m = '0' + m;
}
if (h.length == 1) {
h = '0' + h;
}
return h + ':' + m;
},
/**
* 获取定位信息
*/
getLocation(param = {}) {
/*uni.getLocation({
type: param.type ?? 'gcj02',
success: res => {
store.commit('setLocation', res);
typeof param.success == 'function' && param.success(res);
},
fail: res => {
typeof param.fail == 'function' && param.fail(res);
},
complete: res => {
typeof param.complete == 'function' && param.complete(res);
}
});*/
},
// 计算两个经纬度之间的距离
getDistance(lat1, lng1, lat2, lng2) {
var radLat1 = lat1 * Math.PI / 180.0;
var radLat2 = lat2 * Math.PI / 180.0;
var a = radLat1 - radLat2;
var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137; // EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
},
//记录分享人
onSourceMember(source_member) {
Http.sendRequest({
url: '/api/Member/alterShareRelation',
data: {
share_member: source_member,
},
success: res => {
if (res.code >= 0) {
uni.removeStorage({
key: 'source_member',
success: res => {
console.log('删除成功', res)
}
})
}
}
})
},
/**
* 微信订阅消息
*/
subscribeMessage(keywords) {
// #ifdef MP-WEIXIN
let url = '/weapp/api/weapp/messagetmplids';
// #endif
// #ifdef MP-ALIPAY
let url = '/aliapp/api/aliapp/messagetmplids';
// #endif
Http.sendRequest({
url,
data: {
keywords: keywords
},
success: res => {
if (res.data.length) {
// #ifdef MP-WEIXIN
uni.requestSubscribeMessage({
tmplIds: res.data,
success: (res) => {
console.log("res", res)
},
fail: (res) => {
console.log('fail', res)
}
})
// #endif
// #ifdef MP-ALIPAY
my.requestSubscribeMessage({
entityIds: res.data,
success: res => {
console.log("res", res)
},
fail: res => {
console.log('fail', res)
}
});
// #endif
}
}
})
},
/**
* 获取小程序分享内容数据
*/
getMpShare(path) {
//如果没有特别指定 则获取当前页面的路由
if (!path) {
let route = this.getCurrentRoute();
path = route.path;
if (path == '/pages/member/index') {
return new Promise((resolve, reject) => {
resolve({})
});
}
}
return new Promise((resolve, reject) => {
Http.sendRequest({
url: "/weapp/api/weapp/share",
data: {
path: path
},
success: res => {
if (res.code >= 0) {
let shareConfig = res.data.data;
if (shareConfig) {
//分享给好友
let appMessageData = {
title: shareConfig.title,
path: shareConfig.path,
imageUrl: shareConfig.imageUrl,
success: res => {
},
fail: res => {
}
}
//分享到朋友圈
let query = '';
if (shareConfig.path.indexOf('?') > 0) {
query = shareConfig.path.split('?')[1];
}
let timeLineData = {
title: shareConfig.title,
query: shareConfig.path,
imageUrl: shareConfig.imageUrl,
}
resolve({
appMessage: appMessageData,
timeLine: timeLineData,
})
} else {
reject(res.data);
}
} else {
reject(res.data)
}
}
});
})
},
/**
* 设置公众号分享
* @param shareData
* @param callback
*/
setPublicShare(shareData, callback) {
if (!this.isWeiXin()) return;
Http.sendRequest({
url: '/wechat/api/wechat/jssdkconfig',
data: {
url: uni.getSystemInfoSync().platform == 'ios' ? uni.getStorageSync('initUrl') : window.location
.href
},
success: res => {
if (res.code == 0) {
var wxJS = new Weixin();
wxJS.init(res.data);
wxJS.weixin.showOptionMenu();
wxJS.setShareData({
title: shareData.title ?? '',
desc: shareData.desc ?? '',
link: shareData.link ?? location.href,
imgUrl: shareData.imgUrl ? this.img(shareData.imgUrl) : ''
}, (res) => {
typeof callback == 'function' && callback(res);
})
}
}
})
},
//获取当前路由
getCurrentRoute() {
let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
let currentParam = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
// 拼接参数
let param = [];
for (let key in currentParam) {
param.push(key + '=' + currentParam[key])
}
let currentPath = '/' + currentRoute;
let currentQuery = param.join('&');
if (currentQuery) currentPath += '?' + currentQuery;
return {
path: currentPath,
query: currentQuery,
}
},
//获取分享路由
getCurrentShareRoute(member_id) {
let route = this.getCurrentRoute();
//去掉原来的分享人数据
route.path = route.path.replace(/[?|&]source_member=\d+/, '');
if (member_id) {
//路径的处理
if (route.path.indexOf('?') > 0) {
route.path += '&';
} else {
route.path += '?';
}
route.path += 'source_member=' + member_id;
//参数的处理
if (route.query) {
route.query += '&';
}
route.query += 'source_member=' + member_id;
}
return route;
},
/**
* 对象转style字符串
* @param {Object} obj
*/
objToStyle(obj) {
let s = [];
for (let i in obj) {
s.push(i + ':' + obj[i]);
}
return s.join(';')
},
/**
* 颜色减值
* @param {Object} c1
* @param {Object} c2
* @param {Object} ratio
*/
colourBlend(c1, c2, ratio) {
ratio = Math.max(Math.min(Number(ratio), 1), 0)
let r1 = parseInt(c1.substring(1, 3), 16)
let g1 = parseInt(c1.substring(3, 5), 16)
let b1 = parseInt(c1.substring(5, 7), 16)
let r2 = parseInt(c2.substring(1, 3), 16)
let g2 = parseInt(c2.substring(3, 5), 16)
let b2 = parseInt(c2.substring(5, 7), 16)
let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
r = ('0' + (r || 0).toString(16)).slice(-2)
g = ('0' + (g || 0).toString(16)).slice(-2)
b = ('0' + (b || 0).toString(16)).slice(-2)
return '#' + r + g + b
},
/**
* 生成贝塞尔曲线轨迹
* @param {Object} points
* @param {Object} times
*/
bezier(points, times) {
var bezier_points = [];
var points_D = [];
var points_E = [];
const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0][
'y'
], 2));
// 邻控制BC点间距
const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1][
'y'
], 2));
// D每次在AB方向上移动的距离
if (points[0]['x'] > points[2]['x']) {
var EACH_MOVE_AD = -(DIST_AB / times);
// E每次在BC方向上移动的距离
var EACH_MOVE_BE = -(DIST_BC / times);
} else {
var EACH_MOVE_AD = +(DIST_AB / times);
// E每次在BC方向上移动的距离
var EACH_MOVE_BE = +(DIST_BC / times);
}
// 点AB的正切
const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
// 点BC的正切
const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
// 点AB的弧度值
const RADIUS_AB = Math.atan(TAN_AB);
// 点BC的弧度值
const RADIUS_BC = Math.atan(TAN_BC);
// 每次执行
for (var i = 1; i <= times; i++) {
// AD的距离
var dist_AD = EACH_MOVE_AD * i;
// BE的距离
var dist_BE = EACH_MOVE_BE * i;
// D点的坐标
var point_D = {};
point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
points_D.push(point_D);
// E点的坐标
var point_E = {};
point_E['x'] = dist_BE * Math.cos(RADIUS_BC) + points[1]['x'];
point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
points_E.push(point_E);
// 此时线段DE的正切值
var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
// tan_DE的弧度值
var radius_DE = Math.atan(tan_DE);
// 地市DE的间距
var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']),
2));
// 此时DF的距离
var dist_DF = (dist_AD / DIST_AB) * dist_DE;
// 此时DF点的坐标
var point_F = {};
point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];
bezier_points.push(point_F);
}
return {
'bezier_points': bezier_points
};
},
/**
* 验证手机号
* @param {string} mobile 被验证的mobile
* @return {object} 验证后的结果
**/
verifyMobile(mobile) {
var parse = /^\d{11}$/.test(mobile);
return parse;
}
}

165
common/js/validate.js Normal file
View File

@@ -0,0 +1,165 @@
/**
* 数据验证(表单验证)
*/
module.exports = {
error: '',
check: function (data, rule) {
for (var i = 0; i < rule.length; i++) {
if (!rule[i].checkType) {
return true;
}
if (!rule[i].name) {
return true;
}
if (!rule[i].errorMsg) {
return true;
}
if (!data[rule[i].name]) {
this.error = rule[i].errorMsg;
return false;
}
switch (rule[i].checkType) {
case 'custom':
if (typeof rule[i].validate == 'function') {
if (!rule[i].validate(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
}
break;
case 'required':
var reg = new RegExp('/[\S]+/');
if (reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'string':
var reg = new RegExp('^.{' + rule[i].checkRule + '}$');
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'int':
var reg = new RegExp('^(-[1-9]|[1-9])[0-9]{' + rule[i].checkRule + '}$');
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'between':
if (!this.isNumber(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'betweenD':
var reg = /^-?[1-9][0-9]?$/;
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'betweenF':
var reg = /^-?[0-9][0-9]?.+[0-9]+$/;
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
var minMax = rule[i].checkRule.split(',');
minMax[0] = Number(minMax[0]);
minMax[1] = Number(minMax[1]);
if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'same':
if (data[rule[i].name] != rule[i].checkRule) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'notsame':
if (data[rule[i].name] == rule[i].checkRule) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'email':
var reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'phoneno':
var reg = /^\d{11}$/;
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'zipcode':
var reg = /^[0-9]{6}$/;
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'reg':
var reg = new RegExp(rule[i].checkRule);
if (!reg.test(data[rule[i].name])) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'in':
if (rule[i].checkRule.indexOf(data[rule[i].name]) == -1) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'notnull':
if (data[rule[i].name] == 0 || data[rule[i].name] == undefined || data[rule[i].name] == null || data[rule[i].name]
.length < 1) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'lengthMin':
if (data[rule[i].name].length < rule[i].checkRule) {
this.error = rule[i].errorMsg;
return false;
}
break;
case 'lengthMax':
if (data[rule[i].name].length > rule[i].checkRule) {
this.error = rule[i].errorMsg;
return false;
}
break;
}
}
return true;
},
isNumber: function (checkVal) {
var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
return reg.test(checkVal);
}
}

119
common/js/wx-jssdk.js Normal file
View File

@@ -0,0 +1,119 @@
/**
* 微信jssdk调用
*/
let Weixin = function () {
var wx = require('jweixin-module');
this.weixin = wx;
this.init = function (params) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来若要查看传入的参数可以在pc端打开参数信息会通过log打出仅在pc端时才会打印。
appId: params.appId, // 必填,公众号的唯一标识
timestamp: params.timestamp, // 必填,生成签名的时间戳
nonceStr: params.nonceStr, // 必填,生成签名的随机串
signature: params.signature, // 必填,签名
jsApiList: ['chooseWXPay', 'openAddress', 'updateAppMessageShareData',
'updateTimelineShareData', 'scanQRCode', 'hideMenuItems'
] // 必填需要使用的JS接口列表
});
}
/**
* 发起支付
* @param jsApiParame
* @param callback
* @param cancel
*/
this.pay = function (jsApiParame, callback, cancel) {
wx.ready(function () {
wx.chooseWXPay({
timestamp: jsApiParame
.timestamp, // 支付签名时间戳注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: jsApiParame.nonceStr, // 支付签名随机串,不长于 32 位
package: jsApiParame.package, // 统一支付接口返回的prepay_id参数值提交格式如prepay_id=\*\*\*
signType: jsApiParame.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: jsApiParame.paySign, // 支付签名
success: function (res) {
typeof callback == 'function' && callback(res);
},
cancel: function (res) {
typeof cancel == 'function' && cancel(res);
}
});
})
}
/**
* 获取收货地址
* @param {Object} callback
*/
this.openAddress = function (callback) {
wx.ready(function () {
wx.openAddress({
success: function (res) {
typeof callback == 'function' && callback(res);
},
fail: (res) => {
console.log('获取收货地址 fail',res);
alert(JSON.stringify(res))
}
});
})
}
/**
* 分享给好友
* @param {Object} params
* @param {Object} callback
*/
this.setShareData = function (params, callback) {
wx.ready(function () {
// 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
wx.updateAppMessageShareData({
title: params.title || '', // 分享标题
desc: params.desc || '', // 分享描述
link: params.link || '', // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: params.imgUrl || '', // 分享图标
success: function (res) {
typeof callback == 'function' && callback(res);
},
fail: function (err) {
}
})
// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
wx.updateTimelineShareData({
title: params.title || '', // 分享标题
link: params.link || '', // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: params.imgUrl || '', // 分享图标
success: function (res) {
typeof callback == 'function' && callback(res);
}
})
});
}
/**
* 扫一扫
* @param {Object} callback
*/
this.scanQRCode = function (callback) {
wx.ready(function () {
wx.scanQRCode({
needResult: 1,
scanType: ["qrCode"],
success: function (res) {
typeof callback == 'function' && callback(res);
}
});
})
}
}
export {
Weixin
}