import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro'
import React, { useEffect, useState, useMemo } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { useImmer } from 'use-immer'
import qs from 'qs'
import api from '@/api'
import doc from '@/doc'
import { navigateTo, pickBy, classNames, throttle } from '@/utils'
import { useLogin, useDepChange, useDebounce } from '@/hooks'
import { fetchCartList, deleteCartItem, updateCartItemNum, updateCount } from '@/store/slices/cart'
import {
SpPage,
SpTabbar,
SpPrice,
SpRecommend,
SpLogin,
SpDefault,
SpCheckboxNew,
SpPrivacyModal,
SpImage,
SpGoodsItem
} from '@/components'
import CompGoodsItem from './comps/comp-goodsitem'
import './espier-index.scss'
// const tablist = [
// { title: '普通商品', icon: 'icon-putongshangpin-01', type: 'normal' },
// { title: '跨境商品', icon: 'icon-kuajingshangpin-01', type: 'cross' }
// ]
const initialState = {
recommendList: [], // 猜你喜欢
current: 0, // 0:普通商品 1:跨境商品
policyModal: false, // 隐私弹框
loading: false
}
function CartIndex () {
const { isLogin } = useLogin({
autoLogin: true,
policyUpdateHook: (isUpdate) => {
isUpdate && onPolicyChange(true)
}
})
const dispatch = useDispatch()
const $instance = getCurrentInstance()
const router = $instance.router
const [state, setState] = useImmer(initialState)
const { current, recommendList, policyModal, loading } = state
const { colorPrimary, openRecommend } = useSelector((state) => state.sys)
const { validCart = [], invalidCart = [], cartCount } = useSelector((state) => state.cart)
const { tabbar = 1 } = router?.params || {}
// useDepChange(() => {
// fetch()
// }, [isLogin])
useEffect(() => {
if (isLogin) fetch()
}, [isLogin])
useDidShow(() => {
if (isLogin) fetch()
})
const fetch = () => {
if (openRecommend == 1) {
}
getRecommendList() // 猜你喜欢
if (isLogin) {
getCartList()
}
}
const getCartList = async () => {
// Taro.showLoading({ title: '', })
// setState((draft) => {
// draft.loading = true
// })
const { type = 'distributor' } = router?.params || {}
const params = {
shop_type: type
}
await dispatch(fetchCartList(params))
await dispatch(updateCount(params))
Taro.hideLoading()
setState((draft) => {
draft.loading = false
})
}
const resolveActiveGroup = () => {
const groupsList = validCart.map((item) => {
// used_activity:满减 activity_grouping:满减&满折 gift_activity:满赠 plus_buy_activity:加价购
const {
list,
used_activity = [],
plus_buy_activity = [],
activity_grouping = [],
gift_activity = []
} = item
// 使用活动商品
// const tDict = reduceTransform(list, 'cart_id')
// const activityGrouping = activity_grouping;
// const cus_activity_list = used_activity.map(act => {
// const active = activityGrouping.find(a_item => String(a_item.activity_id) === String(act.activity_id))
// const cus_general_goods_list = active.cart_ids.map(id => {
// const cartItem = tDict[id]
// delete tDict[id]
// return cartItem
// })
// return { list: cus_general_goods_list, active }
// })
// console.log(cus_activity_list, 'cus_activity_list')
// cus_activity_list.push({ list: Object.values(tDict), active: null })
// 加购价
let all_plus_itemid_list = [] // 加价购商品id
let no_active_item = [] // 没有活动的商品
let cus_plus_item_list = plus_buy_activity.map((plusitem, index) => {
const { plus_item, activity_item_ids, activity_id } = plusitem
// 加购价换购的商品
let exchange_item = null
if (plus_item) {
exchange_item = pickBy(plus_item, { ...doc.cart.PLUS_BUY_ITEM, activity_id })
}
all_plus_itemid_list.push(activity_item_ids)
const general_goods = list.filter((k) => activity_item_ids.indexOf(k.item_id) > -1)
return {
...plusitem,
cus_general_goods_list: general_goods,
cus_plus_exchange_item_list: exchange_item
}
})
all_plus_itemid_list = all_plus_itemid_list.toString().split(',')
const goodsMap = reduceTransform(list, 'cart_id')
for (const key in goodsMap) {
if (all_plus_itemid_list.indexOf(goodsMap[key].item_id) < 0) {
no_active_item.push(goodsMap[key])
}
}
cus_plus_item_list.push({
discount_desc: null,
cus_general_goods_list: no_active_item.reverse(),
cus_plus_exchange_item_list: null
})
return {
...item,
cus_plus_item_list
// cus_activity_list
}
})
return groupsList || []
}
const reduceTransform = (list, label) => {
const newList = list.reduce((acc, val) => {
acc[val[label]] = val
return acc
}, {})
return newList
}
const getRecommendList = async () => {
const { list } = await api.cart.likeList({
page: 1,
pageSize: 1000
})
setState((draft) => {
draft.recommendList = list
})
}
// const onChangeSpTab = (current) => {
// setState(draft => {
// draft.current = current
// })
// // setState({
// // ...state,
// // current
// // })
// }
const onChangeGoodsIsCheck = async (item, type, checked) => {
Taro.showLoading({ title: '', mask: true })
// setState((draft) => {
// draft.loading = true
// })
let parmas = { is_checked: checked }
if (type === 'all') {
const cartIds = item.list.map((item) => item.cart_id)
parmas['cart_id'] = cartIds
} else {
parmas['cart_id'] = item.cart_id
}
try {
await api.cart.select(parmas)
} catch (e) {
console.log(e)
}
getCartList()
}
const onDeleteCartGoodsItem = async ({ cart_id }) => {
const res = await Taro.showModal({
title: '提示',
content: '将当前商品移出购物车?',
showCancel: true,
cancel: '取消',
cancelText: '取消',
confirmText: '确认',
confirmColor: colorPrimary
})
if (!res.confirm) return
await dispatch(deleteCartItem({ cart_id }))
getCartList()
}
const onChangeCartGoodsItem = useDebounce(async (item, num) => {
console.log(`onChangeCartGoodsItem:`, num)
// setState((draft) => {
// draft.loading = true
// })
Taro.showLoading({ title: '', mask: true })
let { shop_id, cart_id } = item
const { type = 'distributor' } = router.params
await dispatch(updateCartItemNum({ shop_id, cart_id, num, type }))
getCartList()
}, 200)
const onClickImgAndTitle = async (item) => {
Taro.navigateTo({
url: `/pages/item/espier-detail?id=${item.item_id}&dtid=${item.shop_id}`
})
}
const onPolicyChange = (isShow = false) => {
setState((draft) => {
draft.policyModal = isShow
})
}
const handleCheckout = (item) => {
const { type = 'distributor' } = router.params
const { shop_id, is_delivery, is_ziti, shop_name, address, lat, lng, hour, mobile } = item
const query = {
cart_type: 'cart',
type,
shop_id,
is_delivery,
is_ziti,
name: shop_name,
store_address: address,
lat,
lng,
hour,
phone: mobile,
goodType: current == 0 ? 'normal' : 'cross'
}
Taro.navigateTo({
url: `/pages/cart/espier-checkout?${qs.stringify(query)}`
})
}
const groupsList = resolveActiveGroup()
const handleClickStore = (item) => {
const url = `/subpages/store/index?id=${item.distributor_info?.distributor_id || item.goods_id}`
Taro.navigateTo({
url
})
}
return (
}
showLogoLoading={loading}
showNavLogo isBlack showNavkfIcon
>
{/* {!isLogin && (
授权登录后同步购物车的商品
{ }}>
授权登录
)} */}
{!loading && isLogin && groupsList?.length > 0 && (
{/* */}
{groupsList.map((all_item, all_index) => {
const { cus_plus_item_list = [], activityList = [] } = all_item || {}
const allChecked = all_item.cart_total_count == all_item.list.length
return (
{/* */}
{/* {all_item.shop_name || '自营'} */}
购物车
{/* 共{all_item.cart_total_num}件 */}
共{cartCount}件
{/** 店铺商品开始 */}
{cus_plus_item_list.map((cus_item, cus_index) => {
const {
discount_desc,
activity_id,
cus_general_goods_list,
cus_plus_exchange_item_list
} = cus_item
return (
{/** 换购开始 */}
{discount_desc && (
Taro.navigateTo({
url: `/marketing/pages/plusprice/detail-plusprice-list?marketing_id=${activity_id}`
})
}
>
换购
{discount_desc.info}
Taro.navigateTo({
url: `/marketing/pages/plusprice/cart-plusprice-list?marketing_id=${activity_id}`
})
}
>
去选择
)}
{/** 换购结束 */}
{/**普通商品开始 */}
{cus_general_goods_list.map((c_sitem, c_index) => (
{/**组合商品开始 */}
{c_sitem.packages &&
c_sitem.packages.map((pack_sitem, pack_index) => (
))}
{/**组合商品开始 */}
))}
{/**普通商品开始 */}
{/**换购商品开始 */}
{cus_plus_exchange_item_list && (
)}
{/**换购商品开始 */}
)
})}
{/** 店铺商品结束 */}
{/** 结算/全选操作开始 */}
{/* 共{all_item.cart_total_num}件 */}
共{cartCount}件
{/* 合计: */}
{all_item.discount_fee > 0 && (
共优惠:
)}
handleCheckout(all_item)}
>
立即结算
{/** 结算/全选操作开始 */}
)
})}
{false && invalidCart.length > 0 && (
已失效商品
{invalidCart.map((sitem, sindex) => (
))}
)}
)}
{/* && invalidCart.length == 0 */}
{!loading && validCart.length == 0 && (
{/*
去选购
*/}
购物车还是空的
快去挑选自己喜欢的宝贝吧~
{ }}>
前往选购
)}
{false &&
{validCart.length == 0 && invalidCart.length == 0 ? '商品推荐' : '专属推荐'}
{[
{
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'
},
].map((item, idx) => (
))}
}
{/* 猜你喜欢 */}
{/* */}
{/* */}
)
}
export default CartIndex