订单列表, 详情

This commit is contained in:
Kiyan 2017-05-11 17:38:06 +08:00
parent 573c016ae0
commit 185e822b5d
26 changed files with 1140 additions and 552 deletions

View File

@ -1,14 +1,24 @@
//app.js //app.js
import {getLoginInfo} from './utils/apis' import {
getLoginInfo, getUserAddrs
} from './utils/apis'
import {
getCurrentAddress,
coordFormat
} from './utils/util'
import {
gcj02tobd09
} from './utils/coordtransform'
import distance from './utils/distance'
App({ App({
onLaunch: function () { onLaunch: function () {
//调用API从本地缓存中获取数据 //调用API从本地缓存中获取数据
}, },
getLoginInfo:function(cb){ getLoginInfo: function (cb) {
var that = this var that = this
if (this.globalData.loginInfo){ if (this.globalData.loginInfo) {
cb && cb(this.globalData.loginInfo) cb && cb(this.globalData.loginInfo)
}else{ } else {
//调用登录接口 //调用登录接口
getLoginInfo({ getLoginInfo({
success(data) { success(data) {
@ -24,7 +34,78 @@ App({
} }
this.globalData.loginInfo = loginInfo this.globalData.loginInfo = loginInfo
}, },
globalData:{
loginInfo:null // 获取当前地址
getCurrentAddress(cb) {
var that = this
if (this.globalData.currentAddress) {
return cb && cb(this.globalData.currentAddress)
}
getCurrentAddress(address => {
this.getLoginInfo(loginInfo => {
if (loginInfo.is_login) {
this.findNearbyUserAddr(userAddress => {
if (userAddress) {
address = userAddress
}
address = that.setCurrentAddress(address)
cb(address)
})
} else {
address = that.setCurrentAddress(address)
cb(address)
}
})
})
},
setCurrentAddress(address) {
if(address.addr_id) {
address.title = `${address.addr} ${address.detail}`
address.city = address.city_name
address.district = address.district_name
address.location = {
longitude: address.longitude,
latitude: address.latitude
}
} else {
address.location = coordFormat(address.location)
}
this.globalData.currentAddress = address
return address
},
findNearbyUserAddr(cb, radius = 100) {
radius /= 100
wx.getLocation({
type: 'gcj02',
success: function (res) {
var [lng1, lat1] = gcj02tobd09(res.longitude, res.latitude)
getUserAddrs({
success(addressList) {
for (let i = 0, len = addressList.length; i < len; i++) {
var address = addressList[i]
var {
longitude: lng2,
latitude: lat2
} = address
if (distance(lat1, lng1, lat2, lng2) <= radius) {
return cb(address)
}
}
return cb()
}
})
},
fail(res) {
console.log(res.errMsg)
alert('获取用户地址失败')
}
})
},
globalData: {
loginInfo: null,
currentAddress: null
} }
}) })

View File

@ -1,16 +1,16 @@
{ {
"pages": [ "pages": [
"pages/address/select",
"pages/address/list",
"pages/address/add",
"pages/mine/mine",
"pages/login/login",
"pages/index/index",
"pages/index/address",
"pages/shop/show",
"pages/order/show", "pages/order/show",
"pages/order/quasi",
"pages/order/list", "pages/order/list",
"pages/shop/show",
"pages/mine/mine",
"pages/index/index",
"pages/address/select",
"pages/order/quasi",
"pages/address/list",
"pages/index/address",
"pages/address/add",
"pages/login/login",
"pages/shop/category", "pages/shop/category",
"pages/shop/search" "pages/shop/search"
], ],

View File

@ -14,7 +14,7 @@ Page({
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.id = options.id this.id = options.id
this.callback = options.callback this.callback = options.callback || 'callback'
this.initValidate() this.initValidate()
if (this.id) { if (this.id) {
this.loadData() this.loadData()

View File

@ -3,7 +3,7 @@ import {
getUserAddrs, deleteUserAddr getUserAddrs, deleteUserAddr
} from '../../utils/apis' } from '../../utils/apis'
import { import {
confirm confirm, getPrevPage
} from '../../utils/util' } from '../../utils/util'
Page({ Page({
@ -12,6 +12,7 @@ Page({
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.cb = options.callback || 'callback'
this.setData({ this.setData({
selectedId: options.id selectedId: options.id
}) })
@ -81,5 +82,15 @@ Page({
}) })
} }
}) })
},
onItemTap(e) {
var {id} = e.currentTarget
var {selectedId} = this.data
if (id == selectedId) {
return
}
getPrevPage()[this.cb](id)
wx.navigateBack()
} }
}) })

View File

@ -4,7 +4,7 @@
可选收货地址 可选收货地址
</view> </view>
<view class="address__list"> <view class="address__list">
<view wx:for="{{list}}" wx:key="addr_id" class="address__item"> <view id="{{item.addr_id}}" bindtap="onItemTap" wx:for="{{list}}" wx:key="addr_id" class="address__item">
<image wx:if="{{selectedId == item.addr_id}}" class="address__item-selected-img" src="/images/address_list_selected.png"></image> <image wx:if="{{selectedId == item.addr_id}}" class="address__item-selected-img" src="/images/address_list_selected.png"></image>
<view class=""> <view class="">
{{item.receiver}} {{item.phone}} {{item.receiver}} {{item.phone}}

View File

@ -7,6 +7,8 @@ import {
} from '../../utils/util' } from '../../utils/util'
import debounce from '../../utils/debounce' import debounce from '../../utils/debounce'
import {getUserAddrs} from '../../utils/apis'
var initReLocateLabel = '重新定位' var initReLocateLabel = '重新定位'
Page({ Page({
data: { data: {
@ -21,7 +23,8 @@ Page({
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.callback = options.cb || 'callback' this.callback = options.callback || 'callback'
this.initAddressList()
this.initPoiList() this.initPoiList()
this.onSearchInput = debounce(this.onSearchInput, 300) this.onSearchInput = debounce(this.onSearchInput, 300)
}, },
@ -87,13 +90,35 @@ Page({
}) })
wx.navigateBack() wx.navigateBack()
}, },
onAddressItemTap(e) { onPoiItemTap(e) {
var {id} = e.currentTarget var {id} = e.currentTarget
var {poiList} = this.data var {poiList} = this.data
getPrevPage()[this.callback](poiList[id]) getPrevPage()[this.callback](poiList[id])
wx.navigateBack() wx.navigateBack()
}, },
onAddressItemTap(e) {
var {id} = e.currentTarget
var {addressList} = this.data
getPrevPage()[this.callback](addressList[id])
wx.navigateBack()
},
initAddressList() {
var that = this
getApp().getLoginInfo(loginInfo => {
if(loginInfo.is_login) {
getUserAddrs({
success(data) {
that.setData({
addressList: data
})
}
})
}
})
},
initPoiList() { initPoiList() {
var that = this var that = this
this.setData({ this.setData({

View File

@ -24,7 +24,7 @@
<image class="address-box__title-img" src="/images/takeout_ic_account.png"></image> 您的收货地址 <image class="address-box__title-img" src="/images/takeout_ic_account.png"></image> 您的收货地址
</view> </view>
<view class="address-list"> <view class="address-list">
<view wx:for="{{addressList}}" wx:key="addr_id" class="address-item"> <view id="{{index}}" bindtap="onAddressItemTap" wx:for="{{addressList}}" wx:key="addr_id" class="address-item">
<view class="address-item__addr">{{item.addr}}</view> <view class="address-item__addr">{{item.addr}}</view>
<view class="address-item__name grey-color text-small"> <view class="address-item__name grey-color text-small">
{{item.receiver}} {{item.phone}} {{item.receiver}} {{item.phone}}
@ -37,7 +37,7 @@
<image class="address-box__title-img" src="/images/takeout_ic_address.png"></image> 定位地址 <image class="address-box__title-img" src="/images/takeout_ic_address.png"></image> 定位地址
</view> </view>
<view class="address-list"> <view class="address-list">
<view id="{{index}}" bindtap="onAddressItemTap" wx:for="{{poiList}}" wx:key="{{index}}" class="address-item"> <view id="{{index}}" bindtap="onPoiItemTap" wx:for="{{poiList}}" wx:key="{{index}}" class="address-item">
<view class="address-item__addr">{{item.title}}</view> <view class="address-item__addr">{{item.title}}</view>
<block wx:if="{{index == 0}}"> <block wx:if="{{index == 0}}">
<view class="grey-color text-small"> <view class="grey-color text-small">

View File

@ -1,9 +1,5 @@
//index.js //index.js
//获取应用实例 //获取应用实例
import {
getCurrentAddress, setCurrentAddress
} from '../../utils/util'
import { import {
getSellers getSellers
} from '../../utils/apis' } from '../../utils/apis'
@ -62,13 +58,18 @@ Page({
initAddress() { initAddress() {
var that = this var that = this
getCurrentAddress(function (address) { this.invalidateData()
getApp().getCurrentAddress(function (address) {
if (address.addr_id) {
address['title'] = `${address.addr} ${address.detail}`
}
that.setData({ that.setData({
currentAddress: address currentAddress: address
}) })
that.loadData() that.loadData()
}) })
}, },
loadData() { loadData() {
if (this.data.loading) { if (this.data.loading) {
return; return;
@ -111,16 +112,12 @@ Page({
}) })
}, },
onReachBottom(e) { onReachBottom(e) {
if (this.data.hasMore) { if (this.data.hasMore && !this.data.loading) {
this.loadData() this.loadData()
} }
}, },
callback(address) { callback(address) {
setCurrentAddress(address) getApp().setCurrentAddress(address)
this.setData({ this.initAddress()
currentAddress: address
})
this.invalidateData()
this.loadData()
} }
}) })

View File

@ -3,7 +3,7 @@
<!--index.wxml--> <!--index.wxml-->
<view class="topbar"> <view class="topbar">
<navigator url="./address?cb=callback" class="address trangle"> <navigator url="./address?callback=callback" class="address trangle">
<image class="address__icon" src="/images/location.png"></image>{{currentAddress ? currentAddress.title : '定位中...'}} <image class="address__icon" src="/images/location.png"></image>{{currentAddress ? currentAddress.title : '定位中...'}}
</navigator> </navigator>
<view class="search"> <view class="search">

View File

@ -3,7 +3,7 @@ import WxValidate from '../../utils/WxValidate'
import Countdown from '../../utils/countdown' import Countdown from '../../utils/countdown'
import { alert, getPrevPage } from '../../utils/util' import { alert, getPrevPage } from '../../utils/util'
import { getCode, login } from '../../utils/apis' import { getCode, login } from '../../utils/apis'
var initCount = 10 var initCount = 60
Page({ Page({
data: { data: {
codeLabel: '获取验证码', codeLabel: '获取验证码',
@ -11,7 +11,7 @@ Page({
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.callback = options.callback this.callback = options.callback || 'callback'
this.countdown = new Countdown(this, 'count') this.countdown = new Countdown(this, 'count')
this.initValidate() this.initValidate()
}, },
@ -103,7 +103,9 @@ Page({
that.setData({ that.setData({
loading: false loading: false
}) })
getPrevPage()[that.callback](data) getApp().setLoginInfo(data)
var cb = getPrevPage()[that.callback]
cb && cb(data)
wx.navigateBack() wx.navigateBack()
}, },
error() { error() {

View File

@ -13,17 +13,18 @@ Page({
userInfo userInfo
}) })
}) })
app.getLoginInfo(loginInfo => {
that.setData({
loginInfo: loginInfo.user_info
})
})
}, },
onReady:function(){ onReady:function(){
// 页面渲染完成 // 页面渲染完成
}, },
onShow:function(){ onShow:function(){
// 页面显示 // 页面显示
var that = this
app.getLoginInfo(loginInfo => {
that.setData({
loginInfo: loginInfo.user_info
})
})
}, },
onHide:function(){ onHide:function(){
// 页面隐藏 // 页面隐藏
@ -55,7 +56,6 @@ Page({
}) })
}, },
callback(loginInfo) { callback(loginInfo) {
app.setLoginInfo(loginInfo)
this.setData({ this.setData({
loginInfo: loginInfo.user_info loginInfo: loginInfo.user_info
}) })

View File

@ -1,90 +1,23 @@
// pages/order/list.js // pages/order/list.js
import { ORDER_STATES } from './constant' import { ORDER_STATES } from './constant'
import {
getOrders
} from '../../utils/apis'
import {
datetimeFormat
} from '../../utils/util'
var initData = {
page: 0,
hasMore: true,
loading: false,
list: null
}
Page({ Page({
data: { data: {
login: true,
ORDER_STATES, ORDER_STATES,
list: [
{
"order_id": "1370",
"order_no": "2017042815510158201158862546",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "鸡腿饭(大)",
"add_time": "1493365861",
"order_price": "42.98",
"pay_price": "34.98",
"state": "1",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/Uploadfile/Img/seller_goods/1461034075146103407535640.jpg"
},
{
"order_id": "1347",
"order_no": "2017040708540884666377388205",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "鸡翅饭",
"add_time": "1491526448",
"order_price": "36.00",
"pay_price": "28.00",
"state": "4",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/"
},
{
"order_id": "1345",
"order_no": "2017033115480943749489684006",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "香肠饭 等2件商品",
"add_time": "1490946489",
"order_price": "48.00",
"pay_price": "39.00",
"state": "5",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/"
},
{
"order_id": "1344",
"order_no": "2017033016225869845172165968",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "鸡翅饭",
"add_time": "1490862178",
"order_price": "36.00",
"pay_price": "26.00",
"state": "5",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/"
},
{
"order_id": "1343",
"order_no": "2017033016045232046206634491",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "鸡翅饭",
"add_time": "1490861092",
"order_price": "36.00",
"pay_price": "25.00",
"state": "5",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/"
},
{
"order_id": "1342",
"order_no": "2017033014434386598425245711",
"seller_id": "2",
"seller_name": "鲜极道",
"title": "鸡腿饭",
"add_time": "1490856223",
"order_price": "40.98",
"pay_price": "30.98",
"state": "5",
"is_reviews": "0",
"pic_url": "http://mtest.ipaotui.com/Uploadfile/Img/seller_goods/1461034075146103407535640.jpg"
},
]
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
@ -94,11 +27,81 @@ Page({
}, },
onShow: function () { onShow: function () {
// 页面显示 // 页面显示
var that = this
getApp().getLoginInfo(loginInfo => {
that.setData({
loginInfo: loginInfo
})
var {list} = that.data
if (loginInfo.is_login && !list) {
that.initData()
}
})
}, },
onHide: function () { onHide: function () {
// 页面隐藏 // 页面隐藏
}, },
onUnload: function () { onUnload: function () {
// 页面关闭 // 页面关闭
},
initData(cb) {
this.loadData(cb)
},
loadData(cb) {
var that = this
var {
loading, page
} = this.data
if (loading) {
return
}
this.setData({
loading: true
})
getOrders({
page,
success(data) {
var {list} = that.data
var {list: list2, count, page} = data
list2 = list2.map(item => {
item['add_time_format'] = datetimeFormat(item.add_time)
return item
})
that.setData({
loading: false,
list: list ? list.concat(list2) : list2,
hasMore: count == 10,
page: page + 1
})
cb && cb()
}
})
},
onReachBottom(e) {
var {
loginInfo: {is_login},
hasMore, loading
} = this.data
if (is_login && hasMore && !loading) {
this.loadData()
}
},
onPullDownRefresh() {
var {loginInfo: {is_login}} = this.data
if (is_login) {
wx.showNavigationBarLoading()
this.initData(() => {
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh()
})
} else {
wx.stopPullDownRefresh()
}
},
callback(loginInfo) {
this.setData(initData)
} }
}) })

View File

@ -1,3 +1,4 @@
{ {
"navigationBarTitleText": "我的订单" "navigationBarTitleText": "我的订单",
"enablePullDownRefresh": true
} }

View File

@ -1,31 +1,33 @@
<!--pages/order/list.wxml--> <!--pages/order/list.wxml-->
<view wx:if="{{login}}" class="order-list"> <import src="/templates/load-more.wxml" />
<view wx:if="{{loginInfo.is_login}}">
<view class="order-item" wx:for="{{list}}" wx:key="order_id"> <view class="order-list">
<view class="order-item__hd"> <view class="order-item" wx:for="{{list}}" wx:key="order_id">
<view class="order-item__hd">
<navigator class="order-item__shop trangle" url="/pages/shop/show?id={{item.seller_id}}"> <navigator class="order-item__shop trangle" url="/pages/shop/show?id={{item.seller_id}}">
{{item.seller_name}} {{item.seller_name}}
</navigator> </navigator>
<view class="order-item__status {{item.state==1? 'order-item__status_pay': ''}}">{{ORDER_STATES[item.state]}}</view> <view class="order-item__status {{item.state==1? 'order-item__status_pay': ''}}">{{ORDER_STATES[item.state]}}</view>
</view>
<navigator url="/pages/order/show?id={{item.order_id}}" class="order-item__bd ">
<image class="order-item__pic" src="{{item.pic_url}}"></image>
<view class="order-item__content weui-cell__ft_in-access">
<view class="order-item__price">¥{{item.pay_price}}</view>
<view class="">{{item.add_time}}</view>
</view> </view>
</navigator> <navigator url="/pages/order/show?id={{item.order_id}}" class="order-item__bd ">
<view wx:if="{{item.state == 1 || item.state == 4}}" class="order-item__ft"> <image class="order-item__pic" src="{{item.pic_url}}"></image>
<button wx:if="{{item.state == 1}}" class="weui-btn_primary weui-btn_mini">立即付款</button> <view class="order-item__content weui-cell__ft_in-access">
<navigator wx:else url="url" class="weui-btn_primary weui-btn_mini">去评论</navigator> <view class="order-item__price">¥{{item.pay_price}}</view>
<view class="">{{item.add_time_format}}</view>
</view>
</navigator>
<view wx:if="{{item.state == 1 || item.state == 4}}" class="order-item__ft">
<button wx:if="{{item.state == 1}}" class="weui-btn_primary weui-btn_mini">立即付款</button>
<navigator wx:else url="url" class="weui-btn_primary weui-btn_mini">去评论</navigator>
</view>
</view> </view>
</view> </view>
<template is="load-more" data="{{hasMore: hasMore, loading: loading}}"></template>
</view> </view>
<view wx:else class="order-logout"> <view wx:elif="{{loginInfo}}" class="order-logout">
<image class="order-logout__bg" src="/images/order-logout@2x.png"></image> <image class="order-logout__bg" src="/images/order-logout@2x.png"></image>
<view class="order-logout__tip"> <view class="order-logout__tip">
您还没有登录, 登录后查看订单 您还没有登录, 登录后查看订单
</view> </view>
<navigator url="url" class="weui-btn weui-btn_primary weui-btn_mini" hover-class="button-hover">登录</navigator> <navigator url="/pages/login/login" class="weui-btn weui-btn_primary weui-btn_mini" hover-class="button-hover">登录</navigator>
</view> </view>

View File

@ -1,4 +1,5 @@
/* pages/order/list.wxss */ /* pages/order/list.wxss */
@import '/templates/load-more.wxss';
.order-logout { .order-logout {
text-align: center; text-align: center;

View File

@ -1,65 +1,16 @@
// pages/order/quasi.js // pages/order/quasi.js
import {
getQuasiOrderInfo, updateOrderAddr,
addOrder
} from '../../utils/apis'
Page({ Page({
data: { data: {
info: {
"quasi_order_id": "2691",
"order_no": "2017042716455369061206686592",
"seller_id": "2",
"user_id": "4",
"state": "0",
"add_time": "1493282753",
"order_price": "42.98",
"pay_price": "34.98",
"goods_price": "22.98",
"cut_money": "8.00",
"coupon_money": "0.00",
"packing_fee": "2.00",
"delivery_fee": "18.00",
"receiver": "test4",
"receiver_addr": "龙华大厦",
"receiver_gps": "120.69101,28.002974",
"receiver_phone": "13000000005",
"receive_time": null,
"distance": "7.177",
"remark": null,
"is_reviews": "0",
"is_delete": "0",
"delivery_order_id": "0",
"title": "鸡腿饭(大)",
"receiver_city": "330300",
"commision": "0.00",
"user_coupon_id": null,
"coupon_type": null,
"real_delivery_fee": "18.00",
"cut_delivery_fee": "0.00",
"service_money": "0.00",
"seller_name": "鲜极道",
"seller_phone": "88888888",
"goods": [
{
"goods_id": "29",
"sub_id": "50",
"seller_id": "2",
"detail": "鸡腿饭 xx",
"sales": "46",
"praise": "0",
"state": "1",
"commision": "3.00",
"goods_name": "鸡腿饭(大)",
"price": "22.98",
"packing_fee": "2.00",
"stock": "74",
"is_delete": "0",
"pic_url": "http://test.storesystem.cn/Uploadfile/Img/seller_goods/1461034075146103407535640.jpg",
"num": "1",
"price_sum": "22.98"
}
]
},
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.id = options.id || '2725'
this.loadData()
}, },
onReady: function () { onReady: function () {
// 页面渲染完成 // 页面渲染完成
@ -72,5 +23,84 @@ Page({
}, },
onUnload: function () { onUnload: function () {
// 页面关闭 // 页面关闭
},
loadData() {
var that = this
var {id} = this
var {loading} = this.data
if(loading) {
return
}
this.setData({
loading: true
})
wx.showNavigationBarLoading()
getQuasiOrderInfo({
quasi_order_id: id,
success(data) {
that.setData({
info: data,
loading: false
})
wx.hideNavigationBarLoading()
},
error() {
wx.hideNavigationBarLoading()
}
})
},
callbackAddress(addr_id) {
var that = this
var {id} = this
var {loading} = this.data
if (loading) {
return
}
this.setData({
loading: true
})
wx.showNavigationBarLoading()
updateOrderAddr({
quasi_order_id: id,
addr_id,
success(data) {
that.setData({
info: data,
loading: false
})
wx.hideNavigationBarLoading()
},
error() {
that.setData({
loading: false
})
wx.hideNavigationBarLoading()
}
})
},
onAddOrder(e) {
var that = this
var {id} = this
var {loading} = this.data
if (loading) {
return
}
this.setData({
loading: true
})
addOrder({
quasi_order_id: id,
success(data) {
that.setData({
loading: false
})
},
error() {
that.setData({
loading: false
})
}
})
} }
}) })

View File

@ -1,14 +1,17 @@
<!--pages/order/quasi.wxml--> <!--pages/order/quasi.wxml-->
<view class="quasi"> <view class="quasi">
<view class="weui-panel weui-panel_address "> <view wx:if="{{info}}" class="weui-panel weui-panel_address ">
<view class="weui-panel__bd "> <view class="weui-panel__bd ">
<navigator url class="weui-media-box weui-media-box_text weui-cell__ft_in-access weui-media-box_address"> <navigator wx:if="{{info.receiver_addr_id}}" url="/pages/address/select?callback=callbackAddress&id={{info.receiver_addr_id}}" class="weui-media-box weui-media-box_text weui-cell__ft_in-access weui-media-box_address">
<view class="weui-media-box__title weui-media-box__title_in-text">{{info.receiver}} {{info.receiver_phone}}</view> <view class="weui-media-box__title weui-media-box__title_in-text">{{info.receiver}} {{info.receiver_phone}}</view>
<view class="weui-media-box__desc"> <view class="weui-media-box__desc">
{{info.receiver_addr}} {{info.receiver_addr}}
</view> </view>
</navigator> </navigator>
<navigator wx:else url="/pages/address/select?callback=callbackAddress" class=" weui-media-box weui-media-box_text weui-cell__ft_in-access weui-media-box_address primary-color text-large">
选择地址
</navigator>
</view> </view>
</view> </view>
<view class="weui-cells"> <view class="weui-cells">
@ -79,7 +82,7 @@
待支付 待支付
<text class="primary-color">¥{{info.pay_price}}</text> <text class="primary-color">¥{{info.pay_price}}</text>
</view> </view>
<button class="weui-btn menu-cart__btn" type="primary"> <button bindtap="onAddOrder" loading="{{loading}}" disabled="{{disabled || loading}}" class="weui-btn menu-cart__btn" type="primary">
提交订单 提交订单
</button> </button>
</view> </view>

View File

@ -1,9 +1,13 @@
// pages/order/show.js // pages/order/show.js
import Countdown from '../../utils/countdown' import Countdown from '../../utils/countdown'
import { countdownFormat } from '../../utils/util' import {
countdownFormat, datetimeFormat,
makePhoneCall
} from '../../utils/util'
import { getOrderInfo } from '../../utils/apis'
Page({ Page({
data: { data: {
activeNavIndex: 1, activeNavIndex: 0,
tabNavs: ['订单状态', '订单详情'], tabNavs: ['订单状态', '订单详情'],
statusImgs: { statusImgs: {
'1': '/images/status/order_status_money_icon_current@2x.png', '1': '/images/status/order_status_money_icon_current@2x.png',
@ -14,95 +18,11 @@ Page({
'6': '/images/status/order_status_service_icon_fail_current@2x.png', '6': '/images/status/order_status_service_icon_fail_current@2x.png',
'7': '/images/status/order_status_service_icon_fail_current@2x.png' '7': '/images/status/order_status_service_icon_fail_current@2x.png'
}, },
info: {
"order_id": "1375",
"order_no": "2017050316304632448020041071",
"day_sn": "4",
"seller_id": "2",
"user_id": "4",
"state": "3",
"add_time": "1493800246",
"order_price": "30.00",
"pay_price": "22.00",
"goods_price": "20.00",
"cut_money": "8.00",
"coupon_money": "0.00",
"packing_fee": "0.00",
"delivery_fee": "10.00",
"receiver": "test4",
"receiver_addr": "电商大厦",
"receiver_gps": "120.737561,27.979617",
"receiver_phone": "13000000004",
"receive_time": "1493803846",
"distance": "1.707",
"remark": "",
"is_reviews": "0",
"is_delete": "0",
"delivery_order_id": "0",
"title": "鸡翅饭",
"receiver_city": "330300",
"take_time": "1493800254",
"remind_time": "0",
"pay_type": "3",
"sys_settle_no": null,
"settle_no": null,
"commision": "0.00",
"user_coupon_id": null,
"real_delivery_fee": "10.00",
"cut_delivery_fee": "0.00",
"service_money": "0.00",
"seller_name": "鲜极道",
"seller_phone": "88888888",
"delivery_phone": "13906641410",
"goods": [
{
"goods_id": "32",
"sub_id": "0",
"seller_id": "2",
"detail": "鸡翅饭 xx",
"sales": "43",
"praise": "0",
"state": "1",
"commision": null,
"goods_name": "鸡翅饭",
"price": "20.00",
"packing_fee": "0.00",
"stock": "54",
"is_delete": "0",
"pic_url": null,
"num": "1",
"price_sum": "20.00"
}
],
"expire_time": 0,
"left_time": 0,
"flow": [
{
"time": "1493800246",
"state": "1",
"status": "订单提交成功,待支付",
"remark": ""
},
{
"time": "1493800252",
"state": "2",
"status": "支付成功,等待商家接单",
"remark": ""
},
{
"time": "1493800254",
"state": "3",
"status": "商家已接单",
"remark": ""
}
],
"run_order_id": "6408",
"localphone": "13906641410"
},
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.initCountdown(287) this.id = options.id || 1395
this.loadData()
}, },
onReady: function () { onReady: function () {
// 页面渲染完成 // 页面渲染完成
@ -143,6 +63,54 @@ Page({
}) })
}) })
this.countdown = countdown this.countdown = countdown
},
loadData() {
var that = this
var order_id = this.id
wx.showNavigationBarLoading()
getOrderInfo({
order_id,
success(data) {
data['add_time_format'] = datetimeFormat(data.add_time)
data['flow'] = data.flow.map(item => {
item['time_format'] = datetimeFormat(item.time)
return item
})
that.setData({
info: data
})
if(data.left_time > 0) {
that.initCountdown(+data.left_time)
}
wx.hideNavigationBarLoading()
},
error() {
wx.hideNavigationBarLoading()
}
})
},
onPhoneTap(e) {
var that = this
var {info: {seller_phone, localphone}} = this.data
wx.showActionSheet({
itemList: [
`商家电话: ${seller_phone}`,
`客服电话: ${localphone}`
],
success: function (res) {
var {tapIndex} = res
if(tapIndex == 0) {
makePhoneCall(seller_phone)
} else if(tapIndex == 1) {
makePhoneCall(localphone)
}
},
fail: function (res) {
console.log(res.errMsg)
}
})
} }
}) })

View File

@ -5,7 +5,7 @@
<view bindtap="navChange" id="{{index}}" wx:for="{{tabNavs}}" wx:key="{{index}}" class="tab__navbar-item {{index == activeNavIndex? 'tab__navbar-item_active': ''}} "> <view bindtap="navChange" id="{{index}}" wx:for="{{tabNavs}}" wx:key="{{index}}" class="tab__navbar-item {{index == activeNavIndex? 'tab__navbar-item_active': ''}} ">
订单状态 订单状态
</view> </view>
<view wx:if="{{info.localphone}}" class="phone"> <view bindtap="onPhoneTap" class="phone">
<image class="phone__icon" src="/images/chat_phone_normal.png"></image> <image class="phone__icon" src="/images/chat_phone_normal.png"></image>
</view> </view>
</view> </view>
@ -15,23 +15,24 @@
<view wx:for="{{info.flow}}" wx:key="{{index}}" class="flow-item"> <view wx:for="{{info.flow}}" wx:key="{{index}}" class="flow-item">
{{item.status}} {{item.status}}
<image wx:if="{{item.state == info.state}}" src="{{statusImgs[item.state]}}" class="flow-item__img"></image> <image wx:if="{{item.state == info.state}}" src="{{statusImgs[item.state]}}" class="flow-item__img"></image>
<view class="flow-item__time">{{item.time}}</view> <view class="flow-item__time">{{item.time_format}}</view>
</view> </view>
</view> </view>
<view wx:if="{{count > 0}}" class="order-show__left-time"> <view wx:if="{{count > 0}}" class="order-show__left-time">
支付剩余时间 支付剩余时间
<text class="primary-color">{{countLabel}}</text> <text class="primary-color">{{countLabel}}</text>
</view> </view>
<view class="actionbar"> <view wx:if="{{info.state < 4}}" class="actionbar">
<view class="actionbar-btn actionbar-btn_action">取消订单</view> <view wx:if="{{info.state < 4}}" class="actionbar-btn actionbar-btn_action">取消订单</view>
<view class="actionbar-btn actionbar-btn_action actionbar-btn_primary">立即付款</view> <view wx:if="{{info.state == 1}}" class="actionbar-btn actionbar-btn_action actionbar-btn_primary">立即付款</view>
<view wx:if="{{info.state == 4}}" class="actionbar-btn actionbar-btn_action actionbar-btn_primary">评价</view>
</view> </view>
</swiper-item> </swiper-item>
<swiper-item class="tab__swiper-item tab__swiper-item_detail"> <swiper-item class="tab__swiper-item tab__swiper-item_detail">
<view class="weui-cells__title">订单详情</view> <view class="weui-cells__title">订单详情</view>
<view class="quasi-goods"> <view class="quasi-goods">
<view class="quasi-goods__hd weui-flex"> <view class="quasi-goods__hd weui-flex">
<navigator url="url" class=" trangle"> <navigator url="/pages/shop/show?id={{info.seller_id}}" class=" trangle">
<image class="quasi-goods__img" src="/images/shop-512.png"></image> <image class="quasi-goods__img" src="/images/shop-512.png"></image>
{{info.seller_name}} {{info.seller_name}}
</navigator> </navigator>
@ -125,7 +126,7 @@
订单时间 订单时间
</view> </view>
<view class="weui-cell__bd"> <view class="weui-cell__bd">
{{info.add_time}} {{info.add_time_format}}
</view> </view>
</view> </view>
<view class="weui-cell"> <view class="weui-cell">

View File

@ -1,5 +1,8 @@
/* pages/order/show.wxss */ /* pages/order/show.wxss */
@import './quasi.wxss'; @import './quasi.wxss';
.quasi-goods {
margin-top: 0;
}
.tab { .tab {
display: flex; display: flex;

View File

@ -2,13 +2,12 @@
import { import {
makePhoneCall, makePhoneCall,
getCurrentAddress,
datetimeFormat datetimeFormat
} from '../../utils/util' } from '../../utils/util'
import { import {
getSellerInfo, getSellerInfo,
getReviews getReviews, addQuasiOrder
} from '../../utils/apis' } from '../../utils/apis'
@ -43,7 +42,7 @@ Page({
}, },
onLoad: function (options) { onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数 // 页面初始化 options为页面跳转所带来的参数
this.id = options.id || 1 this.id = options.id || 2
this.loadData() this.loadData()
this.loadReview() this.loadReview()
}, },
@ -64,23 +63,20 @@ Page({
var that = this var that = this
var id = this.id; var id = this.id;
wx.showNavigationBarLoading() wx.showNavigationBarLoading()
getCurrentAddress(function (address) { getSellerInfo({
getSellerInfo({ seller_id: id,
address, success(data) {
seller_id: id, data['distanceFormat'] = +(data['distance'] / 1000).toFixed(2)
success(data) { that.setData({
data['distanceFormat'] = +(data['distance'] / 1000).toFixed(2) info: data
that.setData({ })
info: data wx.setNavigationBarTitle({
}) title: data.seller_name
wx.setNavigationBarTitle({ })
title: data.seller_name },
}) complete() {
}, wx.hideNavigationBarLoading()
complete() { }
wx.hideNavigationBarLoading()
}
})
}) })
}, },
@ -331,5 +327,48 @@ Page({
if (hasMore && !loading) { if (hasMore && !loading) {
this.loadReview() this.loadReview()
} }
},
onAddQuasiOrder(e) {
var that = this
var {
info: {seller_id},
order: {goods},
loading
} = this.data
if (loading) {
return
}
this.setData({
loading: true
})
getApp().getLoginInfo(loginInfo => {
if(!loginInfo.is_login) {
wx.navigateTo({
url: '/pages/login/login',
})
this.setData({
loading: false
})
return
}
addQuasiOrder({
seller_id, goods,
success(data) {
that.setData({
loading: false
})
wx.navigateTo({
url: `/pages/order/quasi?id=${data.quasi_order_id}`
})
},
error() {
that.setData({
loading: false
})
}
})
})
} }
}) })

View File

@ -84,11 +84,13 @@
<view class="text-small grey-color">另需配送费{{info.delivery_fee}}元</view> <view class="text-small grey-color">另需配送费{{info.delivery_fee}}元</view>
</view> </view>
</view> </view>
<button class="weui-btn menu-cart__btn" type="primary" disabled="{{order.totalPrice < info.min_price ? true: false}}"> <button disabled="{{loading}}" loading="{{loading}}" wx:if="{{order.totalPrice >= info.min_price}}" bindtap="onAddQuasiOrder" class="weui-btn menu-cart__btn" type="primary">
<block wx:if="{{order.totalPrice > 0 }}"> 选好了
<text wx:if="{{order.totalPrice > info.min_price}}">选好了</text> </button>
<text wx:else>还差{{info.min_price - order.totalPrice}}元起送</text> <button wx:else class="weui-btn menu-cart__btn" type="primary" disabled>
</block> <text wx:if="{{order.totalPrice > 0}}">
还差{{info.min_price - order.totalPrice}}元起送
</text>
<text wx:else>{{info.min_price}}元起送</text> <text wx:else>{{info.min_price}}元起送</text>
</button> </button>
</view> </view>

View File

@ -1,6 +1,6 @@
import { import {
fetch, coordFormat, fetch, coordFormat,
alert, confirm alert, confirm,
} from './util' } from './util'
// 获取商店列表 // 获取商店列表
@ -10,7 +10,7 @@ export function getSellers(options) {
success success
} = options } = options
page = page || 0 page = page || 0
var location = coordFormat(address.location) var location = address.location
fetch({ fetch({
url: 'index.php?m=Mall&c=Seller&a=getSellers', url: 'index.php?m=Mall&c=Seller&a=getSellers',
data: { data: {
@ -29,18 +29,20 @@ export function getSellers(options) {
// 获取商店详情 // 获取商店详情
export function getSellerInfo(options) { export function getSellerInfo(options) {
var { var {
seller_id, address, seller_id,
success, complete success, complete
} = options } = options
var location = coordFormat(address.location) getApp().getCurrentAddress(address => {
fetch({ var location = address.location
url: 'index.php?m=Mall&c=Seller&a=getSellerInfo', fetch({
data: { url: 'index.php?m=Mall&c=Seller&a=getSellerInfo',
seller_id, data: {
longitude: location.longitude, seller_id,
latitude: location.latitude longitude: location.longitude,
}, latitude: location.latitude
success, complete },
success, complete
})
}) })
} }
@ -185,7 +187,7 @@ export function getUserAddr(options) {
// 新增用户地址 // 新增用户地址
export function addUserAddr(options) { export function addUserAddr(options) {
if(options.addr_id) { if (options.addr_id) {
return updateUserAddr(options) return updateUserAddr(options)
} }
const { const {
@ -198,7 +200,7 @@ export function addUserAddr(options) {
} }
var {user_id, user_token} = loginInfo.user_info var {user_id, user_token} = loginInfo.user_info
var gps = address.gps var gps = address.gps
if(!gps) { if (!gps) {
var location = coordFormat(address.location) var location = coordFormat(address.location)
gps = `${location.longitude},${location.latitude}` gps = `${location.longitude},${location.latitude}`
} }
@ -207,7 +209,7 @@ export function addUserAddr(options) {
data: { data: {
user_id, user_token, user_id, user_token,
receiver, phone, detail, receiver, phone, detail,
gps, gps,
addr: address.title, addr: address.title,
city_id: address.city_id, city_id: address.city_id,
city_name: address.city, city_name: address.city,
@ -233,7 +235,7 @@ export function updateUserAddr(options) {
} }
var {user_id, user_token} = loginInfo.user_info var {user_id, user_token} = loginInfo.user_info
var gps = address.gps var gps = address.gps
if(!gps) { if (!gps) {
var location = coordFormat(address.location) var location = coordFormat(address.location)
gps = `${location.longitude},${location.latitude}` gps = `${location.longitude},${location.latitude}`
} }
@ -275,5 +277,164 @@ export function deleteUserAddr(options) {
success, error success, error
}) })
})
}
// 添加准订单
export function addQuasiOrder(options) {
const {
seller_id,
goods,
success, error
} = options
getApp().getCurrentAddress(address => {
var data = {
seller_id,
goods: JSON.stringify(goods)
}
if (address.addr_id) {
data = Object.assign({
addr_id: address.addr_id
}, data)
} else {
var location = address.location
data = Object.assign({
city_id: address.city_id,
city_name: address.city,
district_id: address.district_id,
district_name: address.district,
longitude: location.longitude,
latitude: location.latitude
}, data)
}
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=addQuasiOrder',
data: Object.assign({
user_id, user_token,
}, data),
success, error
})
})
})
}
// 获取准订单
export function getQuasiOrderInfo(options) {
var {
quasi_order_id,
success, error
} = options
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=getQuasiOrderInfo',
data: {
user_id, user_token,
quasi_order_id
},
success, error
})
})
}
// 更新准订单地址
export function updateOrderAddr(options) {
var {
quasi_order_id, addr_id,
success, error
} = options
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=updateOrderAddr',
data: {
user_id, user_token,
quasi_order_id, addr_id
},
success, error
})
})
}
// 添加订单
export function addOrder(options) {
var {
quasi_order_id,
success, error
} = options
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=addOrder',
data: {
user_id, user_token,
quasi_order_id
},
success, error
})
})
}
// 获取订单列表
export function getOrders(options) {
var {
page,
success, error
} = options
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=getOrders',
data: {
user_id, user_token,
page
},
success, error
})
})
}
// 获取订单详情
export function getOrderInfo(options) {
var {
order_id,
success, error
} = options
getApp().getLoginInfo(loginInfo => {
if (!loginInfo.user_info) {
return alert('用户未登录')
}
var {user_id, user_token} = loginInfo.user_info
fetch({
url: 'index.php?m=Mall&c=Order&a=getOrderInfo',
data: {
user_id, user_token,
order_id
},
success, error
})
}) })
} }

226
app/utils/dateformat.js Normal file
View File

@ -0,0 +1,226 @@
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
(function(global) {
'use strict';
var dateFormat = (function() {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|'[^']*'|'[^']*'/g;
var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;
var timezoneClip = /[^-+\dA-Z]/g;
// Regexes and supporting functions are cached through closure
return function (date, mask, utc, gmt) {
// You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) {
mask = date;
date = undefined;
}
date = date || new Date;
if(!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date)) {
throw TypeError('Invalid date');
}
mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']);
// Allow setting the utc/gmt argument via the mask
var maskSlice = mask.slice(0, 4);
if (maskSlice === 'UTC:' || maskSlice === 'GMT:') {
mask = mask.slice(4);
utc = true;
if (maskSlice === 'GMT:') {
gmt = true;
}
}
var _ = utc ? 'getUTC' : 'get';
var d = date[_ + 'Date']();
var D = date[_ + 'Day']();
var m = date[_ + 'Month']();
var y = date[_ + 'FullYear']();
var H = date[_ + 'Hours']();
var M = date[_ + 'Minutes']();
var s = date[_ + 'Seconds']();
var L = date[_ + 'Milliseconds']();
var o = utc ? 0 : date.getTimezoneOffset();
var W = getWeek(date);
var N = getDayOfWeek(date);
var flags = {
d: d,
dd: pad(d),
ddd: dateFormat.i18n.dayNames[D],
dddd: dateFormat.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dateFormat.i18n.monthNames[m],
mmmm: dateFormat.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(Math.round(L / 10)),
t: H < 12 ? 'a' : 'p',
tt: H < 12 ? 'am' : 'pm',
T: H < 12 ? 'A' : 'P',
TT: H < 12 ? 'AM' : 'PM',
Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
W: W,
N: N
};
return mask.replace(token, function (match) {
if (match in flags) {
return flags[match];
}
return match.slice(1, match.length - 1);
});
};
})();
dateFormat.masks = {
'default': 'ddd mmm dd yyyy HH:MM:ss',
'shortDate': 'm/d/yy',
'mediumDate': 'mmm d, yyyy',
'longDate': 'mmmm d, yyyy',
'fullDate': 'dddd, mmmm d, yyyy',
'shortTime': 'h:MM TT',
'mediumTime': 'h:MM:ss TT',
'longTime': 'h:MM:ss TT Z',
'isoDate': 'yyyy-mm-dd',
'isoTime': 'HH:MM:ss',
'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso',
'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'',
'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z'
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
],
monthNames: [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
]
};
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
/**
* Get the ISO 8601 week number
* Based on comments from
* http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
*
* @param {Object} `date`
* @return {Number}
*/
function getWeek(date) {
// Remove time components of date
var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(targetThursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);
// Check if daylight-saving-time-switch occurred and correct for it
var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
targetThursday.setHours(targetThursday.getHours() - ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (targetThursday - firstThursday) / (86400000*7);
return 1 + Math.floor(weekDiff);
}
/**
* Get ISO-8601 numeric representation of the day of the week
* 1 (for Monday) through 7 (for Sunday)
*
* @param {Object} `date`
* @return {Number}
*/
function getDayOfWeek(date) {
var dow = date.getDay();
if(dow === 0) {
dow = 7;
}
return dow;
}
/**
* kind-of shortcut
* @param {*} val
* @return {String}
*/
function kindOf(val) {
if (val === null) {
return 'null';
}
if (val === undefined) {
return 'undefined';
}
if (typeof val !== 'object') {
return typeof val;
}
if (Array.isArray(val)) {
return 'array';
}
return {}.toString.call(val)
.slice(8, -1).toLowerCase();
};
if (typeof define === 'function' && define.amd) {
define(function () {
return dateFormat;
});
} else if (typeof exports === 'object') {
module.exports = dateFormat;
} else {
global.dateFormat = dateFormat;
}
})(this);

38
app/utils/distance.js Normal file
View File

@ -0,0 +1,38 @@
var RADIUS = 6371;
var toRad = function(n) {
return n * Math.PI / 180;
};
var getDistance = function(from, to) {
var fromLat = from[0];
var fromLon = from[1];
var toLat = to[0];
var toLon = to[1];
var dLat = toRad(toLat - fromLat);
var dLon = toRad(toLon - fromLon);
var fromLat = toRad(fromLat);
var toLat = toRad(toLat);
var a = Math.pow(Math.sin(dLat / 2), 2) +
(Math.pow(Math.sin(dLon / 2), 2) * Math.cos(fromLat) * Math.cos(toLat));
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return RADIUS * c;
};
var measurePath = function(points) {
return points.reduce(function(memo, point) {
var distance = memo.lastPoint === null ? 0 : getDistance(memo.lastPoint, point);
return { lastPoint: point, distance: distance + memo.distance };
}, { lastPoint: null, distance: 0 }).distance;
};
module.exports = function(fromLat, fromLon, toLat, toLon) {
if(typeof fromLat === 'number'){
return getDistance([fromLat, fromLon], [toLat, toLon]);
} else {
return measurePath(fromLat);
}
};

View File

@ -1,306 +1,300 @@
'use strict'; 'use strict';
import timeago from './timeago.min' import timeago from './timeago.min'
import dateFormat from './dateformat'
import distance from './distance'
import QQMapWX from './qqmap-wx-jssdk.min' import QQMapWX from './qqmap-wx-jssdk.min'
import { gcj02tobd09 } from './coordtransform' import {
gcj02tobd09
} from './coordtransform'
import { host, qqmapKey } from '../config' import { host, qqmapKey } from '../config'
const qqmap = new QQMapWX({ const qqmap = new QQMapWX({
key: qqmapKey key: qqmapKey
}); });
function resolveAdInfo(adInfo) { function resolveAdInfo(adInfo) {
const {city, district, adcode} = adInfo const {city, district, adcode} = adInfo
return { return {
city, district, city, district,
district_id: adcode, district_id: adcode,
city_id: adcode.replace(/\d{2}$/, '00') city_id: adcode.replace(/\d{2}$/, '00')
} }
} }
// 解析地址 // 解析地址
export function reverseGeocoder(options) { export function reverseGeocoder(options) {
const { const {
location, success, complete location, success, complete
} = options } = options
qqmap.reverseGeocoder({ qqmap.reverseGeocoder({
location, location,
success: function (res) { success: function (res) {
var address = resolveAdInfo(res.result.ad_info) var address = resolveAdInfo(res.result.ad_info)
success && success(address) success && success(address)
}, },
fail: function (err) { fail: function (err) {
console.log(err) console.log(err)
}, },
complete complete
}) })
} }
// 获取当前地理位置 // 获取当前地理位置
export function getCurrentAddressList(options) { export function getCurrentAddressList(options) {
const { const {
success, complete success, complete
} = options } = options
wx.getLocation({ wx.getLocation({
type: 'gcj02', type: 'gcj02',
success(res) { success(res) {
getAddressFromLocation({ getAddressFromLocation({
location: { location: {
latitude: res.latitude, latitude: res.latitude,
longitude: res.longitude, longitude: res.longitude,
},
success, complete
})
}, },
fail(e) { success, complete
console.log(res.errMsg) })
alert('获取用户地址失败') },
} fail(res) {
}) console.log(res.errMsg)
alert('获取用户地址失败')
}
})
} }
// 地点搜索 // 地点搜索
export function searchAddressList(options) { export function searchAddressList(options) {
const { const {
keyword, success keyword, success
} = options } = options
getCurrentCity(function (cityName) { getCurrentCity(function (cityName) {
qqmap.getSuggestion({ qqmap.getSuggestion({
region: cityName, region: cityName,
keyword, keyword,
success(res) { success(res) {
success && success(res.data) success && success(res.data)
} }
})
}) })
})
} }
// 获取当期地址 // 获取当前地址
var currentAddress;
export function getCurrentAddress(callback) { export function getCurrentAddress(callback) {
if(currentAddress) { getCurrentAddressList({
return callback && callback(currentAddress) success(addressList) {
if (addressList.length > 0) {
callback(addressList[0])
}
} }
})
getCurrentAddressList({
success(addressList) {
if(addressList.length > 0) {
currentAddress = addressList[0]
callback(currentAddress)
}
}
})
}
export function setCurrentAddress(address) {
currentAddress = address
} }
// 获取当前城市 // 获取当前城市
var cityName; var cityName;
export function getCurrentCity(callback) { export function getCurrentCity(callback) {
if (cityName) { if (cityName) {
return callback && callback(cityName) return callback && callback(cityName)
} }
wx.getLocation({ wx.getLocation({
type: 'gcj02', type: 'gcj02',
success(res) { success(res) {
qqmap.reverseGeocoder({ qqmap.reverseGeocoder({
location: { location: {
longitude: res.longitude, longitude: res.longitude,
latitude: res.latitude latitude: res.latitude
},
success: function (res) {
cityName = res.result.address_component.city
callback && callback(cityName)
}
})
}, },
fail(res) { success: function (res) {
console.log(res.errMsg) cityName = res.result.address_component.city
alert('获取用户地址失败') callback && callback(cityName)
} }
}) })
},
fail(res) {
console.log(res.errMsg)
alert('获取用户地址失败')
}
})
} }
// 根据坐标获取地址信息 // 根据坐标获取地址信息
export function getAddressFromLocation(options) { export function getAddressFromLocation(options) {
const {location, success} = options const {location, success} = options
getPois({ getPois({
location, location,
success(pois) { success(pois) {
var addressList = [] var addressList = []
pois.forEach(poi => { pois.forEach(poi => {
var { var {
title, location, title, location,
address, ad_info address, ad_info
} = poi } = poi
addressList.push(Object.assign({ addressList.push(Object.assign({
title, location, address title, location, address
}, resolveAdInfo(ad_info))) }, resolveAdInfo(ad_info)))
}) })
success && success(addressList) success && success(addressList)
} }
}) })
} }
// 获取兴趣点 // 获取兴趣点
export function getPois(options) { export function getPois(options) {
const { const {
location, success, complete location, success, complete
} = options } = options
qqmap.reverseGeocoder({ qqmap.reverseGeocoder({
location, location,
get_poi: 1, get_poi: 1,
success: function (res) { success: function (res) {
success && success(res.result.pois) success && success(res.result.pois)
}, },
fail: function (err) { fail: function (err) {
console.log(err) console.log(err)
}, },
complete complete
}) })
} }
export function getPrevPage() { export function getPrevPage() {
const pages = getCurrentPages() const pages = getCurrentPages()
return pages[pages.length - 2] return pages[pages.length - 2]
} }
export function fetch(options) { export function fetch(options) {
wx.request({ wx.request({
url: `https://${host}/${options.url}`, url: `https://${host}/${options.url}`,
data: Object.assign(options.data, { data: Object.assign(options.data, {
'app_v': 'ipaotui_mall' 'app_v': 'ipaotui_mall'
}), }),
method: options.method || 'POST', method: options.method || 'POST',
header: { header: {
'content-type': 'application/x-www-form-urlencoded' 'content-type': 'application/x-www-form-urlencoded'
}, },
success: function (res) { success: function (res) {
const data = res.data const data = res.data
if (data.State == 'Success') { if (data.State == 'Success') {
options.success && options.success(data.data) options.success && options.success(data.data)
} else { } else {
alert(data.info) alert(data.info)
options.error && options.error(data.info) options.error && options.error(data.info)
} }
options.complete && options.complete() options.complete && options.complete()
} }
}) })
} }
// 提示框 // 提示框
export function alert(content, callback) { export function alert(content, callback) {
wx.showModal({ wx.showModal({
title: '提示', title: '提示',
content: content, content: content,
showCancel: false, showCancel: false,
success: callback success: callback
}) })
} }
// 确认框 // 确认框
export function confirm(options) { export function confirm(options) {
var { var {
content, confirmText, content, confirmText,
ok, ok,
} = options } = options
confirmText = confirmText || '确定' confirmText = confirmText || '确定'
wx.showModal({ wx.showModal({
content, content,
confirmText, confirmText,
cancelText: '关闭', cancelText: '关闭',
success(res) { success(res) {
if (res.confirm) { if (res.confirm) {
ok && ok() ok && ok()
} }
} }
}) })
} }
// 拨打电话 // 拨打电话
export function makePhoneCall(phoneNum) { export function makePhoneCall(phoneNum) {
confirm({ confirm({
content: `是否拨打电话 ${phoneNum}`, content: `是否拨打电话 ${phoneNum}`,
confirmText: '拨打', confirmText: '拨打',
ok() { ok() {
wx.makePhoneCall({ wx.makePhoneCall({
phoneNumber: phoneNum, phoneNumber: phoneNum,
}) })
} }
}) })
} }
// 加载提示 // 加载提示
export function showLoading() { export function showLoading() {
wx.showToast({ wx.showToast({
icon: 'loading', icon: 'loading',
duration: 10000, duration: 10000,
title: '加载中...', title: '加载中...',
mask: true, mask: true,
}) })
} }
export function hideLoading() { export function hideLoading() {
wx.hideToast() wx.hideToast()
} }
// 时间格式化 // 时间格式化
export function datetimeFormat(unix_timestamp) { export function datetimeFormat(unix_timestamp) {
return new timeago().format(new Date(unix_timestamp * 1000), 'zh_CN'); return dateFormat(new Date(unix_timestamp * 1000), "mm月dd日 HH:MM")
} }
// 坐标格式化 // 坐标格式化
export function coordFormat(location) { export function coordFormat(location) {
if(location.lat && location.lng) { if (location.lat && location.lng) {
location = { location = {
longitude: location.lng, longitude: location.lng,
latitude: location.lat latitude: location.lat
}
}
// gcj02 转 bd09
var location = gcj02tobd09(location.longitude, location.latitude)
return {
longitude: location[0],
latitude: location[1]
} }
}
// gcj02 转 bd09
var location = gcj02tobd09(location.longitude, location.latitude)
return {
longitude: location[0],
latitude: location[1]
}
} }
// 倒计时格式化 // 倒计时格式化
export function countdownFormat(count) { export function countdownFormat(count) {
var seconds = count % 60 var seconds = count % 60
count = Math.floor(count / 60) count = Math.floor(count / 60)
var minutes = count % 60 var minutes = count % 60
return `${minutes}分钟${seconds}` return `${minutes}分钟${seconds}`
} }
// 字符串关键字分组 // 字符串关键字分组
export function splitByKeyword(text, keyword) { export function splitByKeyword(text, keyword) {
if (!text) { if (!text) {
return [] return []
} }
var arr = text.split(keyword) var arr = text.split(keyword)
var res = [] var res = []
res.push({
text: arr[0],
isKeyword: false
})
for (let i = 1, len = arr.length; i < len; i++) {
res.push({ res.push({
text: arr[0], text: keyword,
isKeyword: true
}, {
text: arr[i],
isKeyword: false isKeyword: false
}) })
for (let i = 1, len = arr.length; i < len; i++) { }
res.push({ return res
text: keyword,
isKeyword: true
}, {
text: arr[i],
isKeyword: false
})
}
return res
} }
var userInfo var userInfo
export function getUserInfo(cb) { export function getUserInfo(cb) {
if(userInfo) { if (userInfo) {
return cb(userInfo) return cb(userInfo)
} else { } else {
wx.getUserInfo({ wx.getUserInfo({