//@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 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) { 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') }, })