shop_app/components/common.js

1054 lines
30 KiB
JavaScript
Raw Normal View History

2025-05-08 09:16:37 +08:00
import { ref } from "vue"
import { get, post } from '../api/request.js'
import api from "../api/index.js"
import { Style } from '../utils/list.js'
import { areaList } from './areaList.js'
// 登录
export function login() {
return new Promise((resolve, reject) => {
uni.login({
provider: 'weixin',
success: res => {
let { code } = res
uni.request({
method: 'POST',
url: api.url + '/api/v1/auth/login',
data: {code, from: uni.getStorageSync('fromId') || 0},
header: {
Authorization: uni.getStorageSync('token') || '',
accept: "application/json",
appid: api.appId
},
success: (val) => {
if(!Array.isArray(val.data)) {
let token = val.data.token_type + ' ' + val.data.access_token
uni.setStorageSync('token', token)
uni.setStorageSync('subscribe', val.data.is_subscribe)
uni.setStorageSync('avatar', val.data.avatar)
uni.setStorageSync('nickname', val.data.nickname)
uni.setStorageSync('role', 0)
uni.setStorageSync('login_type', 'mini-app')
uni.setStorageSync('is_vip', val.data.is_vip)
uni.setStorageSync('is_new', val.data.is_new)
uni.setStorageSync('is_authorized', val.data.is_authorized)
uni.setStorageSync('is_default_avatar', val.data.is_default_avatar)
uni.setStorageSync('sessionKey', val.data.session_key)
uni.setStorageSync('saveTime', Date.now()) // 存储时间
uni.setStorageSync('expires_in', val.data.expires_in * 1000) // 失效时间
}
resolve(val.data)
}
})
},
fail(err) {
reject(err)
}
})
})
}
// 获取用户信息
export function getUserInfo() {
return new Promise((resolve, reject) => {
uni.hideLoading();
uni.getUserProfile ({
desc: '展示用户信息',
success: user=> {
post('/api/v1/user', {
nickname: user.userInfo.nickName,
avatar: user.userInfo.avatarUrl,
}, 'PUT').then( res => {
uni.setStorageSync('nickname', user.userInfo.nickName)
uni.setStorageSync('avatar', user.userInfo.avatarUrl)
uni.setStorageSync('is_authorized', 1)
uni.setStorageSync('is_default_avatar', false)
resolve(res)
})
},
fail(err) {
reject(err)
},
complete() {
}
})
})
}
export function getUserPhone(detail) {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '获取中...',
mask: true
})
// 如果有code直接调接口
if(detail.code) {
post('/api/v1/user/phone', { code: detail.code }).then((res) => {
uni.setStorageSync('is_authorized', 1)
uni.hideLoading()
resolve(res)
}).catch((err) => {
reject(err)
})
} else {
// detail.encryptedDatadetail.iv根据code获取sessionkey再根据sessionkey、encryptedData、iv获取手机号
uni.checkSession({
success: function (req) {
post('/api/v1/user/phoneByEncrypted', { session_key: uni.getStorageSync('sessionKey'), encrypted_data: detail.encryptedData, iv: detail.iv }).then((res) => {
uni.setStorageSync('is_authorized', 1)
uni.hideLoading()
resolve(res)
}).catch((err) => {
reject(err)
})
},
fail: async function (error) {
uni.hideLoading()
await login()
getUserPhone(detail)
}
})
}
})
}
// 绑定分享信息
export async function userBind(params) {
let from = params.from || 0,
s = params.s || 0,
u = params.u || 0,
group_id = params.group_id || 0,
company_id = params.company_id || '',
scene = params.scene
let has_sale = uni.getStorageSync('has_sale')
let index = getCurrentPages().length - 1
let link = getCurrentPages()[index].route
if (from > 0 || company_id || !has_sale) {
await post('/api/v1/user/bind', {from, s, u, group_id, scene, company_id, link}).then((res) => {
uni.setStorageSync('has_sale', true)
})
}
}
export async function judgePrivacy() {
return new Promise((resolve, reject) => {
if(uni.getPrivacySetting) {
uni.getPrivacySetting({
success: res => {
console.log("是否需要授权:", res.needAuthorization)
if (res.needAuthorization) {
resolve(true)
} else{
resolve(false)
}
}
})
} else {
// 低版本基础库不支持 wx.getPrivacySetting 接口,隐私接口可以直接调用
resolve(false)
}
})
}
export async function uvRecord(id) {
await get('/api/v1/banner/' + id + '/uv/record').then((res) => {
})
}
// 消息提示框
export function showToast(title = '', icon = 'none') {
uni.showToast({
title,
icon
})
}
export function goodsItem () {
function toGoods (id) {
uni.navigateTo({
url: '/pages/groups/index?id=' + id
})
}
// 商品规格
const showSku = ref(false)
const groupId = ref(0)
const sourceId = ref(0)
const sourceType = ref('normal')
const skuInfo = ref([])
const skuId = ref(0)
const sku = ref({})
const showBtn = ref(true)
async function getGoodsSku (item) {
groupId.value = item.shop_group_goods_id
// 判断用户授权状态
await getgoodsgku(item)
}
// 获取商品规格
async function getgoodsgku (item) {
if (item.specs_type === 1) {
skuInfo.value = await getGoodsSpecs(item.id)
skuInfo.value.shop_group_goods_id = item.pivot.shop_group_goods_id
showSku.value = true
} else if (item.shop_goods_id){
skuInfo.value = await getGoodsSpecs(item.shop_goods_id)
skuId.value = item.shop_goods_sku_id || 0
if (item.goods && item.goods.sku) {
sku.value = {...item.goods.sku, num: item.num, cart_id: item.id || ''}
}
if(item.shop_group_goods_id !=0) {
skuInfo.value.shop_group_goods_id = item.shop_group_goods_id || item.pivot.shop_group_goods_id
} else {
skuInfo.value.shop_group_goods_id = 0
}
showSku.value = true
} else if (item.specs_type === 0) {
if (item.stock > 0 || item.goods.stock > 0) {
await addCart(item)
} else {
showToast('商品库存不足')
return
}
}
}
const skus_1 = ref(false)
async function getGoodsSpecs (id) {
let res = await get(`/api/v1/goods/spec/${id}`)
if(res.data.skus.length == 1) {
skus_1.value = true
}
else {
skus_1.value = false
}
return res.data
}
// 添加到购物车
async function addCart (item) {
let res = await post('/api/v1/carts', {
shop_goods_id: item.id,
shop_goods_sku_id: 0,
num:item.goods.limit_type==1 ? item.goods.start_sale_num : 1,
shop_group_goods_id: item.pivot.shop_group_goods_id,
source_id: sourceId.value,
source_type: sourceType.value,
})
if (res.code === 0) {
showToast('已加入购物车')
getNum()
showBtn.value = true
}
}
let num = ref(uni.getStorageSync('cartNum') * 1)
// 获取购物车数量
async function getNum () {
let res = await get('/api/v1/carts/num')
num.value = Number(res.data.num)
uni.setStorageSync('cartNum', num.value)
}
return {
sourceId,
sourceType,
toGoods,
showSku, getGoodsSku, skuInfo, skuId, sku,skus_1,
addCart,
getNum, num,
showBtn,
getGoodsSpecs
}
}
let isclick = true
// 重新支付
export function payAgain (id, link_id = 0) {
if(isclick){
uni.showLoading({ mask: true, title: '加载中' })
isclick = false
get(`/api/v1/pay/${id}`, { pay_style: 'app_pay' }).then((res) => {
uni.hideLoading()
setTimeout(() => {
isclick = true
}, 1000)
wxPay(res.data, id, 0, false, 0, link_id)
}).catch(() => {
isclick = true
})
}
}
// 微信支付
export function wxPay(paymentData, id, type, flag = false, from = 0, link_id = 0) {
console.log('paymentData', paymentData)
if(paymentData.pay_style == 'normal') { // 普通微信支付
uni.requestPayment({
provider: 'wxpay',
timeStamp: paymentData.timeStamp,
nonceStr: paymentData.nonceStr,
package: paymentData.package,
signType: 'MD5',
paySign: paymentData.paySign,
success: (val) => {
if (id) {
if(link_id) {
uni.redirectTo({
url: '/pages/success/two?id=' + id + '&type=' + type + '&pay_id=' + paymentData.pay_id + '&from=' + from + '&link_id=' + link_id
})
} else {
uni.redirectTo({
url: '/pages/success/index?id=' + id + '&type=' + type + '&pay_id=' + paymentData.pay_id + '&from=' + from
})
}
} else {
showToast('支付成功')
uni.navigateBack({delta:1})
}
},
async fail(err) {
showToast('支付失败')
if(flag){
await get(`/api/v1/order/close/${id}`).then((res) => {
})
}
if (type) {
uni.redirectTo({ url: '/pages/order/list/index' })
}
}
})
} else if(paymentData.pay_style == 'jump_mini_half') { // 半屏支付
uni.openEmbeddedMiniProgram({
appId: paymentData.jump_mini_appid,
path: paymentData.jump_mini_path,
extraData: {
'id': id,
'type': type,
'flag': flag
},
success(rea) {
console.log('success', rea)
let showNum = 0
uni.onAppShow((res) => {
showNum += 1
if(showNum > 1) {
return false
}
if(res.referrerInfo && res.referrerInfo.appId == paymentData.jump_mini_appid) {
uni.offAppShow()
uni.showLoading({
title: '加载中...',
mask: true
})
let i = 0
let interval = setInterval(async() => {
let ress = await get(`/api/v1/pay/check/${paymentData.pay_id}`)
console.log('pay_id:', paymentData.pay_id, 'status:', ress.data.status)
i += 1
if(i == 5 || ress.data.status) {
uni.hideLoading()
console.log('status', ress.data.status)
clearInterval(interval)
if(ress.data.status) {
if (id) {
uni.redirectTo({
url: '/pages/success/index?id=' + id + '&type=' + type + '&pay_id=' + paymentData.pay_id + '&from=' + from
})
} else {
showToast('支付成功')
uni.navigateBack({delta:1})
}
} else {
showToast('支付失败')
if(flag){
await get(`/api/v1/order/close/${id}`).then((req) => {
})
}
if (type) {
uni.redirectTo({ url: '/pages/order/list/index' })
}
}
}
}, 300)
}
})
},
fail(err) {
console.log('err', err)
}
})
} else if(paymentData.pay_style == 'plugin_pay') { // 易宝插件支付-plugin_pay
const plugin = requirePlugin('yeepay-plugin')
plugin.yeepayPlugin({
fee: paymentData.orderAmount * 100, // 金额单位传1就是1分钱
paymentArgs: paymentData,
currencyType: 'CNY' // 货币符号的代码,默认为 CNY
}).then(res => {
if (id) {
uni.redirectTo({
url: '/pages/success/index?id=' + id + '&type=' + type + '&pay_id=' + paymentData.pay_id + '&from=' + from
})
} else {
showToast('支付成功')
uni.navigateBack({delta:1})
}
}).catch(err => {
console.log('支付失败', err)
showToast('支付失败')
if(flag){
get(`/api/v1/order/close/${id}`).then((ress) => {
})
}
if (type) {
uni.redirectTo({ url: '/pages/order/list/index' })
}
})
}
}
/**
* 获取本周本季度本月
*/
var now = new Date() //当前日期
var nowDayOfWeek = now.getDay() //今天本周的第几天
var nowDay = now.getDate() //当前日
var nowMonth = now.getMonth() //当前月
var nowYear = now.getYear() //当前年
nowYear += (nowYear < 2000) ? 1900 : 0
// 获取当前日期前几天的日期
export function getOldDay(str = 'y-m-d h:i:s', day = 0) {
var dd = new Date()
dd.setDate(dd.getDate() - day) //获取AddDayCount天后的日期
return dateTimeStr(str, new Date(dd))
}
// 获取某个时间后几天的时间
export function getRangeTime(date, day) {
let odate = new Date(date.replace(/-/g, '/')).getTime()
odate = odate + (day * 24 * 60 * 60 * 1000)
odate = new Date(odate)
// 当前时间年月日
let month1 = (nowMonth + 1) >= 1 && (nowMonth + 1) <= 9 ? '0' + (nowMonth + 1) : (nowMonth + 1)
let day1 = nowDay >= 1 && nowDay <= 9 ? '0' + nowDay : nowDay
let nowTime = nowYear + '-' + month1 + '-' + day1
// 计算的日期
let month2 = (odate.getMonth() + 1) >= 1 && (odate.getMonth() + 1) <= 9 ? '0' + (odate.getMonth() + 1) : (odate.getMonth() + 1)
let day2 = odate.getDate() >= 1 && odate.getDate() <= 9 ? '0' + odate.getDate() : odate.getDate()
let time = odate.getFullYear() + '-' + month2 + '-' + day2
console.log(nowTime, time)
let timeStr = (odate.getMonth() + 1) + '月' + odate.getDate() + '日'
if(nowTime == time) {
timeStr = '今天'
} else if(getOldDay('y-m-d', -1) == time){
timeStr = '明天'
}
return timeStr
}
// 获取某个时间后几天的时间
// (2023-11-10 12:12:11, 3) => 2023-11-13 12:12:11
export function getNextTime(date, day) {
let odate = new Date(date.replace(/-/g, "/")).getTime()
odate = odate + (day * 24 * 60 * 60 * 1000)
odate = new Date(odate)
// 计算的日期
let year2 = odate.getFullYear()
let month2 = (odate.getMonth()+1) >= 1 && (odate.getMonth()+1) <= 9 ? '0' + (odate.getMonth()+1) : (odate.getMonth()+1)
let day2 = odate.getDate() >= 1 && odate.getDate() <= 9 ? '0' + odate.getDate() : odate.getDate()
let hour = odate.getHours() < 10 ? '0' + odate.getHours() : odate.getHours()
let minute = odate.getMinutes() < 10 ? '0' + odate.getMinutes() : odate.getMinutes() //分
let second = odate.getSeconds() < 10 ? '0' + odate.getSeconds() : odate.getSeconds() //秒
let time = year2 + '-' + month2 + '-' + day2 + ' ' + hour + ':' + minute + ':' + second
return time
}
export function compareDate(date1, date2) {
let str1 = new Date(date1.replace(/-/g, "/")).getTime()
let str2 = new Date(date2.replace(/-/g, "/")).getTime()
return str2 - str1 >= 0
}
// 时间戳转日期
export function dateTimeStr(str = "y-m-d h:i:s", day){
var date = new Date(day),
year = date.getFullYear(), //年
month = date.getMonth() + 1, //月
day = date.getDate(), //日
hour = date.getHours(), //时
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(), //分
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
if(str.indexOf('y') != -1){
str = str.replace('y', year)
}
if(str.indexOf('m') != -1){
str = str.replace('m', month)
}
if(str.indexOf('d') != -1){
str = str.replace('d', day)
}
if(str.indexOf('h') != -1){
str = str.replace('h', hour)
}
if(str.indexOf('i') != -1){
str = str.replace('i', minute)
}
if(str.indexOf('s') != -1){
str = str.replace('s', second)
}
return str
}
// 获得本周的开始日期
export function getWeekStartDate() {
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
return dateTimeStr("y-m-d", weekStartDate)
}
// 获得本月的开始日期
export function getMonthStartDate(){
var monthStartDate = new Date(nowYear, nowMonth, 1)
return dateTimeStr("y-m-d", monthStartDate)
}
// 保存图片到相册
export function saveImg (url, text) {
uni.saveImageToPhotosAlbum({
filePath: url,
success(res) {
showToast(text || '保存成功', 'success')
},
fail(err){
if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
uni.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success() {
// 拉起授权
uni.openSetting({
success(settingdata) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
uni.showModal({
title: '提示',
content: '获取权限成功, 请重新保存图片',
showCancel: false
})
} else {
uni.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false
})
}
},
fail(failData) {
},
complete(finishData) {
}
})
}
})
}
}
})
}
// 图片预览
export async function getImg () {
let imgsArray = [];
let res = await get('/api/v1/user/qrCode')
if (res.code === 0) {
imgsArray.push(res.data.qr_code)
}
uni.previewImage({
urls: imgsArray,
current: 0
})
}
// 批量加购物车
export function adddCartBatch (items) {
const goods = items.map(item => {
return {
shop_goods_id: item.shop_goods_id,
shop_goods_sku_id: item.shop_sku_id,
num: item.number,
shop_group_goods_id: item.shop_group_goods_id,
source_id: 0,
source_type: 'normal'
}
})
post('/api/v1/carts/batch', {goods}).then(res => {
showToast('已添加到购物车')
setTimeout(function() {
uni.switchTab({
url: '/pages/cart/index'
})
}, 1000)
})
}
// 去评论
export function toWrite (id) {
uni.navigateTo({
url: `/pages/order/comment/write?id=${id}`
})
}
// 获取店铺信息
export async function getShopInfo () {
let res = await get('/api/app/shop')
uni.setStorageSync('page_rule', res.data.home_page_rule)
uni.setStorageSync('vip_on', res.data.vip_on)
uni.setStorageSync('shop_id', res.data.id)
uni.setStorageSync('official_link', res.data.official_link)
uni.setStorageSync('vip_price_show', res.data.vip_price_show === 1)
uni.setStorageSync('refund_mode', res.data.refund_mode)
uni.setStorageSync('show_identity', res.data.show_identity)
uni.setStorageSync('vip_detail_on', res.data.vip_detail_on)
uni.setStorageSync('score_on', res.data.score_on)
uni.setStorageSync('score_trade_share', res.data.score_trade_share)
uni.setStorageSync('score_comment', res.data.score_comment)
uni.setStorageSync('score_trade', res.data.score_trade)
uni.setStorageSync('deduct_overtime_ship_on', res.data.deduct_overtime_ship_on)
uni.setStorageSync('img_preview_suffix', res.data.img_preview_suffix)
uni.setStorageSync('rule', res.data.home_special_rule)
uni.setStorageSync('logo', res.data.logo)
uni.setStorageSync('theme_index', res.data.show_style_type || 0)
uni.setStorageSync('theme_color', Style[res.data.show_style_type || 0].color)
uni.setStorageSync('show_explain_video', res.data.show_explain_video)
uni.setStorageSync('user_bg', res.data.user_background_img)
uni.setStorageSync('has_multi_group', res.data.has_multi_group)
uni.setStorageSync('technical_support', res.data.extendInfo ? res.data.extendInfo.technical_support : 0)
uni.setStorageSync('technical_support_title', res.data.extendInfo ? res.data.extendInfo.technical_support_title : '')
return res.data
}
/**
* @desc 格式化日期字符串
* @param { Nubmer} - 时间戳
* @returns { String } 格式化后的日期字符串
*/
export function formatDate(timestamp) {
// 补全为13位
let arrTimestamp = (timestamp + '').split('');
for (let start = 0; start < 13; start++) {
if (!arrTimestamp[start]) {
arrTimestamp[start] = '0';
}
}
timestamp = arrTimestamp.join('') * 1;
let minute = 1000 * 60;
let hour = minute * 60;
let day = hour * 24;
let month = day * 30;
let now = new Date().getTime();
let diffValue = now - timestamp;
// 如果本地时间反而小于变量时间
if (diffValue < 0) {
return '不久前';
}
// 计算差异时间的量级
let monthC = diffValue / month;
let weekC = diffValue / (7 * day);
let dayC = diffValue / day;
let hourC = diffValue / hour;
let minC = diffValue / minute;
// 数值补0方法
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
// 使用
if (monthC > 4) {
// 超过1年直接显示年月日
return (function () {
let date = new Date(timestamp);
return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
})();
} else if (monthC >= 1) {
return parseInt(monthC) + '月前';
} else if (weekC >= 1) {
return parseInt(weekC) + '周前';
} else if (dayC >= 1) {
return parseInt(dayC) + '天前';
} else if (hourC >= 1) {
return parseInt(hourC) + '小时前';
} else if (minC >= 1) {
return parseInt(minC) + '分钟前';
}
return '刚刚';
}
// 监听网络变化
export function NetWork() {
uni.getNetworkType({
success: (res) => {
if (res.networkType == 'none') {
uni.showToast({
icon: "none",
title: '网络错误,请重试!'
})
}
}
})
// 监听网络状态变化
uni.onNetworkStatusChange((res) => {
if (!res.isConnected) {
uni.showToast({
icon: "none",
title: '网络错误,请重试!'
})
}
})
}
/**
* @desc 封装倒计时组件
* @param endTime 结束时间
* @param type 返回的类型
* @return {*}
*/
export function DownTime( endTime, type) {
let thisEndTime = new Date(endTime) // 获取截
if(type == 3){
var downFn = setInterval(() => {
let newTime = new Date().getTime()//获取当前时间
let backTime = thisEndTime - newTime//计算剩余时间
var d = Math.floor(backTime / (1000 * 60 * 60 * 24)); //计算天数
var h = Math.floor(backTime / (1000 * 60 * 60) % 24); //计算小时数
var m = Math.floor(backTime / (1000 * 60) % 60); //计算分钟数
var s = Math.floor(backTime / 1000 % 60); //计算秒数
return {d: d, h: h, m: m, s: s}
}, 1000)
}else if(type == 1 || type == 2) {
var to = new Date(endTime.replace(/-/g, "/"))
var now = new Date()
var backTime = to.getTime() - now.getTime()
var d = Math.floor(backTime / (1000 * 60 * 60 * 24)) //计算天数
var h = Math.floor(backTime / (1000 * 60 * 60) % 24) //计算小时数
var m = Math.floor(backTime / (1000 * 60) % 60) //计算分钟数
var s = Math.floor(backTime / 1000 % 60); //计算秒数
if( type == 1){
if(d > 0){
return '距结束<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">'+ d + '</span>天'
}else if(h||m||s){
let time1='距结束<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + s + '</span>秒'
let time2='已结束'
return backTime > 0 ? time1 : time2
}else{
return ''
}
}else if(type == 2) {
d = d > 9 ? d : '0' + d
h = h > 9 ? h : '0' + h
m = m > 9 ? m : '0' + m
let time1='距结束<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + d + '</span>天<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分'
if(d == 0) {
time1='距结束<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分'
}
let time2='已结束'
return backTime > 0 ? time1 : time2
}
}
}
export function UpTime( startTime, type) {
let stTime = new Date(startTime.replace(/-/g, "/"))
if(new Date().getTime() - stTime < 0) {
if(type == 3){
setInterval(() => {
let newTime = new Date().getTime()//获取当前时间
let backTime = stTime - newTime//计算剩余时间
var d = Math.floor(backTime / (1000 * 60 * 60 * 24)); //计算天数
var h = Math.floor(backTime / (1000 * 60 * 60) % 24); //计算小时数
var m = Math.floor(backTime / (1000 * 60) % 60); //计算分钟数
var s = Math.floor(backTime / 1000 % 60); //计算秒数
return {d: d, h: h, m: m, s: s}
}, 1000)
}
if(type == 1 || type == 2) {
var to = new Date(startTime.replace(/-/g, "/"))
var now = new Date()
var backTime = to.getTime() - now.getTime()
var d = Math.floor(backTime / (1000 * 60 * 60 * 24)) //计算天数
var h = Math.floor(backTime / (1000 * 60 * 60) % 24) //计算小时数
var m = Math.floor(backTime / (1000 * 60) % 60) //计算分钟数
var s = Math.floor(backTime / 1000 % 60); //计算秒数
if(type == 1){
if(d > 0){
return '距开始<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">'+ d + '</span>天'
}else if(h || m || s){
let time1 = '距开始<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + s + '</span>秒'
return time1
}
} else if(type == 2) {
d = d > 9 ? d : '0' + d
h = h > 9 ? h : '0' + h
m = m > 9 ? m : '0' + m
let time1='距开始<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + d + '</span>天<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分'
if(d == 0) {
time1='距开始<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + h + '</span>时<span style="color:#2C2C2C;font-weight:bold;margin:0 2px;">' + m + '</span>分'
}
let time2='已结束'
return time1
}
}
} else {
return ''
}
}
export function gapTime(startTime) {
let stTime = new Date(startTime.replace(/-/g, "/"))
var to = new Date(startTime.replace(/-/g, "/"))
var now = new Date()
var backTime = to.getTime() - now.getTime()
var d = Math.floor(backTime / (1000 * 60 * 60 * 24)) //计算天数
var h = Math.floor(backTime / (1000 * 60 * 60) % 24) //计算小时数
var m = Math.floor(backTime / (1000 * 60) % 60) //计算分钟数
var s = Math.floor(backTime / 1000 % 60); //计算秒数
if(d > 0){
return d + '天'
} else if(h > 0){
return h + '小时'
} else if(m > 0) {
return m + '分钟'
} else {
return s + '秒'
}
}
export function parseTime(Time) {
let date = Time.split(' ')[0]
let start = Time.split(' ')[1].substr(0, 5)
let today = new Date().setHours(0, 0, 0, 0)
let dayStr = new Date(date.replace(/-/g, "/")).setHours(0, 0, 0, 0)
let dateObj = {
0: '今天',
86400000: '明天',
172800000: '后天'
}
return (dateObj[dayStr - today] || date) + ' ' + start
}
export const writePhotosAlbum = (successFun, failFun) => {
uni.getSetting({
success(res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: function () {
successFun && successFun()
},
fail: function (res) {
uni.hideLoading()
uni.showModal({
title: '提示',
content: "微信授权保存图片,是否重新授权?",
showCancel: true,
cancelText: "否",
confirmText: "是",
success: function (res2) {
if (res2.confirm) {
uni.openSetting({
success: (res3) => {
if (res3.authSetting['scope.writePhotosAlbum']) {
successFun && successFun()
} else {
failFun && failFun()
}
}
})
} else {
failFun && failFun()
}
}
})
}
})
} else {
successFun && successFun()
}
}
})
}
export const getDayDiff = (date1, date2) => {
const oneDay = 1000 * 60 * 60 * 24
const timeDiff = Math.abs(new Date(date1.replace(/-/g, '/')).getTime() - new Date(date2.replace(/-/g, '/')).getTime())
const dayDiff = Math.ceil(timeDiff / oneDay)
let str = dayDiff == 0 ? '当天' : dayDiff + '天后'
return str
}
export const getIntervalDay = (date1, date2) => {
const oneDay = 1000 * 60 * 60 * 24
const timeDiff = Math.abs(new Date(date1.replace(/-/g, '/')).getTime() - new Date(date2.replace(/-/g, '/')).getTime())
const dayDiff = Math.ceil(timeDiff / oneDay)
let flag = dayDiff < 180 ? true : false
return flag
}
export const getAreaCode = (prov_name, city_name, area_name) => {
return new Promise((resolve, reject) => {
let list = []
for(let a = 0; a < areaList.length; a++){
let prov = areaList[a]
if (prov.name == prov_name) {
list.push({ code: prov.id, name: prov_name })
for(let b = 0; b < prov.children.length; b++){
let city = prov.children[b]
if (city.name == city_name) {
list.push({ code: city.id, name: city_name })
for(let c = 0; c < city.children.length; c++){
let area = city.children[c]
if (area.name == area_name) {
list.push({ code: area.id, name: area_name })
break
}
}
break
}
}
break
}
}
resolve(list)
})
}
export const downloadVideo = (url) => {
uni.showLoading({
mask: true,
title: '加载中'
})
uni.downloadFile({
url: url,
success: (res) => {
if (res.statusCode === 200) {
uni.hideLoading()
uni.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
showToast('保存成功')
},
fail: (err) => {
if (err.errMsg === 'saveVideoToPhotosAlbum:fail auth deny') {
uni.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success() {
uni.openSetting({
success(settingdata) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
uni.showModal({
title: '提示',
content: '获取权限成功, 请重新保存图片',
showCancel: false
})
} else {
uni.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false
})
}
},
fail(failData) {
},
complete(finishData) {
}
})
}
})
}
}
})
}
},
fail: (err) => {
uni.hideLoading()
uni.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
export const uniShare = (title, face_img, path) => {
uni.share({
provider: 'weixin',
scene: "WXSceneSession",
type: 5,
title: title,
imageUrl: face_img,
miniProgram: {
id: api.protoId,
path: path,
type: 0,
webUrl: api.webUrl
},
success(res) {
},
fail(err) {
}
})
}
export const toMiniProgram = (path) => {
uni.showModal({
title: '提示',
content: '需要离开商城APP跳转至妙选商城小程序进行后续操作确认跳转吗',
success(res) {
if (res.confirm) {
var pages = getCurrentPages()
var page = pages[pages.length - 1]
var shares = null, sweixin = null
plus.share.getServices(function(s){
shares = {}
for(var i in s){
var t = s[i]
shares[t.id] = t
}
sweixin = shares['weixin']
sweixin.launchMiniProgram({
id: 'gh_ca74730c9f77',
path: path
})
}, function(e) {
console.log("获取分享服务列表失败:" + e.message)
})
}
}
})
}
export const whetherLogin = () => {
let flag = true
let saveTime = uni.getStorageSync('saveTime')
let expires_in = uni.getStorageSync('expires_in')
let token = uni.getStorageSync('token')
if((saveTime && expires_in && Date.now() > saveTime + expires_in) || !expires_in || !saveTime || !token) {
flag = false
}
return flag
}