123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- // pages/goods/list/index.js
- const app = getApp()
- import { request } from '../../../utils/request'
- import { checkNeedLogin, doLogin, getLoginInfo, checkNeedBindInstitution } from '../../../utils/login'
- Page({
- data: {
- isLogin: false, // 添加登录状态
- goodsList: [],
- loading: false,
- currentPage: 1,
- pageSize: 10,
- totalPages: 1,
- showAuthModal: false, // 添加弹窗显示状态
- bindStatus: 0,
- currentGoodsId: null, // 添加当前商品ID
- currentShopAppid: '', // 当前商品的小店appid
- currentProductId: '', // 当前商品的商品ID
- productPromotionLink: '', // 当前商品的推广链接
- currentProduct: null,
- iconZhihu: '/static/images/icon-zhihu.png',
- iconUser: '/static/images/icon-user.png',
- posterUrl: '',
- showPosterModal: false
- },
- onLoad: function (options) {
- this.checkLoginStatus()
- this.loadGoodsList()
- },
- // 加载商品列表
- loadGoodsList() {
- if (this.data.loading) return
-
- this.setData({ loading: true })
- request({
- url: '/api/goods/list',
- method: 'GET',
- data: {
- page: this.data.currentPage,
- page_size: this.data.pageSize,
- sort: 7
- }
- }).then(res => {
- if (res.rst && res.rst.data) {
- const newGoods = res.rst.data
- const totalPages = res.rst.pageInfo ? parseInt(res.rst.pageInfo.pages || 1) : 1
- // 判断是第一页还是加载更多
- const updatedGoods = this.data.currentPage === 1
- ? newGoods
- : [...this.data.goodsList, ...newGoods]
- this.setData({
- goodsList: updatedGoods,
- currentPage: this.data.currentPage + 1,
- totalPages: totalPages
- })
- }
- }).catch(err => {
- console.error('获取商品列表失败:', err)
- wx.showToast({
- title: '获取商品列表失败',
- icon: 'none'
- })
- }).finally(() => {
- this.setData({ loading: false })
- wx.stopPullDownRefresh()
- })
- },
- // 检查登录状态
- async checkLoginStatus() {
- console.log('检查登录状态')
- if (checkNeedLogin()) {
- try {
- await doLogin()
- this.setData({ isLogin: true })
- await getUserInfo()
- } catch (err) {
- console.error('登录失败:', err)
- this.setData({ isLogin: false })
- }
- } else {
- this.setData({ isLogin: true })
- await getUserInfo()
- }
- // 检查是否需要绑定机构
- const bindStatus = wx.getStorageSync('bindStatus')
- console.log('当前bindStatus:', bindStatus)
- const needBind = checkNeedBindInstitution()
- console.log('是否需要绑定机构:', needBind)
- this.setData({ bindStatus: bindStatus || 0 })
- },
- // 获取用户信息
- async getUserInfo() {
- try {
- const userInfo = wx.getStorageSync('userInfo')
- console.log('当前userInfo:', userInfo)
- this.setData({
- userInfo,
- isLogin: true // 设置登录状态
- })
- } catch (err) {
- console.error('获取用户信息失败:', err)
- }
- },
- // 跳转到商品详情
- navigateToDetail(e) {
- const goodsId = e.currentTarget.dataset.goodsId;
- console.log('1. 获取到的商品ID:', goodsId);
-
- if (!goodsId) {
- console.error('商品ID不存在');
- return;
- }
- // 从商品列表中查找商品信息
- const product = this.data.goodsList.find(item => item.goods_id === goodsId);
- console.log('2. 找到的商品信息:', product);
-
- if (!product) {
- console.error('未找到商品信息');
- return;
- }
- // 获取bindStatus
- const bindStatus = wx.getStorageSync('bindStatus') || 0;
- console.log('3. 当前bindStatus:', bindStatus);
- // 获取用户信息
- const userInfo = wx.getStorageSync('userInfo');
- console.log('4. 用户信息:', userInfo);
- // 先设置基本信息
- const setData = {
- showAuthModal: true,
- bindStatus,
- currentProduct: {
- goods_id: product.goods_id,
- name: product.title,
- price: product.sale_price,
- image: product.head_img_list[0],
- estimatedReturn: product.total_commission_amount || '0'
- },
- currentGoodsId: goodsId,
- currentShopAppid: product.shop_appid,
- currentProductId: product.product_id,
- productPromotionLink: ''
- };
- console.log('5. 商品基本信息:', {
- shop_appid: product.shop_appid,
- product_id: product.product_id
- });
- // 获取推广链接
- request({
- url: '/api/goods/productPromotionLink',
- method: 'POST',
- data: {
- goods_id: goodsId,
- user_id: userInfo ? userInfo.id : '',
- sharer_appid: userInfo ? userInfo.sharer_appid : ''
- }
- }).then(res => {
- console.log('6. 推广链接API返回:', res);
- if (res.errno === '0' && res.rst) {
- setData.productPromotionLink = res.rst.product_promotion_link || '';
- console.log('7. 最终设置的数据:', setData);
-
- this.setData(setData, () => {
- console.log('8. 数据设置完成,当前状态:', {
- showAuthModal: this.data.showAuthModal,
- currentShopAppid: this.data.currentShopAppid,
- currentProductId: this.data.currentProductId,
- productPromotionLink: this.data.productPromotionLink
- });
- });
- } else {
- console.error('9. 获取推广链接失败:', res);
- wx.showToast({
- title: '获取商品信息失败',
- icon: 'none'
- });
- }
- }).catch(err => {
- console.error('10. 获取推广链接请求失败:', err);
- wx.showToast({
- title: '获取商品信息失败',
- icon: 'none'
- });
- });
- },
- // 下拉刷新
- onPullDownRefresh: function() {
- this.setData({
- currentPage: 1,
- goodsList: []
- }, () => {
- this.loadGoodsList()
- })
- },
- // 上拉加载更多
- onReachBottom: function() {
- if (!this.data.loading && this.data.currentPage <= this.data.totalPages) {
- this.loadGoodsList()
- }
- },
- // 隐藏授权弹窗
- hideAuthModal() {
- this.setData({
- showAuthModal: false,
- currentProduct: null,
- currentGoodsId: null,
- currentShopAppid: '',
- currentProductId: '',
- productPromotionLink: ''
- });
- },
- // 阻止事件冒泡
- preventTap() {
- // 空函数,仅用于阻止事件冒泡
- },
- // 点击授权按钮
- onAuthClick() {
- if (!this.data.isLogin) {
- wx.showToast({
- title: '请先登录',
- icon: 'none'
- })
- return
- }
- const userInfo = wx.getStorageSync('userInfo')
- if (!userInfo) {
- wx.showToast({
- title: '获取用户信息失败',
- icon: 'none'
- })
- return
- }
- const businessType = userInfo.bind_business_type
- const queryString = userInfo.bind_query_string
- const commissionType = userInfo.commission_type
- const commissionRatio = userInfo.commission_ratio
- const headSupplierAppid = userInfo.head_supplier_appid
- wx.openBusinessView({
- businessType: businessType,
- queryString: queryString,
- extraData: {
- commissionType: commissionType,
- commissionRatio: commissionRatio,
- headSupplierAppid: headSupplierAppid
- },
- success: (res) => {
- console.log('绑定机构成功', res)
- wx.setStorageSync('bindStatus', 1)
- this.setData({
- bindStatus: 1,
- showAuthModal: false
- })
- },
- fail: (err) => {
- console.error('绑定机构失败', err)
- wx.showToast({
- title: '绑定失败',
- icon: 'none'
- })
- }
- })
- },
- // 分享商品
- async onShareProduct() {
- console.log('[分享商品] 开始分享商品');
- await this.generatePoster();
- },
- // 生成海报
- async generatePoster() {
- try {
- wx.showLoading({
- title: '生成海报中...',
- mask: true
- });
-
- const { currentProduct, currentProductId, currentGoodsId } = this.data;
-
- if (!currentProduct || !currentProductId) {
- throw new Error('商品信息不完整');
- }
- // 获取二维码
- const qrcodeUrl = await this.getShareQrCode(currentGoodsId);
- if (!qrcodeUrl) {
- throw new Error('获取二维码失败');
- }
- // 检查商品图片
- const productImage = await new Promise((resolve, reject) => {
- wx.getImageInfo({
- src: currentProduct.image,
- success: res => resolve(res),
- fail: err => reject(err)
- });
- });
- // 下载二维码图片
- const qrcodeImage = await new Promise((resolve, reject) => {
- wx.getImageInfo({
- src: qrcodeUrl,
- success: res => resolve(res),
- fail: err => reject(err)
- });
- });
- // 绘制海报
- const ctx = wx.createCanvasContext('posterCanvas');
-
- // 绘制背景
- ctx.setFillStyle('#FF5B4C'); // 设置整个画布背景为橙红色
- ctx.fillRect(0, 0, 750, 1500);
- // 绘制内层白色圆角背景
- ctx.save();
- ctx.beginPath();
- const radius = 20;
- // 白色区域的位置和大小(上下边距80px,左右边距40px)
- ctx.moveTo(40 + radius, 80);
- ctx.lineTo(710 - radius, 80);
- ctx.arcTo(710, 80, 710, 80 + radius, radius);
- ctx.lineTo(710, 1420 - radius); // 1500 - 80
- ctx.arcTo(710, 1420, 710 - radius, 1420, radius);
- ctx.lineTo(40 + radius, 1420);
- ctx.arcTo(40, 1420, 40, 1420 - radius, radius);
- ctx.lineTo(40, 80 + radius);
- ctx.arcTo(40, 80, 40 + radius, 80, radius);
- ctx.closePath();
- ctx.setFillStyle('#ffffff');
- ctx.fill();
- ctx.restore();
- // 绘制顶部装饰
- // 左侧横线
- ctx.setStrokeStyle('#FF5B4C');
- ctx.setLineWidth(2); // 加粗线条
- ctx.moveTo(260, 180); // 下移装饰线
- ctx.lineTo(350, 180);
- ctx.stroke();
- // 右侧横线
- ctx.moveTo(400, 180); // 线条右移
- ctx.lineTo(490, 180);
- ctx.stroke();
- // 蝴蝶结(简化版)
- ctx.beginPath();
- ctx.arc(375, 180, 20, 0, 2 * Math.PI); // 增大圆圈
- ctx.setFillStyle('#FF5B4C');
- ctx.fill();
- // 绘制商品标题
- ctx.setFillStyle('#333333');
- ctx.setFontSize(32); // 放大标题字号
- const title = currentProduct.name;
- const titleLines = this.splitText(ctx, title, 630);
- titleLines.slice(0, 2).forEach((line, index) => {
- ctx.fillText(line, 60, 280 + index * 45); // 下移标题
- });
- // 绘制价格
- ctx.setFillStyle('#FF5B4C');
- ctx.setFontSize(36); // 放大价格符号
- ctx.fillText('¥', 60, 400); // 下移价格
- ctx.setFontSize(48); // 放大价格数字
- ctx.fillText(currentProduct.price, 90, 400);
- // 绘制商品图片
- ctx.drawImage(productImage.path, 60, 460, 630, 650); // 下移并适当增加高度
- // 绘制底部信息
- ctx.drawImage(qrcodeImage.path, 480, 1200, 180, 180); // 下移二维码
-
- // 绘制微信小店icon和文字
- // 加载小店icon
- await new Promise((resolve, reject) => {
- const iconPath = 'https://kx-wechat-shop.oss-cn-beijing.aliyuncs.com/2025/02/17/wechat_shop.png'; // 使用相对路径
- console.log('[海报生成] 尝试加载小店icon:', iconPath);
- wx.getImageInfo({
- src: iconPath,
- success: res => {
- console.log('[海报生成] 加载小店icon成功', res);
- ctx.drawImage(res.path, 60, 1260, 32, 32);
- ctx.setFillStyle('#666666');
- ctx.setFontSize(28);
- ctx.fillText('微信小店', 120, 1290);
- ctx.setFillStyle('#999999');
- ctx.setFontSize(26);
- ctx.fillText('微信扫一扫购买', 120, 1330);
- resolve();
- },
- fail: err => {
- console.error('[海报生成] 加载小店icon失败', err);
- // 即使加载失败也继续绘制文字
- ctx.setFillStyle('#666666');
- ctx.setFontSize(28);
- ctx.fillText('微信小店', 120, 1290);
- ctx.setFillStyle('#999999');
- ctx.setFontSize(26);
- ctx.fillText('微信扫一扫购买', 120, 1330);
- resolve();
- }
- });
- });
-
- // 导出画布为图片
- console.log('[海报生成] 画布绘制完成,准备导出图片');
- const posterRes = await new Promise((resolve, reject) => {
- ctx.draw(false, () => {
- wx.canvasToTempFilePath({
- canvasId: 'posterCanvas',
- success: res => resolve(res),
- fail: err => reject(err)
- });
- });
- });
- // 生成海报成功后,显示预览并打开分享菜单
- this.setData({
- posterUrl: posterRes.tempFilePath,
- showPosterModal: true
- }, () => {
- // 显示分享菜单
- wx.showShareImageMenu({
- path: posterRes.tempFilePath,
- complete: () => {
- // 无论用户是分享还是取消,都关闭海报预览
- this.setData({
- showPosterModal: false
- })
- }
- })
- });
-
- wx.hideLoading();
- } catch (error) {
- console.error('生成海报失败:', error);
- wx.hideLoading();
- wx.showToast({
- title: '生成海报失败',
- icon: 'none'
- });
- }
- },
- // 获取商品二维码
- async getShareQrCode(goodsId) {
- try {
- const userInfo = wx.getStorageSync('userInfo');
- if (!userInfo || !userInfo.sharer_appid) {
- throw new Error('缺少分享者信息');
- }
- const res = await request({
- url: '/api/goods/shareQrCode',
- method: 'POST',
- data: {
- goods_id: goodsId,
- user_id: userInfo ? userInfo.id : '',
- sharer_appid: userInfo ? userInfo.sharer_appid : ''
- }
- });
- if (res.errno === '0' && res.rst && res.rst.qrcode_url) {
- return res.rst.qrcode_url;
- } else {
- throw new Error(res.err || '获取二维码失败');
- }
- } catch (error) {
- console.error('获取二维码失败:', error);
- wx.showToast({
- title: error.message || '获取二维码失败',
- icon: 'none'
- });
- return null;
- }
- },
- // 文本分行处理
- splitText(ctx, text, maxWidth) {
- console.log('[文本处理] 开始分行处理:', { text, maxWidth });
- const chars = text.split('');
- const lines = [];
- let tempLine = '';
-
- chars.forEach((char) => {
- const testLine = tempLine + char;
- const metrics = ctx.measureText(testLine);
- if (metrics.width > maxWidth) {
- console.log('[文本处理] 当前行宽度超出,添加新行:', tempLine);
- lines.push(tempLine);
- tempLine = char;
- } else {
- tempLine = testLine;
- }
- });
-
- if (tempLine) {
- console.log('[文本处理] 添加最后一行:', tempLine);
- lines.push(tempLine);
- }
-
- console.log('[文本处理] 分行结果:', lines);
- return lines;
- },
- closePosterModal() {
- this.setData({
- showPosterModal: false
- });
- },
- // 处理海报图片加载完成
- onPosterImageLoad(e) {
- console.log('[海报预览] 图片加载完成:', {
- width: e.detail.width,
- height: e.detail.height
- });
- },
- // store-product组件事件处理
- onStoreProductEnterError(e) {
- console.error('进入商品失败,错误详情:', e.detail);
- wx.showToast({
- title: '进入商品失败',
- icon: 'none'
- });
- }
- });
|