import wafer from '../lib/wafer2-client-sdk'
import tip from './tip'

// 时间格式化
const formatTime = time => {
time = (time.length == 10) ? parseInt(time) * 1000 : parseInt(time)
var date = new Date(time)
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()

return [year, month, day].map(formatNumber).join('-')
}

// Money格式化
const formatFen2Jiao = fen => {
if (fen) {
return parseFloat(fen / 100, 2)
} else {
return '0.00'
}
}

const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}

const deepClone = obj => {
const _this = this
var temp = null
if (obj && obj instanceof Array) {
temp = []
temp = obj.map(function (item) {
return deepClone(item)
})
} else if (obj && typeof obj === 'object') { // typeof null 的值是 object
temp = {}
for (let item in obj) {
temp[item] = deepClone(obj[item])
}
} else {
temp = obj
}
return temp
}

// 复制粘贴
const clip = (obj) => {
wx.setClipboardData(obj)
}

async function request(options, page, tryout, successCB, failCB) {
const session = wafer.Session.get()
if (tryout === 0) {
return
}
let tryTmp = 0
let result = 0
let failTmp = 0
while (tryTmp++ < tryout && !result) {
if (tryTmp > 2) await sleep(3)

failTmp = await tryRequest(options)

if (failTmp.data && (failTmp.data.code || failTmp.data.code == 0)) {
result = failTmp
}
}
if (result) {
successCB.call(page, result)
} else {
failCB.call(page, failTmp)
}

if (options.tip) {
tip.loaded()
}
}

async function tryRequest(options) {
return new Promise((resolve, reject) => {
if (options.tip) {
tip.loading()
}
wafer.request({
method: options.method || 'GET',
data: options.data || {},
url: options.url,
success: function (res) {
resolve(res)
},
fail: function (err) {
console.log('try err:', err)
if (!err.code) {
resolve(0)
} else {
resolve(err)
console.log('请求失败url', options.url)
console.log('请求失败', err)
}
},
complete: function (res) {
// console.log(res)
}
})
})
}

async function sleep(sec) {
return new Promise(resolve => {
setTimeout(() => {
let tmp = ''
console.log('sleep ' + sec + ' seconds')
resolve(true)
}, sec * 1000)
})
}

function getuuid(u) {
let mydate = new Date()
let uuid = u + mydate.getDay() + mydate.getHours() + mydate.getMinutes() +
mydate.getSeconds() + mydate.getMilliseconds() + Math.round(Math.random() * 10000)
return uuid
}

module.exports = {
formatTime,
deepClone,
formatFen2Jiao,
clip,
request,
getuuid
}
posted on 2018-10-15 16:11  阿梅M  阅读(1077)  评论(0编辑  收藏  举报