miao33: 从 main 同步 single_uniapp22miao,dart-sass 兼容修复,DEPLOY.md 更新

- 从 main 获取 single_uniapp22miao 子项目
- dart-sass: /deep/ -> ::v-deep,calc 运算符加空格
- DEPLOY.md 采用 shccd159 版本(4 子项目架构说明)

Made-with: Cursor
This commit is contained in:
apple
2026-03-16 11:16:42 +08:00
parent 9c29721dc4
commit 079076a70e
356 changed files with 569762 additions and 129 deletions

View File

@@ -0,0 +1,89 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
const arrTemp = ["beforePay","afterPay", "createBargain","pink"];
// export function auth() {
// let tmplIds = {};
// let messageTmplIds = uni.getStorageSync(SUBSCRIBE_MESSAGE);
// tmplIds = messageTmplIds ? JSON.parse(messageTmplIds) : {};
// return tmplIds;
// }
/**
* 支付成功后订阅消息id
* 订阅 确认收货通知 订单支付成功 新订单管理员提醒
*/
export function openPaySubscribe() {
let tmplIds = uni.getStorageSync('tempID' + arrTemp[0]);
return subscribe(tmplIds);
}
/**
* 订单相关订阅消息
* 送货 发货 取消订单
*/
export function openOrderSubscribe() {
let tmplIds = uni.getStorageSync('tempID' + arrTemp[1]);
return subscribe(tmplIds);
}
/**
* 提现消息订阅
* 成功 和 失败 消息
*/
// export function openExtrctSubscribe() {
// let tmplIds = uni.getStorageSync('tempID' + arrTemp[2]);
// return subscribe(tmplIds);
// }
/**
* 砍价成功
*/
export function openBargainSubscribe() {
let tmplIds = uni.getStorageSync('tempID' + arrTemp[2]);
return subscribe(tmplIds);
}
/**
* 拼团成功
*/
export function openPinkSubscribe() {
let tmplIds = uni.getStorageSync('tempID' + arrTemp[3]);
return subscribe(tmplIds);
}
// /**
// * 提现
// */
// export function openEextractSubscribe() {
// let tmplIds = JSON.parse(uni.getStorageSync('tempID' + paySubscribe));
// return subscribe(tmplIds);
// }
/**
* 调起订阅界面
* array tmplIds 模板id
*/
export function subscribe(tmplIds) {
let wecaht = wx;
return new Promise((reslove, reject) => {
wecaht.requestSubscribeMessage({
tmplIds: tmplIds,
success(res) {
return reslove(res);
},
fail(res) {
return reslove(res);
}
})
});
}

View File

@@ -0,0 +1,26 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
module.exports = {
/*
-----仅在APP生效-----
slide-in-right 新窗体从右侧进入
slide-in-left 新窗体从左侧进入
slide-in-top 新窗体从顶部进入
slide-in-bottom 新窗体从底部进入
pop-in 新窗体从左侧进入,且老窗体被挤压而出
fade-in 新窗体从透明到不透明逐渐显示
zoom-out 新窗体从小到大缩放显示
zoom-fade-out 新窗体从小到大逐渐放大并且从透明到不透明逐渐显示
none 无动画
*/
type:'zoom-fade-out',
duration:200
}

View File

@@ -0,0 +1,23 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import CryptoJS from './crypto-js.js'
/**
* @word 要加密的内容
* @keyWord String 服务器随机返回的关键字
* */
export function aesEncrypt(word, keyWord = "XwKsGlMcdPMEhR1B") {
var key = CryptoJS.enc.Utf8.parse(keyWord);
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}

View File

@@ -0,0 +1,33 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
const fsm = wx.getFileSystemManager ? wx.getFileSystemManager() : null;
const FILE_BASE_NAME = 'tmp_base64src'; //自定义文件名
export function base64src(base64data, dateminutes, cb) {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
if (!format) {
return (new Error('ERROR_BASE64SRC_PARSE'));
}
const filePath = `${wx.env.USER_DATA_PATH}/${dateminutes+FILE_BASE_NAME}.${format}`;
const buffer = wx.base64ToArrayBuffer(bodyData);
fsm.writeFile({
filePath,
data: buffer,
encoding: 'binary',
success() {
cb(filePath);
},
fail() {
return (new Error('ERROR_BASE64SRC_WRITE'));
},
});
};
//module.exports = base64src;

View File

@@ -0,0 +1,247 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import { EXPIRE } from '../config/app';
class Cache {
constructor(handler) {
this.cacheSetHandler = uni.setStorageSync;
this.cacheGetHandler = uni.getStorageSync;
this.cacheClearHandler = uni.removeStorageSync;
this.cacheExpire = '_expire_2029_12_17_18_44';
this.name = 'storage';
}
/**
* 获取当前时间戳
*/
time()
{
return Math.round(new Date() / 1000);
}
/**
* 日期字符串转时间戳
* @param {Object} expiresTime
*/
strTotime(expiresTime){
let expires_time = expiresTime.substring(0, 19);
expires_time = expires_time.replace(/-/g, '/');
return Math.round(new Date(expires_time).getTime() / 1000);
}
setExpireCaheTag(key, expire) {
expire = expire !== undefined ? expire : EXPIRE;
if (typeof expire === 'number') {
let tag = this.cacheGetHandler(this.cacheExpire), newTag = [],newKeys = [];
if (typeof tag === 'object' && tag.length) {
newTag = tag.map(item => {
newKeys.push(item.key);
if (item.key === key) {
item.expire = expire === 0 ? 0 : this.time() + expire;
}
return item;
});
}
if (!newKeys.length || newKeys.indexOf(key) === -1) {
newTag.push({
key: key,
expire: expire === 0 ? 0 : this.time() + expire
});
}
this.cacheSetHandler(this.cacheExpire, newTag);
}
}
/**
* 设置过期时间缓存
* @param {Object} name key
* @param {Object} value value
* @param {Object} expire 过期时间
* @param {Object} startTime 记录何时将值存入缓存,毫秒级
*/
setItem(params){
let obj = {
name:'',
value:'',
expires:"",
startTime:new Date().getTime()
}
let options = {};
//将obj和传进来的params合并
Object.assign(options,obj,params);
if(options.expires){
//如果options.expires设置了的话
//以options.name为keyoptions为值放进去
// localStorage.setItem(options.name,JSON.stringify(options));
uni.setStorageSync(options.name,JSON.stringify(options));
}else{
//如果options.expires没有设置就判断一下value的类型
let type = Object.prototype.toString.call(options.value);
//如果value是对象或者数组对象的类型就先用JSON.stringify转一下再存进去
if(Object.prototype.toString.call(options.value) == '[object Object]'){
options.value = JSON.stringify(options.value);
}
if(Object.prototype.toString.call(options.value) == '[object Array]'){
options.value = JSON.stringify(options.value);
}
// localStorage.setItem(options.name,options.value);
uni.setStorageSync(options.name,options.value);
}
}
/**
* 缓存是否过期,过期自动删除
* @param {Object} key
* @param {Object} $bool true = 删除,false = 不删除
*/
getExpireCahe(key,$bool)
{
try{
let time = this.cacheGetHandler(key + this.cacheExpire);
if (time) {
let newTime = parseInt(time);
if (time && time < this.time() && !Number.isNaN(newTime)) {
if ($bool === undefined || $bool === true) {
this.cacheClearHandler(key);
this.cacheClearHandler(key + this.cacheExpire);
}
return false;
} else
return true;
} else {
return !!this.cacheGetHandler(key);
}
}catch(e){
return false;
}
}
/**
* 设置缓存
* @param {Object} key
* @param {Object} data
*/
set(key,data,expire){
if(typeof data === 'object')
data = JSON.stringify(data);
try{
this.setExpireCaheTag(key,expire);
return this.cacheSetHandler(key,data);
}catch(e){
return false;
}
}
/**
* 检测缓存是否存在
* @param {Object} key
*/
has(key)
{
return this.getExpireCahe(key);
}
/**
* 获取缓存
* @param {Object} key
* @param {Object} $default
* @param {Object} expire
*/
get(key,$default,expire){
try{
let isBe = this.getExpireCahe(key);
let data = this.cacheGetHandler(key);
if (data && isBe) {
if (typeof $default === 'boolean')
return JSON.parse(data);
else
return data;
} else {
if (typeof $default === 'function') {
let value = $default();
this.set(key,value,expire);
return value;
} else {
this.set(key,$default,expire);
return $default;
}
}
}catch(e){
return null;
}
}
/**
* 删除缓存
* @param {Object} key
*/
clear(key)
{
try{
let cahceValue = this.cacheGetHandler(key + this.cacheExpire);
if(cahceValue)
this.cacheClearHandler(key + this.cacheExpire);
return this.cacheClearHandler(key);
}catch(e){
return false;
}
}
/**
* 清除过期缓存
*/
clearOverdue()
{
// let cacheList = uni.getStorageInfoSync(),that = this;
// if (typeof cacheList.keys === 'object'){
// cacheList.keys.forEach(item=>{
// that.getExpireCahe(item);
// })
// }
}
/**
* 获取缓存,调用后无需转换数据类型
* @param {Object} key
*/
getItem(name){
// let item = localStorage.getItem(name);
let item = uni.getStorageSync(name);
//先将拿到的试着进行json转为对象的形式
try{
item = JSON.parse(item);
}catch(error){
//如果不行就不是json的字符串就直接返回
item = item;
}
//如果有startTime的值说明设置了失效时间
if(item.startTime){
let date = new Date().getTime();
//何时将值取出减去刚存入的时间与item.expires比较如果大于就是过期了如果小于或等于就还没过期
if(date - item.startTime > item.expires){
//缓存过期清除缓存返回false
// localStorage.removeItem(name);
uni.removeStorageSync(name);
return false;
}else{
//缓存未过期,返回值
return item.value;
}
}else{
//如果没有设置失效时间,直接返回值
return item;
}
}
}
export default new Cache;

View File

@@ -0,0 +1,15 @@
import {HTTP_REQUEST_URL,HEADER,TOKENNAME,HEADERPARAMS} from '@/config/app';
import store from "../store";
export function checkOverdue(data) {
let Url = HTTP_REQUEST_URL,header = HEADER;
uni.request({
url: Url + '/api/front/user',
method: 'GET',
header: header,
success:(res) =>{
if([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1){
store.commit("LOGOUT");
}
}
})
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
let app = getApp();

View File

@@ -0,0 +1,72 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
export default [
"em-smile",
"em-laughing",
"em-blush",
"em-smiley",
"em-relaxed",
"em-smirk",
"em-heart_eyes",
"em-kissing_heart",
"em-kissing_closed_eyes",
"em-flushed",
"em-relieved",
"em-satisfied",
"em-grin",
"em-wink",
"em-stuck_out_tongue_winking_eye",
"em-stuck_out_tongue_closed_eyes",
"em-grinning",
"em-kissing",
"em-kissing_smiling_eyes",
"em-stuck_out_tongue",
"em-sleeping",
"em-worried",
"em-frowning",
"em-anguished",
"em-open_mouth",
"em-grimacing",
"em-confused",
"em-hushed",
"em-expressionless",
"em-unamused",
"em-sweat_smile",
"em-sweat",
"em-disappointed_relieved",
"em-weary",
"em-pensive",
"em-disappointed",
"em-confounded",
"em-fearful",
"em-cold_sweat",
"em-persevere",
"em-cry",
"em-sob",
"em-joy",
"em-astonished",
"em-scream",
"em-tired_face",
"em-angry",
"em-rage",
"em-triumph",
"em-sleepy",
"em-yum",
"em-mask",
"em-sunglasses",
"em-dizzy_face",
"em-imp",
"em-smiling_imp",
"em-neutral_face",
"em-no_mouth",
"em-innocent",
"em-alien"
];

View File

@@ -0,0 +1,100 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import { spread } from "@/api/user";
import Cache from "@/utils/cache";
import { getCity } from '@/api/api.js';
/**
* 静默授权绑定上下级,使用在已经登录后扫描了别人的推广二维码
* @param {Object} puid
*/
export function silenceBindingSpread() {
//#ifdef H5
let puid = Cache.get('spread');
//#endif
//#ifdef MP || APP-PLUS
let puid = getApp().globalData.spread;
//#endif
puid = parseInt(puid);
if (Number.isNaN(puid)) {
puid = 0;
}
if (puid) {
spread(puid).then(res => {}).catch(res => {
//#ifdef H5
Cache.clear("spread");
//#endif
//#ifdef MP || APP-PLUS
getApp().globalData.spread = 0;
//#endif
});
} else {
Cache.set('spread', 0);
}
}
export function isWeixin() {
return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}
export function parseQuery() {
const res = {};
const query = (location.href.split("?")[1] || "")
.trim()
.replace(/^(\?|#|&)/, "");
if (!query) {
return res;
}
query.split("&").forEach(param => {
const parts = param.replace(/\+/g, " ").split("=");
const key = decodeURIComponent(parts.shift());
const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;
if (res[key] === undefined) {
res[key] = val;
} else if (Array.isArray(res[key])) {
res[key].push(val);
} else {
res[key] = [res[key], val];
}
});
return res;
}
// #ifdef H5
const VUE_APP_WS_URL = process.env.VUE_APP_WS_URL || `ws://${location.hostname}:20001`;
export {
VUE_APP_WS_URL
}
// #endif
// 获取地址数据
export function getCityList() {
return new Promise((resolve, reject) => {
getCity().then(res => {
resolve(res.data);
let oneDay = 24 * 3600 * 1000;
Cache.setItem({
name: 'cityList',
value: res.data,
expires: oneDay * 7
}); //设置七天过期时间
})
});
}
export default parseQuery;

View File

@@ -0,0 +1,334 @@
// +----------------------------------------------------------------------
// | 路由导航工具类
// +----------------------------------------------------------------------
// | 提供统一的路由跳转方法,支持路径别名和参数处理
// +----------------------------------------------------------------------
/**
* 路由别名映射表
* 将简短的别名映射到实际的页面路径
*/
export const routeAlias = {
// 主要页面
'/': '/pages/index/index',
'/home': '/pages/index/index',
'/index': '/pages/index/index',
'/user': '/pages/personal/index',
'/personal': '/pages/personal/index',
'/rushing': '/pages/rushing/index',
// 登录相关
'/login': '/pages/sub-pages/login/index',
'/register': '/pages/sub-pages/login/register',
'/reset-pwd': '/pages/sub-pages/login/reset-account',
'/change-pwd': '/pages/sub-pages/login/change-pwd',
// 签名功能
'/sign': '/pages/sub-pages/webview/sign',
'/sign-preview': '/pages/sub-pages/webview/sign-preview',
// 订单相关
'/orders': '/pages/sub-pages/rushing-order/index',
'/order-detail': '/pages/sub-pages/rushing-order/detail',
// 用户信息
'/profile': '/pages/sub-pages/user-info/index',
'/address': '/pages/sub-pages/address/index',
'/address-edit': '/pages/sub-pages/address/detail',
// 财务相关
'/balance': '/pages/sub-pages/balance/index',
'/withdraw': '/pages/sub-pages/withdraw/index',
'/withdraw-log': '/pages/sub-pages/withdraw/list',
'/prize': '/pages/sub-pages/prize/index',
// 其他功能
'/coupon': '/pages/sub-pages/coupon/index',
'/invite': '/pages/sub-pages/invite/index',
'/fans': '/pages/sub-pages/my-fans/index',
'/payee': '/pages/sub-pages/my-payee/index',
'/search': '/pages/sub-pages/search/index',
'/settings': '/pages/sub-pages/setting/index',
'/agreement': '/pages/sub-pages/agreement/index',
}
/**
* 将路径别名解析为实际路径
* @param {String} path - 路径或别名
* @returns {String} 实际路径
*/
function resolveAlias(path) {
// 如果是别名,返回实际路径
if (routeAlias[path]) {
return routeAlias[path]
}
// 否则返回原路径
return path
}
/**
* 构建带查询参数的URL
* @param {String} path - 路径
* @param {Object} query - 查询参数对象
* @returns {String} 完整URL
*/
function buildUrl(path, query = {}) {
const resolvedPath = resolveAlias(path)
const queryString = Object.keys(query)
.filter(key => query[key] !== undefined && query[key] !== null)
.map(key => `${key}=${encodeURIComponent(query[key])}`)
.join('&')
return queryString ? `${resolvedPath}?${queryString}` : resolvedPath
}
/**
* 路由导航类
*/
export const Navigation = {
/**
* 保留当前页面,跳转到应用内的某个页面
* @param {String} path - 页面路径或别名
* @param {Object} query - 查询参数
* @returns {Promise}
*
* @example
* Navigation.push('/sign', { id: 123 })
* Navigation.push('/pages/sub-pages/webview/sign', { id: 123 })
*/
push(path, query = {}) {
const url = buildUrl(path, query)
return new Promise((resolve, reject) => {
uni.navigateTo({
url,
success: resolve,
fail: reject
})
})
},
/**
* 关闭当前页面,跳转到应用内的某个页面
* @param {String} path - 页面路径或别名
* @param {Object} query - 查询参数
* @returns {Promise}
*
* @example
* Navigation.replace('/login')
*/
replace(path, query = {}) {
const url = buildUrl(path, query)
return new Promise((resolve, reject) => {
uni.redirectTo({
url,
success: resolve,
fail: reject
})
})
},
/**
* 关闭所有页面,打开到应用内的某个页面
* @param {String} path - 页面路径或别名
* @param {Object} query - 查询参数
* @returns {Promise}
*
* @example
* Navigation.reLaunch('/home')
*/
reLaunch(path, query = {}) {
const url = buildUrl(path, query)
return new Promise((resolve, reject) => {
uni.reLaunch({
url,
success: resolve,
fail: reject
})
})
},
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
* @param {String} path - tabBar 页面路径或别名
* @returns {Promise}
*
* @example
* Navigation.switchTab('/home')
*/
switchTab(path) {
const url = resolveAlias(path)
return new Promise((resolve, reject) => {
uni.switchTab({
url,
success: resolve,
fail: reject
})
})
},
/**
* 关闭当前页面,返回上一页面或多级页面
* @param {Number} delta - 返回的页面数,如果 delta 大于现有页面数,则返回到首页
* @returns {Promise}
*
* @example
* Navigation.back()
* Navigation.back(2)
*/
back(delta = 1) {
return new Promise((resolve, reject) => {
uni.navigateBack({
delta,
success: resolve,
fail: reject
})
})
},
/**
* 预加载页面
* @param {String} path - 页面路径或别名
* @returns {Promise}
*
* @example
* Navigation.preload('/order-detail')
*/
preload(path) {
const url = resolveAlias(path)
// #ifdef APP-PLUS
return new Promise((resolve, reject) => {
uni.preloadPage({
url,
success: resolve,
fail: reject
})
})
// #endif
// #ifndef APP-PLUS
return Promise.resolve()
// #endif
},
/**
* 获取当前页面栈
* @returns {Array} 页面栈
*/
getPages() {
return getCurrentPages()
},
/**
* 获取当前页面路径
* @returns {String} 当前页面路径
*/
getCurrentPath() {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
return currentPage ? `/${currentPage.route}` : ''
},
/**
* 获取上一页面路径
* @returns {String|null} 上一页面路径
*/
getPrevPath() {
const pages = getCurrentPages()
if (pages.length < 2) return null
const prevPage = pages[pages.length - 2]
return prevPage ? `/${prevPage.route}` : null
},
/**
* 判断是否可以返回
* @returns {Boolean}
*/
canBack() {
const pages = getCurrentPages()
return pages.length > 1
},
/**
* 解析URL参数
* @param {String} url - URL字符串
* @returns {Object} 参数对象
*/
parseQuery(url) {
const query = {}
const queryString = url.split('?')[1]
if (queryString) {
queryString.split('&').forEach(item => {
const [key, value] = item.split('=')
query[key] = decodeURIComponent(value)
})
}
return query
}
}
/**
* 路由拦截器
* 可用于登录验证、权限检查等
*/
export class RouteInterceptor {
constructor() {
this.beforeEachHooks = []
this.afterEachHooks = []
}
/**
* 注册全局前置守卫
* @param {Function} hook - (to, from, next) => {}
*/
beforeEach(hook) {
this.beforeEachHooks.push(hook)
}
/**
* 注册全局后置守卫
* @param {Function} hook - (to, from) => {}
*/
afterEach(hook) {
this.afterEachHooks.push(hook)
}
/**
* 执行前置守卫
* @param {String} to - 目标路径
* @param {String} from - 来源路径
* @returns {Promise<Boolean>}
*/
async runBeforeHooks(to, from) {
for (const hook of this.beforeEachHooks) {
const result = await new Promise((resolve) => {
hook(to, from, (next) => {
resolve(next !== false)
})
})
if (!result) return false
}
return true
}
/**
* 执行后置守卫
* @param {String} to - 目标路径
* @param {String} from - 来源路径
*/
runAfterHooks(to, from) {
this.afterEachHooks.forEach(hook => hook(to, from))
}
}
// 创建全局路由拦截器实例
export const router = new RouteInterceptor()
// 导出默认对象
export default {
Navigation,
router,
routeAlias,
resolveAlias,
buildUrl
}

View File

@@ -0,0 +1,254 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
/// null = 未请求1 = 已允许0 = 拒绝|受限, 2 = 系统未开启
var isIOS
function album() {
var result = 0;
var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
var authStatus = PHPhotoLibrary.authorizationStatus();
if (authStatus === 0) {
result = null;
} else if (authStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(PHPhotoLibrary);
return result;
}
function camera() {
var result = 0;
var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
if (authStatus === 0) {
result = null;
} else if (authStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(AVCaptureDevice);
return result;
}
function location() {
var result = 0;
var cllocationManger = plus.ios.import("CLLocationManager");
var enable = cllocationManger.locationServicesEnabled();
var status = cllocationManger.authorizationStatus();
if (!enable) {
result = 2;
} else if (status === 0) {
result = null;
} else if (status === 3 || status === 4) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(cllocationManger);
return result;
}
function push() {
var result = 0;
var UIApplication = plus.ios.import("UIApplication");
var app = UIApplication.sharedApplication();
var enabledTypes = 0;
if (app.currentUserNotificationSettings) {
var settings = app.currentUserNotificationSettings();
enabledTypes = settings.plusGetAttribute("types");
if (enabledTypes == 0) {
result = 0;
console.log("推送权限没有开启");
} else {
result = 1;
console.log("已经开启推送功能!")
}
plus.ios.deleteObject(settings);
} else {
enabledTypes = app.enabledRemoteNotificationTypes();
if (enabledTypes == 0) {
result = 3;
console.log("推送权限没有开启!");
} else {
result = 4;
console.log("已经开启推送功能!")
}
}
plus.ios.deleteObject(app);
plus.ios.deleteObject(UIApplication);
return result;
}
function contact() {
var result = 0;
var CNContactStore = plus.ios.import("CNContactStore");
var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
if (cnAuthStatus === 0) {
result = null;
} else if (cnAuthStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(CNContactStore);
return result;
}
function record() {
var result = null;
var avaudiosession = plus.ios.import("AVAudioSession");
var avaudio = avaudiosession.sharedInstance();
var status = avaudio.recordPermission();
console.log("permissionStatus:" + status);
if (status === 1970168948) {
result = null;
} else if (status === 1735552628) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(avaudiosession);
return result;
}
function calendar() {
var result = null;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
if (ekAuthStatus == 3) {
result = 1;
console.log("日历权限已经开启");
} else {
console.log("日历权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return result;
}
function memo() {
var result = null;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
if (ekAuthStatus == 3) {
result = 1;
console.log("备忘录权限已经开启");
} else {
console.log("备忘录权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return result;
}
function requestIOS(permissionID) {
return new Promise((resolve, reject) => {
switch (permissionID) {
case "push":
resolve(push());
break;
case "location":
resolve(location());
break;
case "record":
resolve(record());
break;
case "camera":
resolve(camera());
break;
case "album":
resolve(album());
break;
case "contact":
resolve(contact());
break;
case "calendar":
resolve(calendar());
break;
case "memo":
resolve(memo());
break;
default:
resolve(0);
break;
}
});
}
function requestAndroid(permissionID) {
return new Promise((resolve, reject) => {
plus.android.requestPermissions(
[permissionID],
function(resultObj) {
var result = 0;
for (var i = 0; i < resultObj.granted.length; i++) {
var grantedPermission = resultObj.granted[i];
console.log('已获取的权限:' + grantedPermission);
result = 1
}
for (var i = 0; i < resultObj.deniedPresent.length; i++) {
var deniedPresentPermission = resultObj.deniedPresent[i];
console.log('拒绝本次申请的权限:' + deniedPresentPermission);
result = 0
}
for (var i = 0; i < resultObj.deniedAlways.length; i++) {
var deniedAlwaysPermission = resultObj.deniedAlways[i];
console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
result = -1
}
resolve(result);
},
function(error) {
console.log('result error: ' + error.message)
resolve({
code: error.code,
message: error.message
});
}
);
});
}
function gotoAppPermissionSetting() {
if (permission.isIOS) {
var UIApplication = plus.ios.import("UIApplication");
var application2 = UIApplication.sharedApplication();
var NSURL2 = plus.ios.import("NSURL");
var setting2 = NSURL2.URLWithString("app-settings:");
application2.openURL(setting2);
plus.ios.deleteObject(setting2);
plus.ios.deleteObject(NSURL2);
plus.ios.deleteObject(application2);
} else {
var Intent = plus.android.importClass("android.content.Intent");
var Settings = plus.android.importClass("android.provider.Settings");
var Uri = plus.android.importClass("android.net.Uri");
var mainActivity = plus.android.runtimeMainActivity();
var intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
intent.setData(uri);
mainActivity.startActivity(intent);
}
}
const permission = {
get isIOS(){
return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios')
},
requestIOS: requestIOS,
requestAndroid: requestAndroid,
gotoAppSetting: gotoAppPermissionSetting
}
module.exports = permission

View File

@@ -0,0 +1,79 @@
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
import {
HTTP_REQUEST_URL,
HEADER,
TOKENNAME,
HEADERPARAMS
} from '@/config/app';
import {
toLogin,
checkLogin
} from '../libs/login';
import store from '../store';
/**
* 发送请求
*/
function baseRequest(url, method, data, {
noAuth = false,
noVerify = false
}, params,prefix) {
let Url = HTTP_REQUEST_URL,header = HEADER
if (params != undefined) {
header = HEADERPARAMS;
}
if (!noAuth) {
//登录过期自动登录
if (!store.state.app.token && !checkLogin()) {
toLogin();
return Promise.reject({
msg: '未登录'
});
}
}
if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
return new Promise((reslove, reject) => {
uni.request({
url: Url + `${prefix?'/api/public/':'/api/front/'}` + url,
method: method || 'GET',
header: header,
data: data || {},
success: (res) => {
if (noVerify)
reslove(res.data, res);
else if (res.data.code == 0 || res.data.code == 200)
reslove(res.data, res);
else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
toLogin();
reject(res.data);
}else if (res.data.code == 500){
reject(res.data.message || res.data.msg || '系统异常');
}else if (res.data.code == 400){
reject(res.data.message || res.data.msg || '参数校验失败');
}else if (res.data.code == 404){
reject(res.data.message || res.data.msg || '没有找到相关数据');
}else if (res.data.code == 403){
reject(res.data.message || res.data.msg || '没有相关权限');
} else
reject(res.data.message || res.data.msg || '系统错误');
},
fail: (msg) => {
reject('请求失败');
}
})
});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
request[method] = (api, data, opt, params,prefix) => baseRequest(api, method, data, opt || {}, params,prefix)
});
export default request;

View File

@@ -0,0 +1,30 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
let app = getApp();
export function setThemeColor(){
switch (app.globalData.theme) {
case 'theme1':
return '#e93323';
break;
case 'theme2':
return '#FE5C2D';
break;
case 'theme3':
return '#42CA4D';
break;
case 'theme4':
return '#1DB0FC';
break;
case 'theme5':
return '#FF448F';
break;
}
}

View File

@@ -0,0 +1,957 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import animationType from '@/utils/animationType.js'
import {
TOKENNAME,
HTTP_REQUEST_URL
} from '../config/app.js';
import store from '../store';
import {
pathToBase64
} from '@/plugin/image-tools/index.js';
import util from 'utils/util'
// #ifdef APP-PLUS
import permision from "./permission.js"
// #endif
export default {
/**
* 链接地址跳转
* @param {Object} url 链接地址
*/
navigateTo(url) {
if (url.indexOf("http") !== -1) {
// #ifdef H5
location.href = url
// #endif
// #ifdef APP-PLUS || MP
uni.navigateTo({
url: '/pages/users/web_page/index?webUel=' + encodeURIComponent(url)
})
// #endif
} else {
if (['/pages/goods_cate/goods_cate', '/pages/order_addcart/order_addcart', '/pages/user/index',
'/pages/discover_index/index', '/pages/index/index'
].indexOf(url) == -1) {
uni.navigateTo({
animationType: animationType.type,
animationDuration: animationType.duration,
url: url
})
} else {
uni.switchTab({
animationType: animationType.type,
animationDuration: animationType.duration,
url: url
})
}
}
},
/**
* 对象转数组
* @param data 对象
* @returns {*[]}
*/
objToArr(data) {
let obj = Object.keys(data).sort();
let m = obj.map(key => data[key]);
return m;
},
/**
* opt object | string
* to_url object | string
* 例:
* this.Tips('/pages/test/test'); 跳转不提示
* this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
* this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
* tab=1 一定时间后跳转至 table上
* tab=2 一定时间后跳转至非 table上
* tab=3 一定时间后返回上页面
* tab=4 关闭所有页面跳转至非table上
* tab=5 关闭当前页面跳转至table上
*/
Tips: function(opt, to_url) {
if (typeof opt == 'string') {
to_url = opt;
opt = {};
}
let title = opt.title || '',
icon = opt.icon || 'none',
endtime = opt.endtime || 2000,
success = opt.success;
if (title) uni.showToast({
title: title,
icon: icon,
duration: endtime,
success
})
if (to_url != undefined) {
if (typeof to_url == 'object') {
let tab = to_url.tab || 1,
url = to_url.url || '';
switch (tab) {
case 1:
//一定时间后跳转至 table
setTimeout(function() {
uni.switchTab({
url: url
})
}, endtime);
break;
case 2:
//跳转至非table页面
setTimeout(function() {
uni.navigateTo({
url: url,
})
}, endtime);
break;
case 3:
//返回上页面
setTimeout(function() {
// #ifndef H5
uni.navigateBack({
delta: parseInt(url),
})
// #endif
// #ifdef H5
history.back();
// #endif
}, endtime);
break;
case 4:
//关闭当前所有页面跳转至非table页面
setTimeout(function() {
uni.reLaunch({
url: url,
})
}, endtime);
break;
case 5:
//关闭当前页面跳转至非table页面
setTimeout(function() {
uni.redirectTo({
url: url,
})
}, endtime);
break;
}
} else if (typeof to_url == 'function') {
setTimeout(function() {
to_url && to_url();
}, endtime);
} else {
//没有提示时跳转不延迟
setTimeout(function() {
uni.navigateTo({
url: to_url,
})
}, title ? endtime : 0);
}
}
},
/**
* 移除数组中的某个数组并组成新的数组返回
* @param array array 需要移除的数组
* @param int index 需要移除的数组的键值
* @param string | int 值
* @return array
*
*/
ArrayRemove: function(array, index, value) {
const valueArray = [];
if (array instanceof Array) {
for (let i = 0; i < array.length; i++) {
if (typeof index == 'number' && array[index] != i) {
valueArray.push(array[i]);
} else if (typeof index == 'string' && array[i][index] != value) {
valueArray.push(array[i]);
}
}
}
return valueArray;
},
/**
* 生成海报获取文字
* @param string text 为传入的文本
* @param int num 为单行显示的字节长度
* @return array
*/
textByteLength: function(text, num) {
let strLength = 0;
let rows = 1;
let str = 0;
let arr = [];
for (let j = 0; j < text.length; j++) {
if (text.charCodeAt(j) > 255) {
strLength += 2;
if (strLength > rows * num) {
strLength++;
arr.push(text.slice(str, j));
str = j;
rows++;
}
} else {
strLength++;
if (strLength > rows * num) {
arr.push(text.slice(str, j));
str = j;
rows++;
}
}
}
arr.push(text.slice(str, text.length));
return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
},
/**
* 获取分享海报
* @param array arr2 海报素材
* @param string store_name 素材文字
* @param string price 价格
* @param string ot_price 原始价格
* @param function successFn 回调函数
*
*
*/
PosterCanvas: function(arr2, store_name, price, ot_price, successFn) {
let that = this;
const ctx = uni.createCanvasContext('firstCanvas');
ctx.clearRect(0, 0, 0, 0);
/**
* 只能获取合法域名下的图片信息,本地调试无法获取
*
*/
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, 750, 1150);
uni.getImageInfo({
src: arr2[0],
success: function(res) {
const WIDTH = res.width;
const HEIGHT = res.height;
// ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
ctx.save();
let r = 110;
let d = r * 2;
let cx = 480;
let cy = 790;
ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
// ctx.clip();
ctx.drawImage(arr2[2], cx, cy, d, d);
ctx.restore();
const CONTENT_ROW_LENGTH = 20;
let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name,
CONTENT_ROW_LENGTH);
if (contentRows > 2) {
contentRows = 2;
let textArray = contentArray.slice(0, 2);
textArray[textArray.length - 1] += '……';
contentArray = textArray;
}
ctx.setTextAlign('left');
ctx.setFontSize(36);
ctx.setFillStyle('#000');
// let contentHh = 36 * 1.5;
let contentHh = 36;
for (let m = 0; m < contentArray.length; m++) {
// ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,750);
if (m) {
ctx.fillText(contentArray[m], 50, 1000 + contentHh * m + 18, 1100);
} else {
ctx.fillText(contentArray[m], 50, 1000 + contentHh * m, 1100);
}
}
ctx.setTextAlign('left')
ctx.setFontSize(72);
ctx.setFillStyle('#DA4F2A');
ctx.fillText('¥' + price, 40, 820 + contentHh);
ctx.setTextAlign('left')
ctx.setFontSize(36);
ctx.setFillStyle('#999');
ctx.fillText('¥' + ot_price, 50, 876 + contentHh);
var underline = function(ctx, text, x, y, size, color, thickness, offset) {
var width = ctx.measureText(text).width;
switch (ctx.textAlign) {
case "center":
x -= (width / 2);
break;
case "right":
x -= width;
break;
}
y += size + offset;
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = thickness;
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.stroke();
}
underline(ctx, '¥' + ot_price, 55, 865, 36, '#999', 2, 0)
ctx.setTextAlign('left')
ctx.setFontSize(28);
ctx.setFillStyle('#999');
ctx.fillText('长按或扫描查看', 490, 1030 + contentHh);
ctx.draw(true, function() {
uni.canvasToTempFilePath({
canvasId: 'firstCanvas',
fileType: 'png',
destWidth: WIDTH,
destHeight: HEIGHT,
success: function(res) {
// uni.hideLoading();
successFn && successFn(res.tempFilePath);
}
})
});
},
fail: function(err) {
console.log('失败', err)
uni.hideLoading();
that.Tips({
title: '无法获取图片信息'
});
}
})
},
/**
* 绘制文字自动换行
* @param array arr2 海报素材
* @param Number x , y 绘制的坐标
* @param Number maxWigth 绘制文字的宽度
* @param Number lineHeight 行高
* @param Number maxRowNum 最大行数
*/
canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
return;
}
// canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
// 字符分隔为数组
var arrText = text.split('');
var line = '';
var rowNum = 1
for (var n = 0; n < arrText.length; n++) {
var testLine = line + arrText[n];
var metrics = canvas.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
if (rowNum >= maxRowNum) {
var arrLine = testLine.split('')
arrLine.splice(-9)
var newTestLine = arrLine.join("")
newTestLine += "..."
canvas.fillText(newTestLine, x, y);
//如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
//canvas.fillStyle = '#2259CA';
//canvas.fillText('扫码查看详情',x + maxWidth-90, y);
return
}
canvas.fillText(line, x, y);
line = arrText[n];
y += lineHeight;
rowNum += 1
} else {
line = testLine;
}
}
canvas.fillText(line, x, y);
},
/**
* 获取活动分享海报
* @param array arr2 海报素材
* @param string storeName 素材文字
* @param string price 价格
* @param string people 人数
* @param string count 剩余人数
* @param function successFn 回调函数
*/
activityCanvas: function(arrImages, storeName, price, people, count, num, successFn) {
let that = this;
let rain = 2;
const context = uni.createCanvasContext('activityCanvas');
context.clearRect(0, 0, 0, 0);
/**
* 只能获取合法域名下的图片信息,本地调试无法获取
*
*/
context.fillStyle = '#fff';
context.fillRect(0, 0, 594, 850);
uni.getImageInfo({
src: arrImages[0],
success: function(res) {
context.drawImage(arrImages[0], 0, 0, 594, 850);
context.setFontSize(14 * rain);
context.setFillStyle('#333333');
that.canvasWraptitleText(context, storeName, 110 * rain, 110 * rain, 230 * rain, 30 *
rain, 1)
context.drawImage(arrImages[2], 68 * rain, 194 * rain, 160 * rain, 160 * rain);
context.save();
context.setFontSize(14 * rain);
context.setFillStyle('#fc4141');
context.fillText('¥', 157 * rain, 145 * rain);
context.setFontSize(24 * rain);
context.setFillStyle('#fc4141');
context.fillText(price, 170 * rain, 145 * rain);
context.setFontSize(10 * rain);
context.setFillStyle('#fff');
context.fillText(people, 118 * rain, 143 * rain);
context.setFontSize(12 * rain);
context.setFillStyle('#666666');
context.setTextAlign('center');
context.fillText(count, (167 - num) * rain, 166 * rain);
that.handleBorderRect(context, 27 * rain, 94 * rain, 75 * rain, 75 * rain, 6 * rain);
context.clip();
context.drawImage(arrImages[1], 27 * rain, 94 * rain, 75 * rain, 75 * rain);
context.draw(true, function() {
uni.canvasToTempFilePath({
canvasId: 'activityCanvas',
fileType: 'png',
destWidth: 594,
destHeight: 850,
success: function(res) {
// uni.hideLoading();
successFn && successFn(res.tempFilePath);
}
})
});
},
fail: function(err) {
console.log('失败', err)
uni.hideLoading();
that.Tips({
title: '无法获取图片信息'
});
}
})
},
/**
* 图片圆角设置
* @param string x x轴位置
* @param string y y轴位置
* @param string w 图片宽
* @param string y 图片高
* @param string r 圆角值
*/
handleBorderRect(ctx, x, y, w, h, r) {
ctx.beginPath();
// 左上角
ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.lineTo(x + w, y + r);
// 右上角
ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
ctx.lineTo(x + w, y + h - r);
ctx.lineTo(x + w - r, y + h);
// 右下角
ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
ctx.lineTo(x + r, y + h);
ctx.lineTo(x, y + h - r);
// 左下角
ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
ctx.lineTo(x, y + r);
ctx.lineTo(x + r, y);
ctx.fill();
ctx.closePath();
},
/**
* 小程序头像获取上传
* @param uploadUrl 上传接口地址
* @param filePath 上传文件路径
* @param successCallback success回调
* @param errorCallback err回调
*/
uploadImgs(filePath, opt, successCallback, errorCallback) {
let that = this;
if (typeof opt === 'string') {
let url = opt;
opt = {};
opt.url = url;
}
let count = opt.count || 1,
sizeType = opt.sizeType || ['compressed'],
sourceType = opt.sourceType || ['album', 'camera'],
is_load = opt.is_load || true,
uploadUrl = opt.url || '',
inputName = opt.name || 'pics',
pid = opt.pid,
model = opt.model;
let urlPath = HTTP_REQUEST_URL + '/api/front/upload/image' + "?model=" + model +
"&pid=" + pid
uni.uploadFile({
url: urlPath,
filePath: filePath,
name: inputName,
formData: {
'filename': inputName
},
header: {
// #ifdef MP
"Content-Type": "multipart/form-data",
// #endif
[TOKENNAME]: store.state.app.token
},
success: function(res) {
uni.hideLoading();
if (res.statusCode == 403) {
that.Tips({
title: res.data
});
} else {
let data = res.data ? JSON.parse(res.data) : {};
if (data.code == 200) {
successCallback && successCallback(data)
} else {
errorCallback && errorCallback(data);
that.Tips({
title: data.message
});
}
}
},
fail: function(res) {
console.log('res', res)
uni.hideLoading();
that.Tips({
title: '上传图片失败'
});
}
})
},
/*
* 单图上传
* @param object opt
* @param callable successCallback 成功执行方法 data
* @param callable errorCallback 失败执行方法
*/
uploadImageOne: function(opt, successCallback, errorCallback) {
let that = this;
if (typeof opt === 'string') {
let url = opt;
opt = {};
opt.url = url;
}
let count = opt.count || 1,
sizeType = opt.sizeType || ['compressed'],
sourceType = opt.sourceType || ['album', 'camera'],
is_load = opt.is_load || true,
uploadUrl = opt.url || '',
inputName = opt.name || 'pics',
pid = opt.pid,
model = opt.model;
uni.chooseImage({
count: count, //最多可以选择的图片总数
sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
//启动上传等待中...
uni.showLoading({
title: '图片上传中',
});
let urlPath = HTTP_REQUEST_URL + '/api/front/upload/image' + "?model=" + model +
"&pid=" + pid
let localPath = res.tempFilePaths[0];
uni.uploadFile({
url: urlPath,
filePath: localPath,
name: inputName,
header: {
// #ifdef MP
"Content-Type": "multipart/form-data",
// #endif
[TOKENNAME]: store.state.app.token
},
success: function(res) {
uni.hideLoading();
if (res.statusCode == 403) {
that.Tips({
title: res.data
});
} else {
let data = res.data ? JSON.parse(res.data) : {};
if (data.code == 200) {
data.data.localPath = localPath;
successCallback && successCallback(data)
} else {
errorCallback && errorCallback(data);
that.Tips({
title: data.message
});
}
}
},
fail: function(res) {
uni.hideLoading();
that.Tips({
title: '上传图片失败'
});
}
})
},
fail: function(err) {
that.Tips({
title: err.errMsg
});
console.log('选择图片失败:', err);
}
})
},
/**
* 处理服务器扫码带进来的参数
* @param string param 扫码携带参数
* @param string k 整体分割符 默认为:&
* @param string p 单个分隔符 默认为:=
* @return object
*
*/
// #ifdef MP
getUrlParams: function(param, k, p) {
if (typeof param != 'string') return {};
k = k ? k : '&'; //整体参数分隔符
p = p ? p : '='; //单个参数分隔符
var value = {};
if (param.indexOf(k) !== -1) {
param = param.split(k);
for (var val in param) {
if (param[val].indexOf(p) !== -1) {
var item = param[val].split(p);
value[item[0]] = item[1];
}
}
} else if (param.indexOf(p) !== -1) {
var item = param.split(p);
value[item[0]] = item[1];
} else {
return param;
}
return value;
},
/**根据格式组装公共参数
* @param {Object} value
*/
formatMpQrCodeData(value) {
let values = value.split(',');
let result = {};
if (values.length === 2) {
let v1 = values[0].split(":");
if (v1[0] === 'pid') {
result.spread = v1[1];
} else {
result.id = v1[1];
}
let v2 = values[1].split(":");
if (v2[0] === 'pid') {
result.spread = v2[1];
} else {
result.id = v2[1];
}
} else {
result.spread = values[0].split(":")[1];
}
return result;
},
// #endif
/*
* 合并数组
*/
SplitArray(list, sp) {
if (typeof list != 'object') return [];
if (sp === undefined) sp = [];
for (var i = 0; i < list.length; i++) {
sp.push(list[i]);
}
return sp;
},
trim(str) {
return String.prototype.trim.call(str);
},
$h: {
//除法函数,用来得到精确的除法结果
//说明javascript的除法结果会有误差在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用:$h.Div(arg1,arg2)
//返回值arg1除以arg2的精确结果
Div: function(arg1, arg2) {
arg1 = parseFloat(arg1);
arg2 = parseFloat(arg2);
var t1 = 0,
t2 = 0,
r1, r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
},
//加法函数,用来得到精确的加法结果
//说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
//调用:$h.Add(arg1,arg2)
//返回值arg1加上arg2的精确结果
Add: function(arg1, arg2) {
arg2 = parseFloat(arg2);
var r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(100, Math.max(r1, r2));
return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
},
//减法函数,用来得到精确的减法结果
//说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
//调用:$h.Sub(arg1,arg2)
//返回值arg1减去arg2的精确结果
Sub: function(arg1, arg2) {
arg1 = parseFloat(arg1);
arg2 = parseFloat(arg2);
var r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2));
//动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
},
//乘法函数,用来得到精确的乘法结果
//说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用:$h.Mul(arg1,arg2)
//返回值arg1乘以arg2的精确结果
Mul: function(arg1, arg2) {
arg1 = parseFloat(arg1);
arg2 = parseFloat(arg2);
var m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) {}
try {
m += s2.split(".")[1].length
} catch (e) {}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
},
},
// 获取地理位置;
$L: {
getLocation() {
return new Promise(async (resolve, reject) => {
// #ifdef APP-PLUS
let status = await this.checkPermission();
if (status !== 1) {
uni.removeStorageSync('user_latitude');
uni.removeStorageSync('user_longitude');
resolve(status);
return;
}
// #endif
// #ifdef MP
let status = await this.getSetting();
if (status === 2) {
uni.removeStorageSync('user_latitude');
uni.removeStorageSync('user_longitude');
this.Tips({
title: '获取当前定位遇到困难,如需定位请开启权限'
});
//this.openSetting();
resolve(status);
return;
}
// #endif
let Location = await this.doGetLocation();
resolve(Location);
});
},
doGetLocation() {
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'wgs84',
// altitude: true,
// geocode: true,
success: (res) => {
uni.setStorageSync('user_latitude', res.latitude);
uni.setStorageSync('user_longitude', res.longitude);
resolve(res);
},
complete: (res) => {
uni.setStorageSync('user_latitude', res.latitude);
uni.setStorageSync('user_longitude', res.longitude);
resolve(res);
},
fail: (err) => {
uni.removeStorageSync('user_latitude');
uni.removeStorageSync('user_longitude');
reject(err);
// #ifdef MP-BAIDU
if (err.errCode === 202 || err.errCode ===
10003) { // 202模拟器 10003真机 user deny
this.openSetting();
}
// #endif
// #ifndef MP-BAIDU
if (err.errMsg.indexOf("auth deny") >= 0) {
uni.showToast({
title: '访问位置被拒绝',
icon: 'none',
duration: 2000
});
} else {
uni.showToast({
title: err.errMsg,
icon: 'none',
duration: 2000
});
}
// #endif
}
})
});
},
getSetting: function() {
return new Promise((resolve, reject) => {
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] === undefined) {
resolve(0);
return;
}
if (res.authSetting['scope.userLocation']) {
resolve(1);
} else {
resolve(2);
}
}
});
});
},
/**
* 开启权限提示
*/
openSetting: function() {
uni.openSetting({
success: (res) => {
if (res.authSetting && res.authSetting['scope.userLocation']) {
this.doGetLocation();
}
},
fail: (err) => {}
})
},
async checkPermission() {
let status = permision.isIOS ? await permision.requestIOS('location') :
await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
let pages = getCurrentPages();
let prePage = pages[pages.length - 1].route;
if (status === null || status === 1) {
status = 1;
} else if (status === 2) {
if (prePage === 'pages/users/user_address/index')
uni.showModal({
content: "系统定位已关闭",
confirmText: "确定",
showCancel: false,
success: function(res) {}
})
} else if (status.code) {
if (prePage === 'pages/users/user_address/index')
uni.showModal({
content: status.message
})
} else {
if (prePage === 'pages/users/user_address/index')
uni.showModal({
content: "需要定位权限",
confirmText: "设置",
success: function(res) {
if (res.confirm) {
permision.gotoAppSetting();
}
}
})
}
return status;
},
},
toStringValue: function(obj) {
if (obj instanceof Array) {
var arr = [];
for (var i = 0; i < obj.length; i++) {
arr[i] = toStringValue(obj[i]);
}
return arr;
} else if (typeof obj == 'object') {
for (var p in obj) {
obj[p] = toStringValue(obj[p]);
}
} else if (typeof obj == 'number') {
obj = obj + '';
}
return obj;
},
/*
* 替换域名
*/
setDomain: function(url) {
url = url ? url.toString() : '';
if (url.indexOf("https://") > -1) return url;
else return url.replace('http://', 'https://');
},
/**
* 姓名除了姓显示其他
*/
formatName: function(str) {
return str.substr(0, 1) + new Array(str.length).join('*');
}
}

View File

@@ -0,0 +1,73 @@
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
/**
* 验证小数点后两位及多个小数
* money 金额
*/
export function isMoney(money) {
var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
if (reg.test(money)) {
return true
} else {
return false
}
}
/**
* 验证手机号码
* money 金额
*/
export function checkPhone(phone) {
var reg = /^1(3|4|5|6|7|8|9)\d{9}$/
if (reg.test(phone)) {
return true
} else {
return false
}
}
/**
* 函数防抖 (只执行最后一次点击)
* @param fn
* @param delay
* @returns {Function}
* @constructor
*/
export const Debounce = (fn, t) => {
const delay = t || 500
let timer
return function() {
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
fn.apply(this, args)
}, delay)
}
}
// 节流函数
export function throttle(fn, delay) {
var lastArgs;
var timer;
var delay = delay || 200;
return function(...args) {
lastArgs = args;
if(!timer){
timer = setTimeout(()=>{
timer = null;
fn.apply(this, lastArgs);
}, delay);
}
}
}