Files
kangyuan-mobile/pages/user/goods_details_store/index.vue
T

699 lines
18 KiB
Vue

<template>
<s-layout :bgStyle="{ color: '#FFF' }" title="选择自提门店">
<view class="store-page">
<view class="search-bar">
<view class="search-inner">
<image class="search-icon" src="/static/icon/search.svg" mode="aspectFit" />
<uni-easyinput
class="search-input"
v-model="state.keyword"
placeholder="搜索自提点..."
:inputBorder="false"
:clearable="true"
/>
</view>
</view>
<view class="map-card">
<map
class="map"
:latitude="state.mapLatitude"
:longitude="state.mapLongitude"
:scale="state.mapScale"
:markers="markers"
show-location
@markertap="onMarkerTap"
/>
<cover-view v-if="selectedStore" class="map-center-marker">
<cover-view class="map-center-marker__label">{{ selectedStore.name || '自提门店' }}</cover-view>
</cover-view>
</view>
<view class="list-hd">
<view class="list-title">附近自提点</view>
<view class="list-sub" v-if="filteredStoreList.length">共{{ filteredStoreList.length }}家</view>
</view>
<view class="store-list" ref="container">
<view
class="store-item"
v-for="(item, index) in filteredStoreList"
:key="item.id || index"
:class="{ 'store-item--active': Number(item.id) === Number(state.selectedStoreId) }"
@tap="onSelect(item)"
>
<view class="store-item__hd">
<view class="store-badge">#{{ index + 1 }}</view>
<view class="store-name">{{ item.name }}</view>
<view
v-if="getStoreStatusText(item.status)"
class="store-status"
:class="`store-status--${getStoreStatusLevel(item.status)}`"
>
{{ getStoreStatusText(item.status) }}
</view>
<view class="store-distance" v-if="item.distance !== undefined && item.distance !== null">
{{ formatDistance(item.distance) }}
</view>
</view>
<view class="store-address line2">
{{ formatAddress(item) || '--' }}
</view>
<view class="store-item__ft">
<view class="store-hours">
<text v-if="Number(item.status) === 1 && formatBusinessHours(item)">
营业中 {{ formatBusinessHours(item) }}
</text>
</view>
<view class="store-actions">
<view class="btn btn--ghost" @tap.stop="showMaoLocation(item)">导航</view>
<view
v-if="Number(item.status) === 1"
class="btn"
@tap.stop="checked(item)"
>选择</view>
</view>
</view>
</view>
</view>
<canvas canvas-id="storeMarkerCanvas" class="marker-canvas" />
</view>
</s-layout>
</template>
<script setup>
import StoreApi from '@/sheep/api/trade/store';
import { computed, getCurrentInstance, onMounted, reactive } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import sheep from '@/sheep';
const { proxy } = getCurrentInstance();
const LONGITUDE = 'user_longitude';
const LATITUDE = 'user_latitude';
const state = reactive({
loaded: false,
loading: false,
storeList: [],
system_store: {},
locationShow: false,
user_latitude: 0,
user_longitude: 0,
mapLatitude: 0,
mapLongitude: 0,
mapScale: 12,
selectedStoreId: 0,
keyword: '',
markerIconMap: {},
});
const selfLocation = () => {
// #ifdef H5
const jsWxSdk = sheep.$platform.useProvider('wechat').jsWxSdk;
if (jsWxSdk.isWechat()) {
jsWxSdk.getLocation((res) => {
state.user_latitude = res.latitude;
state.user_longitude = res.longitude;
state.mapLatitude = res.latitude;
state.mapLongitude = res.longitude;
uni.setStorageSync(LATITUDE, res.latitude);
uni.setStorageSync(LONGITUDE, res.longitude);
getList();
});
} else {
// #endif
uni.getLocation({
type: 'gcj02',
success: (res) => {
try {
state.user_latitude = res.latitude;
state.user_longitude = res.longitude;
state.mapLatitude = res.latitude;
state.mapLongitude = res.longitude;
uni.setStorageSync(LATITUDE, res.latitude);
uni.setStorageSync(LONGITUDE, res.longitude);
} catch (e) {
console.error(e);
}
getList();
},
complete: () => {
getList();
},
});
// #ifdef H5
}
// #endif
};
const showMaoLocation = (e) => {
// #ifdef H5
const jsWxSdk = sheep.$platform.useProvider('wechat').jsWxSdk;
if (jsWxSdk.isWechat()) {
jsWxSdk.openLocation({
latitude: Number(e.latitude),
longitude: Number(e.longitude),
name: e.name,
address: `${e.district}-${e.description}`,
});
} else {
// #endif
uni.openLocation({
latitude: Number(e.latitude),
longitude: Number(e.longitude),
name: e.name,
address: `${e.district}-${e.description}`,
success: function () {
console.log('success');
},
});
// #ifdef H5
}
// #endif
};
/**
* 选中门店
*/
const checked = (addressInfo) => {
if (!isStoreOpen(addressInfo)) {
uni.showToast({ title: '当前门店暂不支持自提', icon: 'none' });
return;
}
uni.$emit('SELECT_PICK_UP_INFO', {
addressInfo,
});
sheep.$router.back();
};
const onSelect = (item) => {
if (!isStoreOpen(item)) {
uni.showToast({ title: '当前门店暂不支持自提', icon: 'none' });
return;
}
state.selectedStoreId = Number(item?.id || 0);
const lat = Number(item?.latitude);
const lon = Number(item?.longitude);
if (lat && lon) {
state.mapLatitude = lat;
state.mapLongitude = lon;
state.mapScale = 14;
}
renderMarkerIcon(item, true);
};
const formatDistance = (km) => {
const d = Number(km);
if (!(d >= 0)) return '';
if (d >= 1) return `${d.toFixed(1)}km`;
return `${Math.round(d * 1000)}m`;
};
const formatAddress = (item) => {
const district = item?.district || '';
const description = item?.description || '';
const address = item?.address || '';
return `${district}${description ? ` ${description}` : ''}${address ? ` ${address}` : ''}`.trim();
};
const formatHm = (hm) => {
if (!Array.isArray(hm) || hm.length < 2) return '';
const h = String(hm[0]).padStart(2, '0');
const m = String(hm[1]).padStart(2, '0');
return `${h}:${m}`;
};
const formatBusinessHours = (item) => {
const start =
item?.openingTime || formatHm(item?.businessHoursStart) || item?.businessHoursStart || '';
const end = item?.closingTime || formatHm(item?.businessHoursEnd) || item?.businessHoursEnd || '';
if (!start || !end) return '';
return `${start}-${end}`;
};
const STORE_STATUS_TEXT = { 1: '营业中', 2: '休息中', 3: '停用' };
const STORE_STATUS_LEVEL = { 1: 'open', 2: 'rest', 3: 'closed' };
const getStoreStatusText = (status) => STORE_STATUS_TEXT[Number(status)] || '';
const getStoreStatusLevel = (status) => STORE_STATUS_LEVEL[Number(status)] || 'closed';
const isStoreOpen = (item) => Number(item?.status) === 1;
const sortStoreList = (list = []) => {
const STATUS_WEIGHT = { 1: 0, 2: 1, 3: 2 };
return [...list].sort((a, b) => {
const wa = STATUS_WEIGHT[Number(a?.status)] ?? 99;
const wb = STATUS_WEIGHT[Number(b?.status)] ?? 99;
if (wa !== wb) return wa - wb;
const da = Number(a?.distance);
const db = Number(b?.distance);
if (da >= 0 && db >= 0) return da - db;
return 0;
});
};
const filteredStoreList = computed(() => {
const list = Array.isArray(state.storeList) ? state.storeList : [];
const kw = String(state.keyword || '').trim();
const raw = !kw
? list
: list.filter((item) => {
const s = `${item?.name || ''} ${formatAddress(item)}`.toLowerCase();
return s.includes(kw.toLowerCase());
});
return sortStoreList(raw);
});
const selectedStore = computed(() => {
const id = Number(state.selectedStoreId || 0);
if (!(id > 0)) return filteredStoreList.value?.[0] || null;
return (filteredStoreList.value || []).find((o) => Number(o?.id) === id) || filteredStoreList.value?.[0] || null;
});
const sanitizeUrl = (value) => String(value || '').replace(/[`"'\s]/g, '');
const normalizeImageUrl = (value) => {
const raw = sanitizeUrl(value);
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) return raw;
return sheep.$url.cdn(raw);
};
const getMarkerKey = (id, active) => `${id}_${active ? 'active' : 'inactive'}`;
const getImageTempPath = (url) =>
new Promise((resolve) => {
if (!url) {
resolve('');
return;
}
if (!/^https?:\/\//i.test(url)) {
resolve(url);
return;
}
uni.downloadFile({
url,
success: (res) => {
resolve(res.statusCode === 200 ? res.tempFilePath || '' : '');
},
fail: () => resolve(''),
});
});
const renderMarkerIcon = async (item, active = false) => {
const id = Number(item?.id || 0);
const key = getMarkerKey(id, active);
if (!(id > 0) || state.markerIconMap[key]) return state.markerIconMap[key] || '';
const imageUrl = normalizeImageUrl(item?.coverImage || item?.logo);
if (!imageUrl) return '';
const tempPath = await getImageTempPath(imageUrl);
if (!tempPath) return '';
const size = 88;
const ring = 6;
const innerSize = size - ring * 2;
const radius = size / 2;
const innerRadius = innerSize / 2;
const ctx = uni.createCanvasContext('storeMarkerCanvas', proxy);
return new Promise((resolve) => {
ctx.clearRect(0, 0, size, size);
ctx.beginPath();
ctx.arc(radius, radius, radius, 0, Math.PI * 2);
ctx.setFillStyle(active ? '#2556EC' : '#C8CDD9');
ctx.fill();
ctx.save();
ctx.beginPath();
ctx.arc(radius, radius, innerRadius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(tempPath, ring, ring, innerSize, innerSize);
ctx.restore();
ctx.draw(false, () => {
uni.canvasToTempFilePath(
{
canvasId: 'storeMarkerCanvas',
x: 0,
y: 0,
width: size,
height: size,
destWidth: size * 2,
destHeight: size * 2,
success: (res) => {
const path = res?.tempFilePath || '';
if (path) {
state.markerIconMap[key] = path;
}
resolve(path);
},
fail: () => resolve(''),
},
proxy,
);
});
});
};
const prepareMarkerIcons = async (list = []) => {
for (const item of list) {
await renderMarkerIcon(item, false);
}
};
const ensureDefaultSelectedStore = async (list = []) => {
const stores = Array.isArray(list) && list.length ? list : filteredStoreList.value;
if (!stores.length) return null;
const openStores = stores.filter((o) => isStoreOpen(o));
const candidates = openStores.length ? openStores : stores;
let target = null;
if (Number(state.selectedStoreId) > 0) {
target = candidates.find((o) => Number(o?.id || 0) === Number(state.selectedStoreId));
}
if (!target) {
target =
candidates.find((o) => Number(o?.latitude) && Number(o?.longitude)) || candidates[0];
state.selectedStoreId = isStoreOpen(target) ? Number(target?.id || 0) : 0;
}
if (target && isStoreOpen(target)) {
const lat = Number(target?.latitude);
const lon = Number(target?.longitude);
if (lat && lon) {
state.mapLatitude = lat;
state.mapLongitude = lon;
}
await renderMarkerIcon(target, true);
}
return isStoreOpen(target) ? target : null;
};
const markers = computed(() => {
return filteredStoreList.value
.filter((item) => Number(item?.latitude) && Number(item?.longitude))
.map((item) => {
const id = Number(item?.id || 0);
const active = id === Number(state.selectedStoreId);
const inactiveIcon = state.markerIconMap[getMarkerKey(id, false)];
const activeIcon = state.markerIconMap[getMarkerKey(id, true)];
return {
id,
latitude: Number(item.latitude),
longitude: Number(item.longitude),
iconPath: active
? activeIcon || '/static/transparent_bg.png'
: inactiveIcon || '/static/transparent_bg.png',
width: active ? 44 : 32,
height: active ? 44 : 32,
callout: {
content: String(item?.name || ''),
display: active ? 'ALWAYS' : 'BYCLICK',
padding: 6,
borderRadius: 8,
bgColor: '#ffffff',
color: '#333333',
fontSize: 12,
},
};
});
});
const onMarkerTap = (e) => {
const markerId = Number(e?.markerId || 0);
if (!(markerId > 0)) return;
const target = (filteredStoreList.value || []).find((o) => Number(o?.id) === markerId);
if (target) {
onSelect(target);
}
};
/**
* 获取门店列表数据
*/
const getList = async () => {
if (state.loading || state.loaded) {
return;
}
const hasLocation = !!(state.user_latitude && state.user_longitude);
state.loading = true;
const { data, code } = await StoreApi.getStoreListByLocation({
latitude: state.user_latitude,
longitude: state.user_longitude,
});
if (code !== 0) {
state.loading = false;
return;
}
state.loading = false;
state.loaded = hasLocation;
state.storeList = Array.isArray(data) ? data : [];
await ensureDefaultSelectedStore(state.storeList);
prepareMarkerIcons(state.storeList);
};
onMounted(() => {
if (state.user_latitude && state.user_longitude) {
getList();
} else {
selfLocation();
getList();
}
});
onLoad(() => {
try {
state.user_latitude = uni.getStorageSync(LATITUDE);
state.user_longitude = uni.getStorageSync(LONGITUDE);
state.mapLatitude = state.user_latitude;
state.mapLongitude = state.user_longitude;
} catch (e) {
console.error(e);
}
});
onShow(() => {
ensureDefaultSelectedStore();
});
</script>
<style lang="scss" scoped>
.line2 {
display: -webkit-box;
line-clamp: 2;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.geoPage {
position: fixed;
width: 100%;
height: 100%;
top: 0;
z-index: 10000;
}
.store-page {
background: #fff;
padding: 0 30rpx 30rpx;
}
.search-bar {
padding: 20rpx 0 10rpx;
}
.search-inner {
display: flex;
align-items: center;
height: 72rpx;
padding: 0 20rpx;
border-radius: 18rpx;
background: #f6f7f9;
box-sizing: border-box;
}
.search-icon {
width: 28rpx;
height: 28rpx;
margin-right: 12rpx;
opacity: 0.7;
}
.map-card {
position: relative;
border-radius: 20rpx;
overflow: hidden;
background: #f6f7f9;
}
.map {
width: 100%;
height: 460rpx;
}
.map-center-marker {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, 8rpx);
display: flex;
flex-direction: column;
align-items: center;
pointer-events: none;
}
.map-center-marker__label {
margin-top: 0;
padding: 8rpx 14rpx;
border-radius: 10rpx;
background: rgba(0, 0, 0, 0.72);
color: #fff;
font-size: 22rpx;
line-height: 1;
max-width: 360rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.marker-canvas {
position: fixed;
left: -9999px;
top: -9999px;
width: 88px;
height: 88px;
opacity: 0;
pointer-events: none;
}
.list-hd {
display: flex;
align-items: baseline;
justify-content: space-between;
padding: 22rpx 0 10rpx;
}
.list-title {
font-size: 30rpx;
font-weight: 700;
color: #222;
}
.list-sub {
font-size: 24rpx;
color: #666;
}
.store-item {
position: relative;
padding: 22rpx 22rpx 20rpx;
border-radius: 18rpx;
background: #ffffff;
box-shadow: 0 10rpx 28rpx rgba(0, 0, 0, 0.06);
margin-top: 18rpx;
border: 2rpx solid transparent;
}
.store-item--active {
border-color: rgba(37, 86, 236, 0.35);
box-shadow: 0 14rpx 34rpx rgba(37, 86, 236, 0.16);
}
.store-item__hd {
display: flex;
align-items: center;
}
.store-badge {
height: 36rpx;
padding: 0 12rpx;
border-radius: 999rpx;
background: rgba(37, 86, 236, 0.12);
color: #2556ec;
font-size: 22rpx;
line-height: 36rpx;
margin-right: 14rpx;
}
.store-name {
flex: 1;
font-size: 30rpx;
font-weight: 700;
color: #222;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.store-distance {
font-size: 24rpx;
color: #666;
margin-left: 10rpx;
}
.store-status {
height: 32rpx;
padding: 0 12rpx;
border-radius: 999rpx;
font-size: 20rpx;
line-height: 32rpx;
margin-left: 12rpx;
flex-shrink: 0;
}
.store-status--open {
background: rgba(18, 180, 107, 0.12);
color: #12b46b;
}
.store-status--rest {
background: rgba(255, 159, 67, 0.12);
color: #ff9f43;
}
.store-status--closed {
background: rgba(153, 153, 153, 0.12);
color: #999;
}
.store-address {
margin-top: 10rpx;
font-size: 24rpx;
color: #666;
line-height: 34rpx;
}
.store-item__ft {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 14rpx;
}
.store-hours {
flex: 1;
min-width: 0;
height: 56rpx;
line-height: 56rpx;
font-size: 22rpx;
color: #12b46b;
margin-right: 14rpx;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.store-actions {
display: flex;
align-items: center;
flex-shrink: 0;
}
.btn {
height: 56rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: #2556ec;
color: #fff;
font-size: 24rpx;
line-height: 56rpx;
margin-left: 14rpx;
flex-shrink: 0;
}
.btn--ghost {
background: rgba(37, 86, 236, 0.12);
color: #2556ec;
margin-left: 0;
}
</style>