123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699 |
- //@ts-ignore
- import Toast from 'tdesign-miniprogram/toast/index'
- import GoodApi from '../../services/good'
- // import checkauth from '../../utils/checkauth'
- import Navi from '../../utils/navi'
- import { backPage, isLogin } from '../../utils/util'
- // pages/cart/index.ts
- Page({
- /**
- * 页面的初始数据
- */
- data: {
- // 猜你喜欢
- // 猜你喜欢
- favList: [] as WxGetCateAlbumOutput[],
- favTotal: 0,
- loadMoreStatus: 0,
- albumInput: {
- skipCount: 0,
- maxResultCount: 10,
- },
- cartData: {} as any,
- cartGoods: [] as any,
- wait: false,
- selgi: -1,
- isStock: false,
- isSpuSelectPopupShow: false,
- outEditStatus: true,
- details: {} as any,
- specImg: '',
- primaryImage: '',
- skuArray: [] as any[],
- unit: '',
- limitMaxCount: 999,
- limitMinCount: 1,
- limitBuyInfo: '',
- minSalePrice: 0,
- minLinePrice: 0,
- closed: true,
- _promotionGoods: [],
- _invalidGoods: [],
- selectItem: null as any,
- selectSkuSellPrice: 0,
- selectSkuLinePrice: 0,
- container: null as any,
- isChooseAddr: false,
- addr: {
- id: -1,
- name: '',
- },
- },
- // behaviors: [checkauth],
- userAddr(addr: any) {
- this.setData({
- isChooseAddr: true,
- addr: {
- id: addr.id,
- name: addr.detailAddress,
- },
- })
- },
- load() {
- const apis = [GoodApi.GetCart()]
- if (!this.data.isChooseAddr) {
- apis.push(GoodApi.GetAddr())
- }
- Promise.all(apis)
- .then((rsps) => {
- if (rsps[0].result) {
- const cartData = rsps[0].result as any
- console.log(cartData)
- if (cartData && cartData.goods && cartData.goods.length > 0) {
- cartData.goods.forEach((o: any) => {
- o.skuTitle = o.specs.map((x: any) => x.title).join(' ')
- })
- } else {
- cartData.goods = []
- }
- const { goods, ...rest } = cartData
- this.setData(
- {
- cartData: rest,
- cartGoods: goods,
- },
- () => {
- console.log(this.data.cartGoods)
- },
- )
- }
- if (rsps[2].result) {
- const addr = rsps[2].result
- this.setData({
- addr: {
- id: addr.id,
- name: addr.detailAddress,
- },
- })
- }
- })
- .finally(() => {
- this.setData({
- wait: false,
- })
- })
- this.loadRecommend()
- },
- loadRecommend(rest = false) {
- console.log('next')
- this.setData({
- loadMoreStatus: 1,
- })
- GoodApi.GetHomeRecommend(this.data.albumInput as any).then((rsp) => {
- if (rsp.result) {
- const result = rsp.result as any
- const { items = [] } = result
- const nowItems = rest ? items : this.data.favList.concat(items)
- this.setData({
- favList: nowItems as any,
- favTotal: result.totalCount || 0,
- loadMoreStatus: nowItems.length === result.totalCount ? 2 : 0,
- })
- }
- })
- },
- handleReachBottom() {
- if (this.data.loadMoreStatus === 0 && this.data.favList.length < this.data.favTotal) {
- this.setData(
- {
- albumInput: {
- ...this.data.albumInput,
- skipCount: this.data.albumInput.skipCount + 10,
- },
- },
- () => {
- this.loadRecommend()
- },
- )
- }
- },
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad() {},
- /**
- * 生命周期函数--监听页面初次渲染完成
- */
- onReady() {
- this.setData({
- container: () => this.createSelectorQuery().select('.cartwrap'),
- })
- },
- /**
- * 生命周期函数--监听页面显示
- */
- onShow() {
- const self = this
- this.getTabBar().init(() => {
- // //@ts-ignore
- // this.afterAuth(() => {
- // self.load()
- // })
- if (isLogin()) {
- self.load()
- } else {
- self.setData({
- favList: [],
- favTotal: 0,
- loadMoreStatus: 0,
- albumInput: {
- skipCount: 0,
- maxResultCount: 10,
- },
- cartData: {},
- cartGoods: [],
- selgi: -1,
- isStock: false,
- isSpuSelectPopupShow: false,
- outEditStatus: true,
- details: {},
- specImg: '',
- primaryImage: '',
- skuArray: [],
- unit: '',
- limitMaxCount: 999,
- limitMinCount: 1,
- limitBuyInfo: '',
- minSalePrice: 0,
- minLinePrice: 0,
- closed: true,
- _promotionGoods: [],
- _invalidGoods: [],
- selectItem: null as any,
- selectSkuSellPrice: 0,
- selectSkuLinePrice: 0,
- container: null as any,
- isChooseAddr: false,
- addr: {
- id: -1,
- name: '',
- },
- })
- }
- })
- },
- /**
- * 生命周期函数--监听页面卸载
- */
- onUnload() {},
- /**
- * 页面相关事件处理函数--监听用户下拉动作
- */
- onPullDownRefresh() {
- wx.stopPullDownRefresh()
- if (this.data.wait) return
- this.setData(
- {
- wait: true,
- },
- () => {
- setTimeout(() => {
- this.load()
- }, 100)
- },
- )
- },
- /**
- * 页面上拉触底事件的处理函数
- */
- onReachBottom() {},
- /**
- * 用户点击右上角分享
- */
- onShareAppMessage() {},
- reload() {
- this.setData({
- wait: true,
- })
- this.load()
- },
-
- gotoAddr() {
- const { id } = this.data.addr
- // wx.showModal({
- // content: JSON.stringify(this.data.addr),
- // success(res) {
- // if (res.confirm) {
- Navi.navigateTo({
- url: '/pages/mine/myaddr/list/index?mode=choose&id=' + id,
- })
- // }
- // },
- // })
- },
- gotoList() {
- Navi.switchTab({
- url: '/pages/goods/category/index',
- })
- },
- onToSettle() {
- if (this.data.addr.id > 0) {
- Navi.navigateTo({
- url: '/pages/mine/myorder/confirm/index?addrId=' + this.data.addr.id,
- })
- } else {
- Toast({
- context: this,
- selector: '#t-toast',
- message: '请选择配送地址',
- icon: '',
- duration: 1000,
- })
- }
- },
- gotoFavGoods(
- e: WechatMiniprogram.BaseEvent<
- {},
- {
- goods: any
- }
- >,
- ) {
- const { goods } = e.currentTarget.dataset
- Navi.navigateTo({
- url: '/pages/goods/detail/index?id=' + goods.id + '&cateid=' + goods.cateId,
- })
- },
- gotoGoods(
- e: WechatMiniprogram.BaseEvent<
- {},
- {
- goods: any
- }
- >,
- ) {
- const { goods } = e.currentTarget.dataset
- Navi.navigateTo({
- url: '/pages/goods/detail/index?id=' + goods.goodId + '&cateid=' + goods.cateId,
- })
- },
- handlePopupHide() {
- this.setData({
- isSpuSelectPopupShow: false,
- selgi: -1,
- })
- },
- specsConfirm(e: WechatMiniprogram.CustomEvent<{ buy: number }>) {
- const { selectItem, cartGoods, selgi: gi } = this.data
- const goods = cartGoods[gi]
- const bag: WxAddCartInput = {
- id: goods.id,
- cateId: goods.cateId,
- goodId: goods.goodId,
- skuId: selectItem.skuId,
- info: selectItem.specInfo.map((o: any) => o.specValueId),
- } as any
- this.setData({
- wait: true,
- })
- GoodApi.AddCart(bag)
- .then((rsp) => {
- if (rsp.result === 'ok') {
- goods.skuTitle = selectItem.specInfo.map((o: any) => o.specValue).join(' ')
- goods.specs = selectItem.specInfo.map((o: any) => ({
- id: o.specValueId,
- title: o.specValue,
- }))
- goods.skuId = selectItem.skuId
- goods.price = selectItem.price
- goods.skuImage = selectItem.image
- } else if (Number(rsp.result) > 0) {
- const beforeNum = goods.buyNum
- const combineId = Number(rsp.result)
- cartGoods.splice(gi, 1)
- for (var g of cartGoods) {
- if (g.id === combineId) {
- g.buyNum += beforeNum
- break
- }
- }
- }
- this.setData({
- cartGoods: cartGoods,
- isSpuSelectPopupShow: false,
- wait: false,
- selgi: -1,
- })
- })
- .catch(() => {
- this.setData({
- wait: false,
- selgi: -1,
- })
- })
- },
- selectGoods(
- e: WechatMiniprogram.BaseEvent<
- {},
- {
- promoindex: number
- gi: number
- }
- >,
- ) {
- const { gi } = e.currentTarget.dataset
- const data = this.data.cartGoods as any[]
- const state = !data[gi].isSelected
- // data[gi].isSelected = !data[gi].isSelected
- this.setData({
- cartGoods: data,
- wait: true,
- })
- GoodApi.SelectCartItem({
- id: data[gi].id,
- state,
- })
- .then((rsp) => {
- if (rsp.result === 'ok') {
- data[gi].isSelected = !data[gi].isSelected
- this.calc(data)
- }
- })
- .catch(() => {
- this.setData({
- wait: false,
- })
- })
- },
- onSelectAll() {
- const unselected = this.data.cartData.isAllSelected
- const api = unselected ? GoodApi.UnSelectAllCartItem : GoodApi.SelectAllCartItem
- this.setData({
- wait: true,
- })
- api()
- .then((rsp) => {
- if (rsp.result === 'ok') {
- const data = this.data.cartGoods as any[]
- data.forEach((o) => {
- o.isSelected = !unselected
- })
- this.calc(data)
- }
- })
- .catch(() => {
- this.setData({
- wait: false,
- })
- })
- },
- onChangeStepper(
- e: WechatMiniprogram.CustomEvent<{ value: number }, {}, { gi: number; goods: any }>,
- ) {
- const { gi, goods } = e.currentTarget.dataset
- const val = e.detail.value
- const data = this.data.cartGoods as any[]
- if (data[gi].buyNum == val) {
- return
- }
- this.setData({
- wait: true,
- })
- GoodApi.NumCartItem({
- id: goods.id,
- buyNum: Number(val),
- })
- .then((rsp) => {
- if (rsp.result === 'ok') {
- data[gi].buyNum = val
- this.calc(data)
- }
- })
- .catch(() => {
- this.setData({
- wait: false,
- })
- })
- },
- onDeleteGoods(e: WechatMiniprogram.CustomEvent<{}, {}, { gi: number; goods: any }>) {
- const { gi, goods } = e.currentTarget.dataset
- const data = this.data.cartGoods as any[]
- this.setData({
- wait: true,
- })
- GoodApi.RemoveCartItem({
- id: goods.id,
- })
- .then((rsp) => {
- if (rsp.result === 'ok') {
- data.splice(gi, 1)
- this.calc(data)
- }
- })
- .catch(() => {
- this.setData({
- wait: false,
- })
- })
- },
- chooseSpecItem(
- e: WechatMiniprogram.CustomEvent<{
- selectedSku: Record<string, string>
- isAllSelectedSku: boolean
- }>,
- ) {
- const { specList } = this.data.details
- const { selectedSku, isAllSelectedSku } = e.detail
- console.log(specList, isAllSelectedSku, selectedSku)
- if (!isAllSelectedSku) {
- this.setData({
- selectSkuSellPrice: 0,
- })
- }
- this.setData({
- isAllSelectedSku,
- })
- this.getSkuItem(specList, selectedSku)
- },
- getSkuItem(specList: TmpSpec[] | undefined, selectedSku: Record<string, string>) {
- const { skuArray, primaryImage, unit } = this.data
- const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku)
- let selectedAttrStr = ` ${unit} `
- selectedSkuValues.forEach((item) => {
- selectedAttrStr += `,${item.specValue} `
- })
- // eslint-disable-next-line array-callback-return
- const findSkuItem = skuArray.filter((item) => {
- let status = true
- ;(item.specInfo || []).forEach((subItem: any) => {
- if (!selectedSku[subItem.specId] || selectedSku[subItem.specId] !== subItem.specValueId) {
- status = false
- }
- })
- if (status) return item
- })
- this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '')
- console.log('find sku:', findSkuItem)
- if (findSkuItem && findSkuItem.length > 0) {
- const selectItem = findSkuItem[0]
- this.setData({
- specImg: selectItem.image,
- selectItem,
- selectSkuSellPrice: selectItem.price || 0,
- selectSkuLinePrice: selectItem.linePrice || 0,
- })
- } else {
- this.setData({
- specImg: primaryImage,
- selectItem: null,
- selectSkuSellPrice: 0,
- selectSkuLinePrice: 0,
- })
- }
- },
- getSelectedSkuValues(skuTree: any, selectedSku: any) {
- const normalizedTree = this.normalizeSkuTree(skuTree)
- return Object.keys(selectedSku).reduce((selectedValues: any[], skuKeyStr) => {
- const skuValues = normalizedTree[skuKeyStr] as any[]
- const skuValueId = selectedSku[skuKeyStr]
- if (skuValueId !== '') {
- const skuValue = skuValues.filter((value) => {
- return value.specValueId === skuValueId
- })[0]
- skuValue && selectedValues.push(skuValue)
- }
- return selectedValues
- }, [])
- },
- normalizeSkuTree(skuTree: any) {
- const normalizedTree = {} as any
- skuTree.forEach((treeItem: any) => {
- normalizedTree[treeItem.specId] = treeItem.specValueList
- })
- return normalizedTree
- },
- selectSpecsName(selectSpecsName: string) {
- if (selectSpecsName) {
- this.setData({
- selectedAttrStr: selectSpecsName,
- })
- } else {
- this.setData({
- selectedAttrStr: '',
- })
- }
- },
- onChangeSpec(e: WechatMiniprogram.CustomEvent<{}, {}, { gi: number; goods: any }>) {
- const { gi, goods } = e.currentTarget.dataset
- const data = this.data.cartGoods as any[]
- this.setData({
- wait: true,
- selgi: gi,
- })
- GoodApi.GetProduct({ id: goods.goodId } as any)
- .then((rsp) => {
- if (rsp.result) {
- const details = rsp.result
- const {
- imageUrl: primaryImage,
- limitMaxCount,
- limitMinCount,
- limitBuyInfo,
- unit,
- } = details
- const skuArray = [] as {
- skuId: number
- quantity: number
- image: string
- price: number
- linePrice: number
- specInfo: TmpSpecInfo[]
- }[]
- if (details.skuList) {
- details.skuList.forEach((item) => {
- const priceInfo = item.priceInfo || []
- const len = priceInfo.length
- skuArray.push({
- skuId: Number(item.skuId),
- image: item.skuImage || primaryImage || '',
- price: len > 0 ? priceInfo[0].price : 0,
- linePrice: len > 1 ? priceInfo[1].price : 0,
- quantity: item.stockInfo ? item.stockInfo.stockQuantity : 0,
- specInfo: item.specInfo || [],
- })
- })
- }
- console.log(rsp.result, skuArray)
- this.setData({
- details: rsp.result,
- wait: false,
- isAllSelectedSku: false,
- isSpuSelectPopupShow: true,
- primaryImage,
- isStock: details.spuStockQuantity > 0,
- skuArray: skuArray as any,
- soldout: details.isPutOnSale === 0,
- minSalePrice: details.minSalePrice,
- minLinePrice: details.minSalePrice,
- limitMaxCount,
- limitMinCount,
- limitBuyInfo,
- unit,
- })
- }
- })
- .catch(() => {
- this.setData({
- wait: false,
- selgi: -1,
- })
- })
- },
- calc(data: any[]) {
- const total = data.reduce(
- (
- re: {
- sum: number
- selected: number
- },
- o,
- ) => {
- if (o.isSelected) {
- re.sum += o.buyNum * o.price
- re.selected += 1
- }
- return re
- },
- {
- sum: 0,
- selected: 0,
- },
- )
- this.setData({
- cartGoods: data,
- wait: false,
- cartData: {
- ...this.data.cartData,
- totalAmount: total.sum,
- isAllSelected: data.length !== 0 && total.selected === data.length,
- selectedGoodsCount: total.selected,
- isNotEmpty: data.length !== 0,
- },
- })
- },
- changeAddress() {
- console.log('switch address')
- },
- })
|