import React, { useEffect, useState, useCallback } from 'react'
import Taro, {
getCurrentInstance,
useShareAppMessage,
useShareTimeline,
useDidShow,
usePageScroll,
usePullDownRefresh
} from '@tarojs/taro'
import { View, Image, Swiper, SwiperItem, Video, ScrollView } from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import {
SpScreenAd,
SpPage,
SpSearch,
SpRecommend,
SpTabbar,
SpCouponPackage,
SpNavBar,
SpImage,
SpGoodsItem,
SpChat,
SpLogin
} from '@/components'
import api from '@/api'
import {
isWeixin,
isAPP,
isEmpty,
getDistributorId,
VERSION_STANDARD,
VERSION_PLATFORM,
VERSION_IN_PURCHASE,
VERSION_B2C,
classNames,
getCurrentPageRouteParams,
resolveStringifyParams
} from '@/utils'
import entryLaunch from '@/utils/entryLaunch'
import { updateLocation } from '@/store/slices/user'
import { updateShopInfo } from '@/store/slices/shop'
import { useImmer } from 'use-immer'
import { useLogin, useNavigation } from '@/hooks'
import HomeWgts from './home/comps/home-wgts'
import { WgtHomeHeader, WgtHomeHeaderShop } from './home/wgts'
// import CompAddTip from './home/comps/comp-addtip'
// import CompFloatMenu from './home/comps/comp-floatmenu'
import './home/index.scss'
// const MCompAddTip = React.memo(CompAddTip)
const initialState = {
wgts: [],
showBackToTop: false,
loading: false,
searchComp: null,
pageData: null,
fixedTop: false,
filterWgts: [],
isShowHomeHeader: false,
swiperList: [],
list: [
{
type: 'image',
src: process.env.APP_IMAGE_CDN_NEW + '/index/22.jpg'
},
{
type: 'image',
// src: '//img10.360buyimg.com/ling/jfs/t1/181258/24/10385/53029/60d04978Ef21f2d42/92baeb21f907cd24.jpg'
src: process.env.APP_IMAGE_CDN_NEW + '/index/33.jpg'
},
{
type: 'video',
src: 'https://espier-oss-cdn.oss-cn-shanghai.aliyuncs.com/default_project/wxAssets/index/video-1.mp4'
}
],
length: 2,
showBottom: false,
scrollTop: 0,
isUpOperation: false,
showRecommend: false,
currentIndex: 0,
shopList: [
{
brief: "副标题",
itemName: "测试商品1",
price: "1099",
goods_id: 6,
pic: 'https://espier-oss-cdn.oss-cn-shanghai.aliyuncs.com/default_project/image/1/2024/01/15/46fe6ca52277038e39ee2c026a4af3c9xHQuJ96YIcZWtjRS0HBCTzp7dzXIs2pl'
},
{
brief: "副标题",
itemName: "测试商品2",
price: "1099",
goods_id: 6,
pic: 'https://espier-oss-cdn.oss-cn-shanghai.aliyuncs.com/default_project/image/1/2024/01/15/801c18d59d95ea26930fefc43bf66febTQjxb65cpnCqVLaOsYmiHdkDdYqBnXVm'
},
{
brief: "副标题",
itemName: "测试商品3",
price: "1099",
goods_id: 6,
pic: 'https://espier-oss-cdn.oss-cn-shanghai.aliyuncs.com/default_project/image/1/2024/01/15/46fe6ca52277038e39ee2c026a4af3c90XruENsSSAhRiz0HPI3PjR8XQNVgbxHb'
},
],
goodList: [],
recommend: [],
activeInfo: {},
muted: true,
}
function Home () {
const [state, setState] = useImmer(initialState)
const [startY, setStartY] = useState(0)
const [startX, setStartX] = useState(0)
const [likeList, setLikeList] = useImmer([])
const { isLogin, isNewUser } = useLogin()
const { initState, openRecommend, openLocation, openStore, appName, openScanQrcode } = useSelector(
(state) => state.sys
)
const { shopInfo } = useSelector(
(state) => state.shop
)
const showAdv = useSelector((member) => member.user.showAdv)
const { location } = useSelector((state) => state.user)
const { setNavigationBarTitle } = useNavigation()
const { windowWidth } = Taro.getSystemInfoSync()
const imgW = parseFloat(((windowWidth * 2 - 60 - 32) / 3).toFixed(4))
const { wgts, loading, searchComp, pageData, fixedTop, filterWgts, isShowHomeHeader, isUpOperation, showRecommend, shopList, swiperList, goodList, recommend } = state
const dispatch = useDispatch()
useEffect(() => {
if (initState) {
init()
setNavigationBarTitle(appName)
getSwiperList()
getRecommendItems()
}
}, [initState])
// useEffect(() => {
// if (shopInfo && VERSION_STANDARD) {
// fetchWgts()
// }
// }, [shopInfo])
// useEffect(() => {
// if (location && VERSION_STANDARD) {
// fetchWgts()
// }
// }, [location])
useShareAppMessage(async (res) => {
const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
let params = getCurrentPageRouteParams()
const dtid = getDistributorId()
if (dtid && !('dtid' in params)) {
params = Object.assign(params, { dtid })
}
let path = `/pages/index${isEmpty(params) ? '' : '?' + resolveStringifyParams(params)}`
console.log('useShareAppMessage path:', path, params)
return {
title: title,
imageUrl: imageUrl,
path
}
})
useShareTimeline(async (res) => {
const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
let params = getCurrentPageRouteParams()
const dtid = getDistributorId()
if (dtid && !('dtid' in params)) {
params = Object.assign(params, { dtid })
}
return {
title: title,
imageUrl: imageUrl,
query: resolveStringifyParams(params)
}
})
const init = async () => {
fetchLocation()
// 非云店
if (!VERSION_STANDARD) {
// fetchWgts()
} else {
fetchStoreInfo(location)
}
}
const getRecommendItems = async () => {
const req = {
page: 1,
pageSize: 10,
approve_status: 'onsale',
approve_status: 'onsale,only_show',
item_type: 'normal',
is_point: false,
// goodsSort: 6,
distributor_id: 0
}
// const { list: jdList } = await api.item.search({ ...req, tag_id: 1 })
const { list: newList = [] } = await api.item.search({ ...req, tag_id: 4 })
const { list: hotList = [] } = await api.item.search({ ...req, tag_id: 3 })
const { list: BOSTON_List = [] } = await api.item.search({ ...req, tag_id: 5 })
const { list: ARIZONA_List = [] } = await api.item.search({ ...req, tag_id: 6 })
const { list: LONDON_List = [] } = await api.item.search({ ...req, tag_id: 7 })
const newSort = {
"BK023": 1,
"BK066": 2,
"BK053": 3,
"BK038": 4,
"BK064": 5,
"BK014": 6
}
const hotSort = {
"BK014": 1,
"BK031": 2,
"BK018": 3,
"BK020": 4,
"BK052": 5,
"BK064": 6,
}
const BOSTON_sort = {
"BK020": 1,
"BK023": 2,
"BK025": 3,
"BK029": 4,
"BK030": 5,
"BK031": 6,
}
const ARIZONA_sort = {
"BK001": 1,
"BK017": 2,
"BK007": 3,
"BK010": 4,
"BK011": 5,
"BK014": 6,
}
const LONDON_sort = {
"BK052": 1,
"BK053": 2,
"BK051": 3,
}
setState((draft) => {
draft.recommend = [{
type: 'new',
text: "新品推荐",
btnTxt: '查看更多',
postions: 'left',
url: '',
tag_id: 4,
img: 'index/rec/new.png?v=1',
list: newList.map(item => ({ ...item, price: (item.price / 100) })).sort((a, b) => {
return newSort[a.item_name_3] - newSort[b.item_name_3]
})
}, {
type: 'hot',
text: "热销单品",
btnTxt: '查看更多',
postions: 'left',
url: '',
tag_id: 3,
img: 'index/rec/hot.png?v=1',
list: hotList.map(item => ({ ...item, price: (item.price / 100) })).sort((a, b) => {
return hotSort[a.item_name_3] - hotSort[b.item_name_3]
})
}, {
type: 'BOSTON',
text: "BOSTON",
btnTxt: 'BOSTON',
postions: 'left',
url: '',
tag_id: 5,
img: 'index/rec/Boston.png',
list: BOSTON_List.map(item => ({ ...item, price: (item.price / 100) })).sort((a, b) => {
return BOSTON_sort[a.item_name_3] - BOSTON_sort[b.item_name_3]
})
}, {
type: 'ARIZONA',
text: "ARIZONA",
btnTxt: 'ARIZONA',
url: '',
postions: 'left',
tag_id: 6,
img: 'index/rec/Arizona.png',
list: ARIZONA_List.map(item => ({ ...item, price: (item.price / 100) })).sort((a, b) => {
return ARIZONA_sort[a.item_name_3] - ARIZONA_sort[b.item_name_3]
})
}, {
type: 'LONDON',
text: "LONDON",
btnTxt: 'LONDON',
url: '',
postions: 'left',
tag_id: 7,
img: 'index/rec/London.png',
list: LONDON_List.map(item => ({ ...item, price: (item.price / 100) })).sort((a, b) => {
return LONDON_sort[a.item_name_3] - LONDON_sort[b.item_name_3]
})
}
]
// bak
// draft.recommend = [{
// type: 'new',
// text: "新品推荐",
// btnTxt: '查看更多',
// postions: 'left',
// url: '',
// img: 'index/rec/new.png',
// list: newList.map(item => ({ ...item, price: (item.price / 100) }))
// }, {
// type: 'hot',
// text: "热销单品",
// btnTxt: '查看更多',
// postions: 'left',
// url: '',
// img: 'index/rec/hot.png',
// list: hotList.map(item => ({ ...item, price: (item.price / 100) }))
// }, {
// type: 'jd',
// text: "ARIZONA",
// btnTxt: '经典双扣',
// postions: 'right',
// url: '',
// img: 'index/rec/jd.png',
// list: jdList.map(item => ({ ...item, price: (item.price / 100) }))
// }
// ]
})
}
const getSwiperList = async () => {
// const { status, activity_info = {}, total_count } = await api.user.registrationActivity({ activity_id: 1 })
// const activeSwiper = activity_info.pics.map(item => ({
// type: 'image',
// src: item,
// goods: []
// }))
const res = await api.shop.homeSwiperList({ page: 1, pageSize: 999 })
const list = (res?.list?.map((item) => {
return {
type: item.type || 'image',
src: item.pic,
sort: item.sort,
goods: (item.goods_info_detail || []).map((ite) => {
return {
itemName: ite.item_name,
goods_id: ite.item_id,
itemId: ite.item_id,
pic: ite.pics?.[0],
brief: ite.brief,
price: ite.price ? ite.price / 100 : 0,
spec_images: ite.spec_images || [],
tagList: ite.tagList || []
}
})
}
}) || []).sort((a, b) => a.sort - b.sort)
setState((draft) => {
// draft.swiperList = [...activeSwiper, ...list]
draft.swiperList = list
draft.goodList = list[0].goods || []
draft.loading = false
// draft.activeInfo = {
// ...activity_info,
// total_count,
// status
// }
})
}
const fetchWgts = async () => {
setState((draft) => {
draft.wgts = []
draft.pageData = []
draft.filterWgts = []
draft.loading = true
})
const { config } = await api.shop.getShopTemplate({
distributor_id: getDistributorId()
})
const searchComp = config.find((wgt) => wgt.name == 'search')
const pageData = config.find((wgt) => wgt.name == 'page')
let filterWgts = []
if (searchComp && searchComp.config.fixTop) {
filterWgts = config.filter((wgt) => wgt.name !== 'search' && wgt.name != 'page')
} else {
filterWgts = config.filter((wgt) => wgt.name != 'page')
}
const fixedTop = searchComp && searchComp.config.fixTop
const isShowHomeHeader =
VERSION_PLATFORM ||
(openScanQrcode == 1 && isWeixin) ||
(VERSION_STANDARD && openStore && openLocation == 1) ||
fixedTop
setState((draft) => {
draft.wgts = config
draft.searchComp = searchComp
draft.pageData = pageData
draft.fixedTop = fixedTop
draft.isShowHomeHeader = isShowHomeHeader
draft.filterWgts = filterWgts
draft.loading = false
})
}
const fetchLikeList = async () => {
if (openRecommend == 1) {
const query = {
page: 1,
pageSize: 30
}
const { list } = await api.cart.likeList(query)
setLikeList(list)
}
}
// 定位
const fetchLocation = () => {
if (!location && ((VERSION_STANDARD && openLocation == 1) || VERSION_PLATFORM)) {
try {
entryLaunch.isOpenPosition((res) => {
if (res.lat) {
dispatch(updateLocation(res))
}
})
} catch (e) {
console.error('map location fail:', e)
}
}
}
const fetchStoreInfo = async (location) => {
let params = {
distributor_id: getDistributorId() // 如果店铺id和经纬度都传会根据哪个去定位传参
}
if (openLocation == 1 && location) {
const { lat, lng } = location
params.lat = lat
params.lng = lng
// params.distributor_id = undefined
}
const res = await api.shop.getShop(params)
dispatch(updateShopInfo(res))
}
const handleTouchStart = (e) => {
const { clientY, clientX } = e.touches[0]
setStartY(clientY)
setStartX(clientX)
}
const handleTouchEnd = (e) => {
const { clientX, clientY } = e.changedTouches[0]
const deltaY = clientY - startY
const deltaX = clientX - startX
if (Math.abs(deltaY) < 50) return
if (deltaY > 0) {
// 下滑操作
setState((draft) => {
draft.showBottom = false
draft.showRecommend = false
})
if (state.showBottom) {
setTimeout(() => {
setState((draft) => {
draft.isUpOperation = false
})
}, 500)
}
} else if (deltaY < 0) {
// if (currentIndex === 0) return
// 上滑操作
setState((draft) => {
draft.showBottom = true
draft.isUpOperation = true
})
setTimeout(() => {
setState((draft) => {
draft.showRecommend = true
})
}, 1000)
if (!state.showBottom) {
}
}
}
const [recommendTouch, setRecommendTouch] = useImmer({
recommendStartY: 0,
recommendStartX: 0,
recommendEndY: 0,
recommendEndX: 0,
})
const onRecommendTouch = (e) => {
const { clientY, clientX } = e.touches[0]
setRecommendTouch(v => v.recommendStartX = clientX)
setRecommendTouch(v => v.recommendStartY = clientY)
}
const onRecommendTouchEnd = (e) => {
const { clientY, clientX } = e.changedTouches[0]
const { recommendStartY, recommendStartX } = recommendTouch
const deltaY = clientY - recommendStartY
const deltaX = clientX - recommendStartX
if (Math.abs(deltaY) < 50) return
if (deltaY > 0) {
// 下滑操作
console.log("🚀 ~ file: index.js:456 ~ 下滑操作:", '下滑操作')
} else if (deltaY < 0) {
// 上滑操作
console.log("🚀 ~ file: index.js:460 ~ 上滑操作:", '上滑操作')
}
}
const onSwiperChange = (e) => {
const { current } = e.detail
// if (current === 0) {
// setState((draft) => {
// draft.showBottom = false
// draft.isUpOperation = false
// })
// }
setState((draft) => {
draft.currentIndex = current
draft.goodList = swiperList[current].goods || []
})
}
const handleClickStore = (item) => {
const url = `/subpages/store/index?id=${item.distributor_info?.distributor_id || item.goods_id}`
Taro.navigateTo({
url
})
}
const { activeInfo = {}, currentIndex } = state
const handleApply = () => {
// if (!isLogin) return
let url = '/pages/recommend/detail?id='
if (activeInfo.total_count) {
url = `/pages/recommend/status?id=`
}
Taro.navigateTo({
url: url + activeInfo.activity_id
})
}
const handleGoRecommendGoods = (item) => {
const url = `/pages/item/list?tag_id=${item.tag_id || ''}`
Taro.navigateTo({
url: url
})
}
return (
}
// pageConfig={pageData?.base}
// renderFloat={wgts.length > 0 && }
renderFooter={}
loading={loading}
isTop={!isUpOperation}
isBlack
>
{false &&
{isShowHomeHeader && {fixedTop && }}
{
filterWgts.length > 0 &&
{/* 猜你喜欢 */}
}
}
{/* 小程序搜藏提示 */}
{/* {isWeixin && } */}
{/* 开屏广告 */}
{/* {isWeixin && !showAdv && } */}
{/* 优惠券包 */}
{/* {VERSION_STANDARD && } */}
{/* */}
{state.swiperList.map((item, index) => (
{item.type === "image" && (
//
)}
{item.type === "video" && (
))}
{!isUpOperation && <>
滑 动 探 索
{swiperList.map((_, index) => (
))}
>}
{isUpOperation &&
}
{isUpOperation &&
{goodList.map((item, idx) => (
))}
}
{/* 推荐图片+商品 isUpOperation && */}
{isUpOperation && showRecommend && <>
{recommend.length > 0 && recommend.map((_item, id) =>
= 400 ? 920 : 800} mode='scaleToFill' src={_item.img} isShowMenuByLongpress={false} lazyLoad isNew >
handleGoRecommendGoods(_item)} className="recommend_btn" style={{ [_item.postions]: '70rpx', opacity: 0 }}>
{_item.text}
{_item.btnTxt}
{_item.list?.map((item, idx) => (
))}
)}
>}
{isUpOperation && showRecommend &&
Taro.navigateTo({
url: '/pages/home/story'
})} isShowMenuByLongpress={false} lazyLoad isNew>
{/* */}
{/*
Taro.navigateTo({
url: '/pages/webview?url=' + encodeURIComponent('https://www.baidu.com')
})} width={windowWidth * 2 - 60} mode='widthFix' src="index/story/more.png" isShowMenuByLongpress={false} lazyLoad isNew>
*/}
}
{false && isUpOperation && showRecommend &&
品牌介绍
Taro.navigateTo({
url: '/pages/webview?url=' + encodeURIComponent('https://www.baidu.com')
})} className="brand-guanzhu" mode="widthFix" src="index/guanzhu.png" isShowMenuByLongpress={false} lazyLoad isNew>
订阅消息
{/* */}
}
{/* */}
)
}
export default Home