Commit 69d9b41c authored by xwq's avatar xwq

mini

parent 641364d4
App({
onLaunch(){
const logs=wx.getStorageSync('logs')||{}
if(logs){
console.log("---------已登录");
}else{
wx.login({
// timeout: 0,
success:(res)=>{
console.log("-----------",res);
// wx.setStorage({
// data: res,
// key: 'userInfo',
// })
}
})
}
}
})
\ No newline at end of file
{"pages": [
"pages/photo/photo",
"pages/takePhoto/takePhoto",
"pages/displayAnswers/displayAnswers",
"pages/index/index",
"pages/logs/logs"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Weixin"
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
\ No newline at end of file
const Jade = {}
Jade.Object = require("./Object")
Jade.UserManager = require("./UserManager")
const getUrl = require("./request").getUrl
Jade.BabyManager = class extends Jade.Object {
static className = "Jade.BabyManager"
static singleton = null
constructor() {
super()
this.grades = [
{name: '选择年级', value: null},
{name: '小班', value: 'kindergarten_junior'},
{name: '中班', value: 'kindergarten_middle'},
{name: '大班', value: 'kindergarten_senior'},
{name: '一年接', value: 'primaryschool_grade1'},
{name: '二年级', value: 'primaryschool_grade2'},
{name: '三年级', value: 'primaryschool_grade3'},
{name: '四年级', value: 'primaryschool_grade4'},
{name: '五年级', value: 'primaryschool_grade5'},
{name: '六年级', value: 'juniormiddleschool_grade6'},
{name: '初一', value: 'juniormiddleschool_grade7'},
{name: '初二', value: 'juniormiddleschool_grade8'},
{name: '初三', value: 'juniormiddleschool_grade9'},
{name: '1周岁内', value: 'grade_one_year'},
{name: '2周岁内', value: 'grade_two_year'},
{name: '3周岁内', value: 'grade_three_year'},
{name: '其他', value: 'grade_other'}
]
}
getClass() {
return Jade.BabyManager
}
static getInstance() {
if (Jade.BabyManager.singleton == null) {
Jade.BabyManager.singleton = new Jade.BabyManager
}
return Jade.BabyManager.singleton
}
getBaby() {
return wx.getStorageSync('baby')
}
setBaby(baby) {
wx.setStorageSync('baby', baby)
}
clearBaby() {
wx.removeStorageSync('baby')
}
getGrades() {
return this.grades || []
}
getGradeNames() {
let names = this.grades.map( (grade) => {
return grade.name
})
return names || []
}
getGradeValues() {
let values = this.grades.map( (grade) => {
return grade.value
})
return values || []
}
getBabyGrade() {
let baby = this.getBaby()
let babyGrade = this.grades.find((grade) => {
if (baby && baby.grade) {
return grade.value === baby.grade
} else {
return false
}
})
return babyGrade
}
getBabyGradeIndex() {
let baby = this.getBaby()
let index = this.grades.findIndex( grade => {
if (baby && baby.grade) {
return grade.value === baby.grade
}
return false
})
return index
}
checkBaby() {
let baby = this.getBaby()
if (baby && baby.state != -1) {
return true
}
return false
}
getBabyRemote(options) {
Jade.UserManager.authRequest({
url: getUrl("babies.json"),
success: (result) => {
// this.clearBaby()
console.log('---------',result.data)
if (typeof result.data === "object") {
this.setBaby(result.data)
} else {
this.setBaby(null)
}
if (options && options.success) {
options.success(result)
}
}
})
}
}
module.exports = Jade.BabyManager
\ No newline at end of file
const Jade = {}
Jade.Page = require("./Page")
Jade.UserManager = require("./UserManager")
Jade.BabyManager = require("./BabyManager")
const getUrl = require("./request").getUrl
Jade.MiniProgramConfig = require('./MiniProgramConfig')
Jade.BasePage = class extends Jade.Page {
static className = "Jade.BasePage"
constructor(options = {}) {
super(options)
}
getClass() {
return Jade.BasePage
}
getCurrentPage() {
return this.getData(["currentPage"])
}
setCurrentPage(currentPage) {
this.setData({
currentPage: currentPage
})
}
onLoad(page, options) {
super.onLoad(page, options)
this.checkWeChatVersion()
}
onShow(page) {
super.onShow(page)
Jade.UserManager.getInstance().executeAfterAuthenticated(() => {
if (this.checkWebView()) {
return
}
const babyManager = Jade.BabyManager.getInstance()
if (!babyManager.checkBaby()) {
wx.navigateTo({ url: '/pages/users/BabyInfo' })
} else{
console.log('congls! you got a baby!')
}
})
let onChangeCallback = this.networkChangeDelegate()
wx.onNetworkStatusChange(onChangeCallback)
wx.getNetworkType({
success: this.getNetworkTypeSuccess()
})
}
networkChangeDelegate() {
var tips = {
'none': '无网络连接',
'unknown': '未知网络',
'wifi': 'WIFI 已连接',
'2g': '当前为2G网络',
'3g': '当前为3G网络',
'4g': '当前为4G网络'
}
var method = function(res) {
if (!res.isConnected) {
wx.showToast({
title: '无网络连接',
icon: 'none',
duration: 1500
})
} else {
if (res.networkType == 'none' || res.networkType == 'unkown') {
wx.showToast({
title: tips[res.networkType],
icon: 'none',
duration: 1500
})
}
}
}
return function delegate() {
method.apply(this, arguments)
}
}
getNetworkTypeSuccess() {
let tips = {
'none': '无网络连接',
'unknown': '未知网络',
}
let method = function(res) {
if (res.networkType == 'none' || res.networkType == 'unkown') {
wx.showToast({
title: tips[res.networkType],
icon: 'none',
duration: 1500
})
}
}
return function() {
method.apply(this, arguments)
}
}
checkWebView() {
return false
}
onUnload() {
super.onUnload()
}
loadBaby() {
const babyManager = Jade.BabyManager.getInstance()
if (!babyManager.checkBaby()) {
babyManager.getBabyRemote()
}
}
checkReview() {
return new Promise(function (resolve, reject) {
let config = Jade.MiniProgramConfig.getInstance()
config.fetchOnlineConfig().then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}
checkBought(callback) {
let um = Jade.UserManager.getInstance()
um.executeAfterAuthenticated(() => {
this.checkReview().then(isReview => {
console.log("isReview", isReview)
if (!isReview) {
this.fetchBuyInfo(callback)
}
})
})
}
checkWeChatVersion() {
var res = wx.getSystemInfoSync()
var value = this.compareVersion(res.version, "6.6.6")
if (res.model.match(/iPad/)) {
value = this.compareVersion(res.version, "6.7.2")
}
if (value == -1) {
wx.showModal({
title: '提示',
content: '请升级到最新微信版本, 否则无法使用该功能' + `${res.model}`,
showCancel: false,
})
}
}
compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
var len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (var i = 0; i < len; i++) {
var num1 = parseInt(v1[i])
var num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
fetchBuyInfo(callback) {
wx.showLoading({
title: '加载中。。。',
mask: true
})
Jade.UserManager.authRequest({
url: getUrl(`users/find_order.json?productable_type=TrainingCamp&productable_id=${1}`),
success: result => {
wx.hideLoading()
console.log(result)
if (result.data.is_bought && result.data.has_address) {
var userManager = Jade.UserManager.getInstance()
var currentUser = userManager.getUser()
currentUser.isBought = result.data.is_bought
userManager.setUser(currentUser)
callback(result)
} else {
let params = {
path: '/bargain_activities',
queryParams: {
id: 2,
}
}
let paramsString = JSON.stringify(params)
console.log(paramsString)
wx.redirectTo({
url: `/pages/webView/webView?url=${paramsString}`
})
}
},
fail: err => {
console.log(err)
wx.hideLoading()
wx.showToast({
title: err.errMsg,
duration: 2000,
icon: 'none'
})
callback(err)
}
})
}
}
module.exports = Jade.BasePage
\ No newline at end of file
const Jade = {}
Jade.Context = require("./Context")
Jade.Page = require("./Page")
Jade.Component = class extends Jade.Context {
static componentName = "Jade.Component"
constructor(context) {
super()
this.data = {}
this.components = []
this.context = context
}
getClass() {
return Jade.Component
}
getPage() {
if (this.context instanceof Jade.Page) {
return this.context
} else {
return this.context.getPage()
}
}
isVisible() {
const data = this.getLocalData()
if (data) {
return data["visible"]
}
}
setVisible(visible) {
this.setLocalData({ visible: visible })
}
getComponentDatas() {
const data = this.getLocalData()
if (data) {
return data["componentDatas"]
}
}
setComponentDatas(componentDatas) {
this.setLocalData({
componentDatas: componentDatas
})
}
getComponents() {
return this.components
}
addComponents(...args) {
let componentDatas = this.getComponentDatas() || []
const components = this.getComponents()
args.forEach(e => {
let componentName
if (typeof e === "function") {
e = new e(this)
}
components.push(e)
componentDatas.push({
name: e.getClass().componentName,
data: e.getLocalData()
})
})
this.setComponentDatas(componentDatas)
}
static registerEventHandlers(component, eventHandlers) {
const prefix = component.getEventHandlerPrefix()
const handlers = {}
Object.keys(eventHandlers).forEach(k => {
let name = `${prefix}${k}`
handlers[name] = eventHandlers[k]
})
component.registerEventHandlers(handlers)
}
registerEventHandlers(eventHandlers) {
this.context.registerEventHandlers(eventHandlers)
}
getEventHandlerPrefix() {
return `${this.getClass().componentName}_`
}
getCurrentScope() {
return this.getClass().componentName
}
getLocalData() {
return this.data
}
setLocalData(data, withScope = true) {
this.setData(data, withScope)
}
getData(scopes = []) {
scopes.push(this.getCurrentScope())
return this.context.getData(scopes)
}
setData(data, withScope = true) {
if (typeof data === "object") {
Object.keys(data).forEach(k => {
this.data[k] = data[k]
})
}
if (withScope) {
const o = {}
o[this.getCurrentScope()] = this.data
this.context.setData(o)
} else {
this.context.setData(this.data)
}
}
onLoad(options) {
const components = this.getComponents()
if (components) {
components.forEach(c => {
c.onLoad(options)
})
}
}
onReady() {
const components = this.getComponents()
if (components) {
components.forEach(c => {
c.onReady()
})
}
}
onShow() {
const components = this.getComponents()
if (components) {
components.forEach(c => {
c.onShow()
})
}
}
onHide() {
const components = this.getComponents()
if (components) {
components.forEach(c => {
c.onHide()
})
}
}
onUnload() {
this.setVisible(false)
const components = this.getComponents()
if (components) {
components.forEach(c => {
c.onUnload()
})
}
}
}
module.exports = Jade.Component
\ No newline at end of file
const Jade = {}
Jade.Object = require("./Object")
Jade.Context = class extends Jade.Object {
static className = "Jade.Context"
getData(data) {
throw new Error("Child class must implement this method!")
}
setData(data) {
throw new Error("Child class must implement this method!")
}
registerEventHandlers(eventHandlers) {
throw new Error("Child class must implement this method!")
}
}
module.exports = Jade.Context
\ No newline at end of file
const Jade = {}
Jade.Page = require("./Page")
Jade.ListPage = class extends Jade.Page {
static className = "Jade.ListPage"
constructor(options = {}) {
super(options)
this.setHasMore(true)
this.setLoadingMore(false)
this.setCurrentPage(0)
}
getClass() {
return Jade.ListPage
}
getCurrentPage() {
return this.getData(["currentPage"])
}
setCurrentPage(currentPage) {
this.setData({
currentPage: currentPage
})
}
isHasMore() {
return this.getData(["hasMore"])
}
setHasMore(hasMore) {
this.setData({
hasMore: hasMore
})
}
isLoadingMore() {
return this.getData(["loadingMore"])
}
setLoadingMore(loadingMore) {
this.setData({
loadingMore: loadingMore
})
}
loadMore() {
throw new Error("child class must implement this method")
}
onLoad(page, options) {
super.onLoad(page, options)
}
onUnload() {
super.onUnload()
}
onReachBottom() {
super.onReachBottom()
if (this.isHasMore() && !this.isLoadingMore()) {
this.loadMore()
}
}
}
module.exports = Jade.ListPage
\ No newline at end of file
const Jade = {}
Jade.Object = require('./Object')
const request = require('./request')
Jade.MiniProgramConfig = class extends Jade.Object {
static className = 'MiniProgramConfig'
static singleton = null
constructor() {
super()
}
static version() {
return '1.5.1'
}
getClass() {
return Jade.MiniProgramConfig
}
static getInstance() {
if (Jade.MiniProgramConfig.singleton == null) {
Jade.MiniProgramConfig.singleton = new Jade.MiniProgramConfig
}
return Jade.MiniProgramConfig.singleton
}
fetchOnlineConfig() {
let self = this
return new Promise(function(resolve, reject) {
const key = ["miniProgramReviewVersion", "miniProgramOnlineVersion"].join(',')
console.log(key)
request.XYRequest({
url: request.getUrlAbs(`/api/system_configs.json?config_key=${key}`)
}).then(res => {
var config = {}
res.data.forEach((element, index) => {
config[element['config_key']] = element['config_value']
})
self.setConfig(config)
resolve(self.isReview())
}).catch(err => {
reject(err)
})
})
}
setConfig(config) {
wx.setStorageSync('config', config)
}
getConfig() {
return wx.getStorageSync('config')
}
isReview() {
return Jade.MiniProgramConfig.version() === this.getConfig().miniProgramReviewVersion
}
}
module.exports = Jade.MiniProgramConfig
\ No newline at end of file
const Jade = {}
Jade.Object = class {
static className = "Jade.Object"
getClass() {
return Jade.Object
}
debug(msg) {
this.info(msg)
}
info(msg) {
console.log(`${this.getClass().className}: ${msg}`)
}
warn(msg) {
console.warn(`${this.getClass().className}: ${msg}`)
}
error(msg) {
console.error(`${this.getClass().className}: ${msg}`)
}
}
module.exports = Jade.Object
\ No newline at end of file
const Jade = {}
Jade.Context = require("./Context")
Jade.Page = class extends Jade.Context {
static className = "Jade.Page"
static PAGE_OK = "ok"
static PAGE_LOADING = "loading"
static PAGE_ERROR = "error"
constructor(options = {}) {
super()
this.data = options.data || {}
this.callbacks = {}
if (options.callbacks) {
this.addCallbacks(options.callbacks)
}
this.eventHandlers = {}
if (options.eventHandlers) {
this.addEventHandlers(options.eventHandlers)
}
this.extraBindings = {}
if (options.extraBindings) {
this.addExtraBindings(options.extraBindings)
}
this.components = []
}
getClass() {
return Jade.Page
}
addCallbacks(callbacks) {
Object.keys(callbacks).forEach(name => {
this.callbacks[name] = callbacks[name].bind(this)
})
}
addEventHandlers(eventHandlers) {
Object.keys(eventHandlers).forEach(name => {
this.eventHandlers[name] = eventHandlers[name].bind(this)
})
}
addExtraBindings(extraBindings) {
Object.keys(extraBindings).forEach(name => {
this.extraBindings[name] = extraBindings[name].bind(this)
})
}
getPageState() {
return this.getData(["pageState"])
}
setPageState(pageState) {
this.setData({
pageState: pageState
})
}
getData(scopes = []) {
var data = null
if (this.page) {
data = this.page.data
let i = scopes.length - 1
while (i >= 0) {
let scope = scopes[i]
if (typeof data[scope] === "undefined") {
data = null
break
}
data = data[scope]
i -= 1
}
}
return data
}
setData(data) {
if (typeof data !== "object") {
return
}
if (this.page) {
this.page.setData(data)
} else {
// TODO Should we need deep copy?
Object.keys(data).forEach(k => {
this.data[k] = data[k]
})
}
}
registerEventHandlers(handlers) {
Object.keys(handlers).forEach(k => {
if (typeof this.eventHandlers[k] === "undefined") {
this.eventHandlers[k] = handlers[k]
} else {
console.warn(`${k} has already been defined on page!`)
}
})
}
runCallback(name, ...args) {
if (this.callbacks && this.callbacks[name]) {
this.callbacks[name](...args)
}
}
onLoad(page, options) {
this.page = page
if (options.title) {
wx.setNavigationBarTitle({
title: options.title
})
}
this.setPageState(Jade.Page.PAGE_OK)
this.runCallback("onLoad", options)
this.components.forEach(component => {
component.onLoad(options)
})
}
onReady(page) {
this.components.forEach(component => {
component.onReady()
})
}
onShow(page) {
this.runCallback("onShow")
this.components.forEach(component => {
component.onShow()
})
}
onHide(page) {
this.runCallback("onHide")
this.components.forEach(component => {
component.onHide()
})
}
onUnload() {
this.page = null
this.components.forEach(component => {
component.onUnload()
})
this.runCallback("onUnload")
}
onPullDownRefresh() {
}
onReachBottom() {
}
onShareAppMessage(res) {
}
addComponents(...args) {
args.forEach(e => {
if (typeof e == "function") {
e = new e(this)
}
this.components.push(e)
})
}
create() {
const _this = this
const o = {
/**
* 页面的初始数据
*/
data: _this.data,
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
_this.onLoad(this, options)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
_this.onReady(this)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
_this.onShow(this)
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
_this.onHide(this)
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
_this.onUnload(this)
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
_this.onPullDownRefresh()
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
_this.onReachBottom()
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function (res) {
return _this.onShareAppMessage(res)
}
}
Object.keys(this.eventHandlers).forEach(k => {
o[k] = this.eventHandlers[k]
})
Object.keys(this.extraBindings).forEach(k => {
o[k] = this.extraBindings[k]
})
Page(o)
}
}
module.exports = Jade.Page
\ No newline at end of file
const Jade = {}
Jade.Object = require("./Object")
const request = require("./request")
const retryFetch = require("./request").retryFetch
Jade.UserManager = require("./UserManager")
Jade.UploadFileManager = class extends Jade.Object {
static className = "Jade.UploadFileManager"
static singleton = null
constructor() {
super()
}
getClass() {
return Jade.UploadFileManager
}
static getInstance() {
if (Jade.UploadFileManager.singleton == null) {
Jade.UploadFileManager.singleton = new Jade.UploadFileManager
}
return Jade.UploadFileManager.singleton
}
/**
* params:
* path
* type
* success
*/
uploadFile(params, cancelToast) {
let filePath = params.path
if (typeof fielpath !== "string") {
filePath = filePath[0]
}
if (!cancelToast) {
wx.showLoading({
title: '上传中...',
})
}
var uploadPromise = new Promise(function (resolve, reject) {
Jade.UserManager.authRequest({
url: request.getUrlAbs("/api/qiniu/token.json"),
method: "GET",
data: {
type: params.type
},
success: res => {
wx.uploadFile({
url: 'https://upload.qiniup.com',
filePath: filePath,
name: 'file',
formData: {
token: res.data.token
},
success: res => {
resolve(res)
},
fail: error => {
console.log(error)
reject(error)
},
complete: () => {
wx.hideLoading()
}
})
},
fail: err => {
reject(err)
}
})
})
var fetchUseRetry = retryFetch({times: 3, delay: 300});
function promiseFunc () {
return uploadPromise
}
return fetchUseRetry(promiseFunc)
}
}
module.exports = Jade.UploadFileManager
\ No newline at end of file
const Jade = {}
Jade.Object = require("./Object")
const getUrl = require("./request").getUrl
Jade.UserManager = class extends Jade.Object {
static className = "Jade.UserManager"
static singleton = null
constructor() {
super()
}
getClass() {
return Jade.UserManager
}
static getInstance() {
if (Jade.UserManager.singleton == null) {
Jade.UserManager.singleton = new Jade.UserManager
}
return Jade.UserManager.singleton
}
static onBindPhoneSuccess() {
const um = Jade.UserManager.getInstance()
if (um.onBindPhoneSuccess) {
um.onBindPhoneSuccess()
}
um.onBindPhoneSuccess = undefined
}
getUser() {
return wx.getStorageSync('user')
}
setUser(user) {
wx.setStorageSync('user', user)
}
getToken() {
return wx.getStorageSync('user_token')
}
setToken(token) {
wx.setStorageSync('user_token', token)
}
isAuthenticated() {
return !!this.getToken()
}
checkUser(options) {
if (this.isAuthenticated()) {
if (options && options.success) {
options.success()
}
} else {
this.login(options)
}
}
checkPhone(options) {
const user = this.getUser()
if (user.phone) {
if (options && options.success) {
options.success()
}
} else {
this.onBindPhoneSuccess = () => {
if (options && options.success) {
options.success()
}
}
wx.navigateTo({
url: '/pages/users/BindPhone?callback=UserManager',
})
}
}
checkSession(options) {
wx.checkSession({
success: () => {
if (options && options.success) {
options.success()
}
},
fail: () => {
this.newSession(options)
}
})
}
newSession(options) {
this.login(options)
}
/*
*
* options:
* checkPhone
*/
executeAfterAuthenticated(callback, options = {}) {
let wrapper = () => {
if (options.checkPhone) {
this.checkPhone({
success: callback
})
} else {
callback()
}
}
this.checkUser({
success: wrapper
})
}
login(options) {
wx.login({
success: res => {
var code = res.code
wx.getUserInfo({
withCredentials: true,
success: res => {
console.log('getUserInfo')
wx.request({
url: getUrl("users/sign_in.json"),
method: 'POST',
data: {
code: code,
user_info: res.userInfo,
encrypted_data: res.encryptedData,
iv: res.iv
},
success: res => {
const data = res.data
this.setUser(data)
this.setToken(data.token)
Jade.UserManager.authRequest({
url: getUrl("babies.json"),
success: (result) => {
if (typeof result.data === "object") {
wx.setStorageSync('baby', result.data)
} else {
wx.setStorageSync('baby', null)
}
if (options && options.success) {
options.success(result)
}
},
fail: err => {
if (options && options.success) {
options.success(result)
}
}
})
}
})
},
fail: err => {
var pages = getCurrentPages()
var currentPage = pages[pages.length - 1]
if (currentPage.route == 'pages/study_package_activities/studyPackageActivityList' || currentPage.route == 'pages/webView/webView') {
console.log('authorizeDialog NavigateTo')
wx.navigateTo({
url:`/pages/AuthorizeDialog/AuthorizeDialog?code=${code}&objc=UserManager`
})
} else {
console.log('authorizeDialog redirectTo')
wx.redirectTo({
url:`/pages/AuthorizeDialog/AuthorizeDialog?code=${code}&objc=UserManager`
})
}
}
})
}
})
}
logout(options) {
this.setUser(null)
this.setToken(null)
if (options && options.success) {
options.success()
}
}
setPhone(phone) {
const user = this.getUser()
user.phone = phone
this.setUser(user)
}
getUserRemote(options) {
Jade.UserManager.authRequest({
url: getUrl("users.json"),
success: (result) => {
this.setUser(result.data)
if (options && options.success) {
options.success(result)
}
}
})
}
static authRequest(params) {
var header = params.header
if (!header) {
header = params.header = {}
}
// error!!!
// if (!header["User-Agent"]) {
// header["User-Agent"] = "XinYaWechatMiniProgram"
// }
if (!header["Authorization"]) {
const um = Jade.UserManager.getInstance()
if (um.isAuthenticated()) {
header["Authorization"] = um.getToken()
}
}
wx.request(params)
}
}
module.exports = Jade.UserManager
\ No newline at end of file
const Jade = {}
Jade.UserManager = require("./UserManager")
Jade.checkUser = options => {
Jade.UserManager.getInstance().checkUser(options)
}
module.exports = Jade.checkUser
\ No newline at end of file
const request = require("./request")
const UserManager = require("./UserManager")
const executeAfterAuthenticated = (callback, options) => {
UserManager.getInstance().executeAfterAuthenticated(callback, options)
}
const utils = require("./utils")
// const AudioRecorderManager = require('./AudioRecorderManager')
const Jade = {
// Object: require("./Object"),
// Context: require("./Context"),
// Page: require("./Page"),
// ListPage: require("./ListPage"),
// Component: require("./Component"),
// BasePage: require('./BasePage'),
// UserManager: UserManager,
// executeAfterAuthenticated: executeAfterAuthenticated,
// BabyManager: require("./BabyManager"),
// checkUser: require("./checkUser"),
request: UserManager.authRequest,
// getUrl: request.getUrl,
// getUrlAbs: request.getUrlAbs,
UploadFileManager: require("UploadFileManager"),
// XYDownload: request.XYDownload,
// XYBatchDownload: request.XYBatchDownload,
// XYRequest: request.XYRequest,
// retryFetch: request.retryFetch,
// XYBatchFetch: request.XYBatchFetch,
// XYSequencedBatchFetch: request.XYSequencedBatchFetch,
// MiniProgramConfig: require('./MiniProgramConfig'),
}
Object.keys(utils).forEach(k => {
Jade[k] = utils[k]
})
// Object.keys(AudioRecorderManager).forEach(k => {
// Jade[k] = AudioRecorderManager[k]
// },AudioRecorderManager)
module.exports = {
Jade: Jade
}
\ No newline at end of file
const Jade = {}
Jade.request = params => {
var header = params.header
if (!header) {
header = params.header = {}
}
// error!!!
// if (!header["User-Agent"]) {
// header["User-Agent"] = "XinYaWechatMiniProgram"
// }
wx.request(params)
}
var XYRequest = function (params) {
var promiseRequest = new Promise(function (resolve, reject) {
var header = params.header
if (!header) {
header = {}
params.header = header
}
if (header) {
if (!header["Authorization"]) {
const token = wx.getStorageSync('user_token')
if (token) {
header["Authorization"] = token
}
const baby = wx.getStorageSync('baby')
if (baby) {
header['Baby'] = baby.id
}
}
}
var success = function (res) {
resolve(res)
}
var fail = function (err) {
reject(err)
}
params['success'] = success
params['fail'] = fail
wx.request(params)
});
var fetchUseRetry = retryFetch({times: 2, delay: 300});
function promiseFunc () {
return promiseRequest
}
return fetchUseRetry(promiseFunc)
}
var XYDownload = function(params) {
var fetchUseRetry = retryFetch({times: 2, delay: 300})
function promiseFunc() {
return new Promise(function(resolve, reject) {
var header = params.header
if (!header) {
header = params.header = {}
}
if (header) {
if (!header["Authorization"]) {
const token = wx.getStorageSync('user_token')
if (token) {
header["Authorization"] = token
}
const baby = wx.getStorageSync('baby')
if (baby) {
header['Baby'] = baby.id
}
}
}
var success = function (res) {
resolve(res)
}
var fail = function (err) {
reject(err)
}
params['success'] = success
params['fail'] = fail
wx.downloadFile(params)
})
}
return fetchUseRetry(promiseFunc)
}
var XYBatchDownload = function(paramsArr) {
let PromisedArr = []
paramsArr.forEach(element => {
if (isPromise(element)) {
PromisedArr.push(element)
} else {
PromisedArr.push(XYDownload(element))
}
});
return Promise.all(PromisedArr)
}
// usage:
// var fetchUseRetry = retryFetch({times: 2, delay: 300});
// fetchUseRetry(XYRequest).then(function (data) {
// console.log(data)
// }).catch(function (err) {
// console.log(err);
// });
var retryFetch = function (opts) {
let DRYOptions = Object.assign({
times: 0,
delay: 0
}, opts)
var originalFunc
return function exec(fn) {
if (!originalFunc) originalFunc = fn;
return fn().catch(function (error) {
if (DRYOptions.times-- <= 0) return Promise.reject(error);
return exec(delay);
});
};
//延时处理
function delay() {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(originalFunc());
}, DRYOptions.delay);
})
}
}
//判断是否为promise对象
var isPromise = function (value) {
return value && typeof value.then === "function";
}
//usage:
// one : [{url,data,method},{url,data,method}] output type is an array
// two: [promisedObject,promisedObject,promisedObject] output type is an array
// three: [promisedObject,{url,data,method},promisedObject] output type is an array
var XYBatchFetch = function (paramsArr) {
let PromisedArr = []
paramsArr.forEach(element => {
if (isPromise(element)) {
PromisedArr.push(element)
} else {
PromisedArr.push(XYRequest(element))
}
});
return Promise.all(PromisedArr)
}
// usage: XYSequencedBatchFetch([{url,data,method},{url,data,method}]). the type of output is an array which is related to the sequence of input
var XYSequencedBatchFetch = function (paramsArr) {
function promiseFactory(params) {
if (isPromise(params)) {
return params
} else {
return XYRequest(params)
}
}
function sequencedTask(paramsArr) {
function recordValue(results, value) {
results.push(value)
return results
}
var pushValue = recordValue.bind(null, [])
var promise = Promise.resolve()
paramsArr.forEach((params,index) => {
promise = promise.then(res => {
var promise = promiseFactory(params)
return promise
}).then((res) => {
console.log(res)
return pushValue(res)
})
})
return promise
}
return sequencedTask(paramsArr)
}
const HOST = "https://xinya.me"
const API_URL = HOST + "/mp/"
const getUrl = (relative_path, params = {}) => {
return API_URL + relative_path
}
const getUrlAbs = (abs_path, params = {}) => {
return `${HOST}${abs_path}`
}
module.exports = {
request: Jade.request,
getUrl: getUrl,
getUrlAbs: getUrlAbs,
XYRequest: XYRequest,
retryFetch: retryFetch,
XYBatchFetch: XYBatchFetch,
XYSequencedBatchFetch: XYSequencedBatchFetch,
XYDownload: XYDownload,
XYBatchDownload: XYBatchDownload
}
\ No newline at end of file
function formatDate(date) {
let dayOfBirthEnd = `${date.getFullYear()}-`
let month = date.getMonth() + 1
if (month < 10) {
dayOfBirthEnd += `0${month}-`
} else {
dayOfBirthEnd += `${month}-`
}
let day = date.getDate()
if (day < 10) {
dayOfBirthEnd += `0${day}`
} else {
dayOfBirthEnd += `${day}`
}
return dayOfBirthEnd
}
function formatTime(seconds) {
let m = Math.floor(seconds / 60)
let s = Math.floor(seconds % 60)
return `${m < 10 ? "0" + m : m}:${s < 10 ? "0" + s : s}`
}
function formatMinAndSecond() {
var timeArray = []
for (let k=0; k < 2; k++) {
var array = []
for(let i = 0; i < 61; i++) {
if (k == 0 && i == 0) {
array.push('')
} else if (k == 1 && i == 0) {
array.push('')
} else {
array.push(i)
}
}
timeArray.push(array)
}
return timeArray
}
module.exports = {
formatDate,
formatTime,
formatMinAndSecond
}
\ No newline at end of file
// pages/displayAnswers/displayAnswers.js
import UploadFileManager from "../../jade/UploadFileManager";
Page({
/**
* 页面的初始数据
*/
data: {
},
getImageInfopromised(src) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: src.replace(" ", ""),
success: function (res) {
resolve(res);
},
fail: function (err) {
reject(src);
},
});
}).catch((err) => {
return Promise.reject(err);
});
},
getPhotoBase64: (path) => {
return new Promise((resolve, reject) => {
wx.getFileSystemManager().readFile({
filePath: path, //选择图片返回的相对路径
encoding: "base64", //编码格式
success: (res) => {
//成功的回调
resolve(res.data);
},
fail: (e) => reject(e),
});
});
},
detectAnswer: (tempPath) => {
// tempPath -> url
// console.log("detectAnswer", tempPath);
const ufm = UploadFileManager.getInstance();
return ufm
.uploadFile(
{
path: [tempPath],
type: "",
},
true
)
.then((res) => {
// console.log("detectAnswer", res);
const ret = JSON.parse(wx.getStorageSync("result"));
const baby = wx.getStorageSync("baby");
const exerciseBookId = ret.exerciseBookId;
return {
baby_id: baby.id,
exercise_book_id: exerciseBookId,
photo_id: JSON.parse(res.data).id,
};
})
.then(
(params) =>
new Promise((resolve, reject) => {
wx.request({
url: `https://xinya.me/api/arithmetic_ocr`,
method: "POST",
data: params,
success: (res) => {
resolve(res.data.data);
},
fail: (e) => {
reject(e);
},
});
})
)
.then(
(res) =>
new Promise((resolve, reject) => {
wx.request({
url: "https://ocr.tencentcloudapi.com",
method: "POST",
header: res.headers,
data: res.body,
success: (ocrRes) => {
console.warn("ocrRes.data", ocrRes.data);
if (
ocrRes.data &&
ocrRes.data.Response &&
ocrRes.data.Response.Error
) {
reject(ret.Response.Error);
} else {
resolve({
...ocrRes.data,
exercise_ocr_record_id: res.exercise_ocr_record_id,
});
}
},
reject: (e) => {
reject(e);
},
});
})
);
},
/**
* 生命周期函数--监听页面加载
*/
reTake: (e) => {
wx.navigateBack({
delta: 0,
});
},
confirm: function (e) {
const ret = JSON.parse(wx.getStorageSync("result"));
ret.errors = this.data.errors != null ? this.data.errors : 0;
ret.errorItems = ret.errors;
const r = Object.keys(ret).reduce((acc, key) => {
return acc + key + "=" + ret[key] + "&";
}, "");
// console.log(r);
wx.redirectTo({
url: `/pages/photo/photo`,
});
},
onLoad: function (options) {
// console.log(options.photo);
const context = wx.createCanvasContext("photo_answer");
let radio;
wx.showLoading({
title: "结果加载中",
});
this.getImageInfopromised(options.photo)
.then((resPhoto) => {
// draw用户拍摄的图片
const width = wx.getSystemInfoSync().windowWidth;
const height = Math.ceil((resPhoto.height / resPhoto.width) * width);
radio = (resPhoto.width / width).toFixed(1);
context.drawImage(resPhoto.path, 0, 0, width, height);
context.draw(true);
return resPhoto.path;
})
.then((tempPath) => this.detectAnswer(tempPath))
.then((ret) => {
console.log("ret", ret);
return Promise.all([
this.getImageInfopromised("../../assets/images/correct.png"),
this.getImageInfopromised("../../assets/images/error.png"),
this.getImageInfopromised(
"../../assets/images/error_wrapper.png"
),
])
.then(([correctIcon, errorIcon, errorWrapper]) => {
const corrects = ret.Response.TextDetections.filter((t) => t.Result)
.length;
this.setData({
corrects,
errors: ret.Response.TextDetections.length - corrects,
});
// console.warn("Res sys", radio);
ret.Response.TextDetections.forEach((t, index) => {
if (t.Result) {
context.drawImage(
`/${correctIcon.path}`,
(t.ItemCoord.X + t.ItemCoord.Width) / radio - 10,
t.ItemCoord.Y / radio - 10,
23,
20
);
} else {
context.drawImage(
`/${errorWrapper.path}`,
t.ItemCoord.X / radio,
t.ItemCoord.Y / radio,
t.ItemCoord.Width / radio,
t.ItemCoord.Height / radio
);
context.drawImage(
`/${errorIcon.path}`,
(t.ItemCoord.X + t.ItemCoord.Width) / radio + 4,
t.ItemCoord.Y / radio - 10,
23,
23
);
}
context.draw(true);
});
})
.then(() => ret)
.then(
(ret) =>
new Promise((resolve, reject) =>
setTimeout(() => {
wx.hideLoading();
wx.canvasToTempFilePath({
canvasId: context.canvasId,
success: (pic) => {
const tempFilePath = pic.tempFilePath;
console.log(tempFilePath);
const umf = UploadFileManager.getInstance();
umf
.uploadFile(
{
path: [tempFilePath],
type: "",
},
true
)
.then((res) => {
resolve({
exercise_ocr_result: { Response: ret.Response },
exercise_ocr_record_id: ret.exercise_ocr_record_id,
ocr_photo_id: JSON.parse(res.data).id,
});
})
.catch(reject);
},
fail: (e) => {
console.log(e);
reject(e);
},
});
}, 1000)
)
);
})
.then(
(res) =>
new Promise((resolve, reject) => {
wx.request({
url: "https://xinya.me/api/arithmetic_ocr_result",
method: "POST",
data: res,
success: (res) => {
resolve(res);
},
reject: (e) => {
reject(e);
},
});
})
)
.catch((e) => {
console.error(e);
wx.hideLoading();
wx.showToast({
title: "检查答案出错,请重新拍照检查",
icon: "none",
duration: 4000,
});
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
\ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file
<!--pages/displayAnswers/displayAnswers.wxml-->
<!--pages/calculate_training/displayAnswers.wxml-->
<view style="height: 100vh; width: 100vw">
<canvas canvas-id='photo_answer' style="width:100%;height:calc(100% - 100px)"></canvas>
<view style="width: 100%; height:100px;">
<block wx:if="{{corrects!=null}}">
<view style="padding: 7px; text-align: center; border-bottom: 1px solid #EFEFEF;">
{{corrects}}题正确,<text style="color: red">{{errors}}</text>题存疑
</view>
</block>
<view style="display: flex; justify-content: center; margin: 10px 0">
<view style="padding: 4px 34px;border: 1px solid #FF4466;border-radius: 21px; display: flex; align-items: center;" bindtap="reTake">重拍</view>
<view style="padding: 4px 34px; background: #FF4466;border-radius: 21px; margin-left: 20px; display: flex; align-items: center; color: white" bindtap="confirm">确定</view>
</view>
</view>
</view>
/* pages/displayAnswers/displayAnswers.wxss */
\ No newline at end of file
// index.js
// 获取应用实例
const app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
},
// 事件处理函数
bindViewTap() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res)
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
console.log(e)
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
})
{
"usingComponents": {}
}
\ No newline at end of file
<!--index.wxml-->
<view>
<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<button type="primary" bindtap="takePhoto">拍照</button>
</view>
/**index.wxss**/
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
color: #aaa;
}
.userinfo-avatar {
overflow: hidden;
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.usermotto {
margin-top: 200px;
}
\ No newline at end of file
// logs.js
const util = require('../../utils/util.js')
Page({
data: {
logs: []
},
onLoad() {
this.setData({
logs: (wx.getStorageSync('logs') || []).map(log => {
return {
date: util.formatTime(new Date(log)),
timeStamp: log
}
})
})
}
})
{
"navigationBarTitleText": "查看启动日志",
"usingComponents": {}
}
\ No newline at end of file
<!--logs.wxml-->
<view class="container log-list">
<block wx:for="{{logs}}" wx:key="timeStamp" wx:for-item="log">
<text class="log-item">{{index + 1}}. {{log.date}}</text>
</block>
</view>
.log-list {
display: flex;
flex-direction: column;
padding: 40rpx;
}
.log-item {
margin: 10rpx;
}
// pages/photo/photo.js
Page({
/**
* 页面的初始数据
*/
data: {
},
goIndex(){
wx.navigateTo({
url: '/pages/takePhoto/takePhoto',
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
\ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file
<!--pages/photo/photo.wxml-->
<view class="photp_back">
<!-- <image class="photp_back_img" src="../assets/images/icon_back.png"></image> -->
<view class="photp_camera_view" bindtap="goIndex">
<image class="photp_camera_img" src="../../assets/images/icon_camera.png"></image>
<view class="photo_tilte">拍照检查</view>
</view>
</view>
/* pages/photo/photo.wxss */
.photp_back{
width: 100%vw;
min-height: 100vh;
max-height: 100vh;
/* height: 100%vh; */
position: relative;
background: url("https://upload.fireflybaby.cn/photo/fb5cf071f0ab250a9457ee524d6a8e86.png") 0 0/100% 100% no-repeat;
/* background-size: cover; */
}
.photp_camera_view{
/* margin: auto; */
background: #FFFFFF;
box-shadow: 0px 0px 20px rgba(255, 177, 44, 0.5);
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
padding: 33px 38px;
font-size: 16px;
font-family: PingFang SC;
font-weight: 400;
/* line-height: 22px; */
color: #FFB12C;
text-align: center;
}
.photp_camera_img{
width: 136px;
height: 123px;
/* position: absolute; */
/* width: calc(100%-160px); */
}
.photo_tilte{
margin-top: -12px;
}
\ No newline at end of file
// pages/takePhoto/takePhoto.js
Page({
/**
* 页面的初始数据
*/
data: {
},
takePhoto() {
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'normal',
success: (res) => {
wx.navigateTo({
url: `/pages/displayAnswers/displayAnswers?photo=${res.tempImagePath}`,
})
},
fail: (error) => {
wx.showToast({
title: "如需拍照检查,请允许摄像头授权",
icon: 'none',
duration: 2000
})
}
})
},
error:function(e) {
// wx.getSetting({
// success(res) {
// if (!res.authSetting['scope.camera']) {
// wx.authorize({
// scope: 'scope.camera',
// success :()=> {
// this.takePhoto()
// }
// })
// }
// }
// })
wx.showToast({
title: "摄像头打开错误, 请重启小程序,如需拍照检查,请允许摄像头授权",
icon: 'none',
duration: 5000
})
// this.setData({
// cameraError: "摄像头打开错误, 请重启小程序,如需拍照检查,请允许摄像头授权"
// })
console.log(e.detail)
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
\ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file
<!--pages/takePhoto/takePhoto.wxml-->
<view style="height: 100vh; width: 100%">
<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: calc(100% - 100px); background: black"></camera>
<block wx:if="{{cameraError}}">
<view style="margin-top: 30vh;text-align: center;">{{cameraError}}</view>
</block>
<view bindtap="takePhoto" style="height: 100px; width: 100%; background: black; display: flex; justify-content: center;align-items: center;">
<image src='../../assets/images/take_photo.png' style="width: 70px; height: 70px"></image>
</view>
</view>
/* pages/takePhoto/takePhoto.wxss */
.cameras{
width: 100%;
height: 500px;
min-height: calc(100%vh - 50px);
}
\ No newline at end of file
{
"description": "项目配置文件",
"packOptions": {
"ignore": []
},
"setting": {
"urlCheck": true,
"es6": true,
"enhance": false,
"postcss": true,
"preloadBackgroundData": false,
"minified": true,
"newFeature": false,
"coverView": true,
"nodeModules": false,
"autoAudits": false,
"showShadowRootInWxmlPanel": true,
"scopeDataCheck": false,
"uglifyFileName": false,
"checkInvalidKey": true,
"checkSiteMap": true,
"uploadWithSourceMap": true,
"compileHotReLoad": false,
"useMultiFrameRuntime": true,
"useApiHook": true,
"useApiHostProcess": false,
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
},
"enableEngineNative": false,
"bundle": false,
"useIsolateContext": true,
"useCompilerModule": true,
"userConfirmedUseCompilerModuleSwitch": false,
"userConfirmedBundleSwitch": false,
"packNpmManually": false,
"packNpmRelationList": [],
"minifyWXSS": true
},
"compileType": "miniprogram",
"libVersion": "2.16.1",
"appid": "wx1c51f89fedfbe68d",
"projectname": "xinya_mini",
"debugOptions": {
"hidedInDevtools": []
},
"scripts": {},
"staticServerOptions": {
"baseURL": "",
"servePath": ""
},
"isGameTourist": false,
"condition": {
"search": {
"list": []
},
"conversation": {
"list": []
},
"game": {
"list": []
},
"plugin": {
"list": []
},
"gamePlugin": {
"list": []
},
"miniprogram": {
"list": []
}
}
}
\ No newline at end of file
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}
\ No newline at end of file
const Jade = require("../jade/index").Jade
const getUrl = Jade.getUrl
const getCurrentPage = () => {
const pages = getCurrentPages()
return pages[pages.length - 1]
}
const calculateTrainingStar = function (training) {
var suggestHigh = training.suggest_time_high
var suggestMid = training.suggest_time_mid
var suggestLow = training.suggest_time_low
var questionCount = training.question_count
var exerciseBooks = training.exercise_books
if (exerciseBooks)
var starCounts = []
for (let index = 0; index < exerciseBooks.length; index++) {
const element = exerciseBooks[index];
if (!element) { continue; }
var record = element.record
if (record) {
var spendTime = record.spend_time || 0
var wrongQuestionCount = record.wrong_question_count || 0
starCounts.push(calculateStarCount(questionCount, spendTime, wrongQuestionCount, suggestHigh, suggestMid, suggestLow).starCount)
}
}
var maxStarCount = Math.max(...starCounts)
return maxStarCount
}
const calculateStarCount = function (question_count, spend_time, wrong_question_count, suggest_high, suggest_mid, suggest_low) {
var questionCount = question_count
var suggestHigh = suggest_high * questionCount
var suggestMid = suggest_mid * questionCount
var suggestLow = suggest_low * questionCount
var spendTime = spend_time
var wrongQuestionCount = wrong_question_count
var wrongPer = wrongQuestionCount / questionCount
if (wrongPer > 0.1) {
return { startOne: false, startTwo: false, startThree: false, starCount: 0 }
} else {
var starCount = { startOne: false, startTwo: false, startThree: false }
if (suggestHigh >= spendTime) {
starCount = { startOne: true, startTwo: true, startThree: true, starCount: 3 }
} else if (suggestHigh < spendTime && spendTime <= suggestMid) {
starCount = { startOne: true, startTwo: true, startThree: false, starCount: 2 }
} else if (suggestMid < spendTime && spendTime <= suggestLow) {
starCount = { startOne: true, startTwo: false, startThree: false, starCount: 1 }
} else if (spendTime > suggestLow) {
starCount = { startOne: false, startTwo: false, startThree: false, starCount: 0 }
}
return starCount
}
}
// usage: promisedCanIUseAPI(api, method, param, options) params must in a such sequence
const promisedCanIUseAPI = function (api, method, param, options) {
return new Promise((resolve, reject) => {
if (api && (method === 'return' || 'success' || 'object' || 'callback' || null)) {
if (wx.canIUse) {
resolve(wx.canIUse(`${api}${method ? `.${method}` : ''}${param ? `.${param}` : ''}${options ? `.${options}` : ''}`))
} else {
reject(`cannot use ${api}`)
}
} else {
reject('bad params')
}
})
}
const getSingle = function (fn) {
var result;
return function () {
return result || (result = fn.apply(this, arguments));
}
};
const debounce = function (action, delay = 300, immediate = true) {
var timer = null
return function debouncing() {
var self = this
var callNow = immediate && !timer
clearTimeout(timer)
timer = setTimeout(() => {
timer = null
if (!immediate) {
action.apply(self, arguments)
}
}, delay)
if (callNow) { action.apply(self, arguments); }
}
}
const throttle = function (action, delay = 300) {
var last = null
var timer = null
return function throttling() {
var self = this
if (!last) {
action.apply(self, arguments)
last = Date.now()
} else {
clearTimeout(timer)
timer = setTimeout(() => {
timer = null
if ((Date.now() - last) >= delay) {
last = Date.now()
action.apply(self, arguments)
}
}, Math.max((delay - (Date.now() - last)), 0))
}
}
}
const convertURLToJSON = function (url, params = {}) {
// let urlArray = url.split('/')
let subUrlArray = url.split('?')
let pathname = subUrlArray[0]
let queryParams = {}
subUrlArray[1].split('&').forEach(query => {
queryParams[`${query.split('=')[0]}`] = `${query.split('=')[1]}`
})
let parameters = {
path: pathname,
queryParams: queryParams,
}
let paramsString = JSON.stringify(parameters)
return paramsString
}
// const onMiniProgram = (e, mini_url, params = {}) => {
// let paramsString = convertURLToJSON(mini_url, params)
// const url = `/pages/webView/webView?url=${paramsString}`
// wx.ready(function () {
// wx.miniProgram.navigateTo({ url: url })
// })
// }
// }
module.exports = {
getUrl,
getCurrentPage,
Jade,
calculateTrainingStar,
promisedCanIUseAPI,
getSingle,
debounce,
throttle,
convertURLToJSON
}
const formatTime = date => {
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('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
module.exports = {
formatTime
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment