checkProduct.js 17.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
// pages/checkProduct/checkProduct.js
// const navStyle = "background-color: transparent;";
const navStyle = 'background-color: #fff'
import { senceData } from '~/pages/tab/index/constant/data'
import { IMG_URL } from '~/utils/constantData.js'
import { productBysceneApi } from '~/api/index.js'
import Draw from '~/utils/Draw.js'
import { createQrCodeApi, sceneByIdApi } from '~/api/checkProduct.js'
import utils from '~/utils/util.js'

Page({
  /**
   * 页面的初始数据
   */
  noPageAuth: true,
  data: {
    navStyle,
    headerHeight: 0,
    senceData,
    // 模态框
    isShow: false,
    // IMG_URL: `${IMG_URL}index`,
    btnList: [
      {
        src: `${IMG_URL}index/down.png`,
        name: '生成海报'
      },
      {
        src: `${IMG_URL}index/wechat.png`,
        name: '转发给好友'
      }
      // {
      //   src: `${IMG_URL}index/moments.png`,
      //   name: "朋友圈分享",
      // },
    ],
    // 4种场景下图片所有的高 (单位 rpx)
    imgHeightArr: [
      [1110, 1290, 596, 744, 490, 1532],
      [2168, 1290, 596, 830, 490, 752],
      [1110, 1290, 596, 984, 490],
      [678, 1266, 1398, 830, 490, 1666]
    ],
    posterUrl: '', //海报url
    noVideoimgList: [],
    //分享相关
    isShare: false,
    // 是否授权昵称
    hasUserInfo: false,
    phone: '', //授权手机号
    userInfo: '',
    isAuthphone: true, //授权昵称弹窗显示,更多按钮显示
    // 视频播放地址
    videoSrc:'',
    videoTitle:'',
    //下载海报授权
    showAuth: false,
    img_version:0.1
  },
  observers: {
    actNum: function (actNum) {
      let imgList = [`${IMG_URL}index/scene${actNum + 1}1.png`, `${IMG_URL}index/scene${actNum + 1}2.png`, `${IMG_URL}index/scene${actNum + 1}3.png`, `${IMG_URL}index/scene${actNum + 1}4.png`, `${IMG_URL}index/scene${actNum + 1}5.png`]
      this.setData({
        noVideoimgList: imgList
      })
      if (actNum != 2) {
        imgList.push(`${IMG_URL}index/scene${actNum + 1}6.png`)
      }
      this.setData({
        imgList
      })
    }
  },
  // navbar高度设置
  navbarReady(e) {
    let { height, statusBarHeight } = e.detail
    console.log('height, statusBarHeight : ', height, statusBarHeight );
    this.setData({
      // headerHeight: height / 2 + statusBarHeight
      headerHeight: height 
      // headerHeight: height / 2 + statusBarHeight + 88 * 2,
    })
    // console.log(e)
    // console.log(this.data.headerHeight)
  },
  // 分项弹框关闭
  modelcloseFn(e) {
    this.setData({
      isShow: false
    })
  },
  // 分享按钮
  sharehandle() {
    this.setData({
      isShow: true
    })
  },
  //如果是直接查看页面,获取合成apiData
  getData() {
    console.log(123456)
    // 看产品
    productBysceneApi().then(res => {
      let { code, data } = res

      if (code == 0 && data) {
        // this.setData({
        //   apiData: data
        // })
        this.compositionData(senceData, data)
        // this.getFirstSenceIndex();
      }
    })
  },
  //接口数据,本地数据对接
  compositionData(localData, apiData) {
    localData.forEach((item, index) => {
      apiData.forEach((inner, idx) => {
        if (item.name == inner.stage) {
          item.sceneStatus = inner.sceneStatus

          item.productList.forEach((outChild, outIndex) => {
            inner.productList.forEach((innerChild, innerIndex) => {
              if (outChild.proName == innerChild.productName) {
                outChild.productStatus = innerChild.productStatus
              }
            })
          })
        }
      })
    })
    // console.log('localData, apiData: ', localData);
    this.setData({
      senceData: localData
    })
  },

  //接受跳转的路由参数(小程序页面跳转)
  onRoute(options) {
    // console.log('分享onRoute ', options)
    if (!options || utils.isEmptyObj(options)) return
    // if(!Object.keys(options).includes('actNum'))return
    let { senceData } = this.data

    //选中场景的index,和产品的index
    let {
      actNum,
      activeNavIdx,
      // apiData,
      outshowVideo,
      isShow,
      // origin  //跳转来源 home
    } = options
    // if(actNum&&activeNavIdx)return

    // 设置标题
    let userInfoObj = wx.$storage.get('userInfo')

    // #服务商账号#取该分享者商户的联系人字段,无则取商户简称,无则取商户全称
    let name = userInfoObj.merchantName
    // let name
    // if (userInfoObj.name) {
    //   name = userInfoObj.name
    // }else if(userInfoObj.merchantName){
    // }else if(userInfoObj.merchantName){
    //   //全称
    //   name = userInfoObj.merchantName
    // }

    this.shareTitle = `${name}给你分享一个活动${senceData[actNum]?.productList[activeNavIdx].proName},戳我参与~`
    this.getImgInfo(actNum)

    this.setData({
      actNum,
      activeNavIdx,
      // apiData,
      outshowVideo,
      isShow,
      share_phone: options.sharePhone
      // origin
      // isShare
    })
    // let apiDataJson = JSON.stringify(apiData);
    let item = senceData[actNum]?.productList[activeNavIdx]
    this.shareQuery = `sceneCode=${senceData[actNum].sceneCode}&productCode=${item?.productCode}&isShare=${true}&productDesc=${item?.productName}&category=${item?.category}&actNum=${actNum}&activeNavIdx=${activeNavIdx}`
    this.shareTrackData = {
      sceneCode: senceData[actNum]?.sceneCode,
      productCode: item?.productCode,
      productName: item?.productName,
      category: item?.category,
      productDesc: item?.productName
      // actNum,
      // activeNavIdx,
      // apiData,
    }
  },
  // 分享按钮
  handleClick(e) {
    let { index } = e.currentTarget.dataset
    let _this = this
    switch (index) {
      case 0:
        wx.showModal({
          content: '生成并下载页面为海报',
          success: async res => {
            if (res.confirm) {
              wx.getSetting({
                success: (res)=> {
                  if(res.authSetting['scope.writePhotosAlbum']===false){
                    _this.setData({
                      showAuth: true
                    })
                  }else{
                    _this.download()
                  }
                }
              })

            }
          },
          confirmText:'下载',
          cancelText:'返回',
          fail: res => {},
          complete: res => {}
        })
        // this.download();

        break
      case 1:
        this.wechatFn()
        break
    }
  },
  //授权添加相册
  toSetting() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.writePhotosAlbum']) {
            resolve(true)
          } else {
            wx.openSetting({
              success: resp => {
                if (resp.authSetting['scope.writePhotosAlbum']) {
                  resolve(true)
                } else {
                  wx.showToast({
                    title: "下载海报前需要您授权'添加到相册'权限",
                    icon: 'none',
                    duration: 2500
                  })
                }
              }
            })
          }
        }
      })
    })
  },
  // 微信转发
  wechatFn() {
    // this.data.onShareAppMessage()
    // this.modelcloseFn();
  },
  // 下载海报
  async download() {
    let { actNum, activeNavIdx, imgHeightArr, imgPath } = this.data
    const { appId } = wx.getAccountInfoSync().miniProgram
    let { userInfo } = wx.$storage.get(),
    wx_user_info = wx.$storage.get('wx_user_info'),
     senceItem = senceData[actNum], item = senceData[actNum]?.productList[activeNavIdx];
    // let wx_user_info = wx.$storage.get("wx_user_info");
    // console.log('wx_user_info: ', wx_user_info.appId);
    wx.showLoading({
      title: "海报生成中...",
    });
    console.log(wx_user_info)
    let params = {
      actNum,
      activeNavIdx,
      isShare: true,
      merchantId:userInfo.merchantId || '',
      shareOpenId: wx_user_info.openId || '',
      sharePhone: userInfo.phone || '',
      sceneCode: senceItem?.sceneCode || '',
      productCode: item?.productCode || '',
      productDesc: item?.productName || '',
      category: item?.category || ''
    };
    // console.log(' wx_user_info.appId', wx_user_info)
    let res = await createQrCodeApi({
      appId: appId,
      // appId:'wx2c28337db96364d2',
      path: 'pages/checkProduct/checkProduct',
      scene: JSON.stringify(params)
    })

    let _this = this
    console.log('imgPath',imgPath)
    wx.getImageInfo({
      src: imgPath,
      success: async respp => {
        let imgW = respp.width / 4,
          imgH = respp.height / 4
        let pradH = (288 * imgW) / 1029,
          qrcodeH = 100
        let drawFun = new Draw({
          width: imgW,
          height: imgH + pradH
        })

        console.log('actNum', actNum)
        let qrcodeY = actNum == 2 ? 20 : 0
        let arr = [456, 222, 0, 496]
        let imgList = [
          {
            x: 0,
            y: 0,
            width: imgW,
            height: pradH,
            url: `${IMG_URL}index/canvas/${senceData[actNum].productList[activeNavIdx].img}.png`
          },
          {
            x: 0,
            y: pradH,
            width: imgW,
            height: imgH,
            url: `https://img02.glsx.com.cn/weapp/resource/saas/business-assistant/index/longpic${actNum + 1}.jpg?v=${Date.now()}`
            // url: `https://img02.glsx.com.cn/weapp/resource/saas/business-assistant/index/longpic${actNum + 1}.webp`
          },
          {
            // x: 245 * 2,
            // y: erCodeHeight + 30,
            // width: 120 * 2,
            // height: 120 * 2,
            x: imgW - qrcodeH,
            y: imgH + pradH - qrcodeH - 20,
            width: qrcodeH,
            height: qrcodeH,
            url: res.data //二维码
          }
        ]
        let telephone = userInfo.phone ? userInfo.phone : ''
        let textList = [
          {
            x: 22,
            y: imgH + pradH - 25,
            text: `联系我:${telephone}`,
            color: '#323436',
            fontSize: 10
          }
        ]
        // console.log(imgList)
        let posterUrl = await drawFun.begin({
          imageList: imgList,
          textList
        })
        _this.setData({
          posterUrl: posterUrl.path
        })
        console.log('posterUrl.path', posterUrl.path)
        if (_this.data.posterUrl) {
          wx.saveImageToPhotosAlbum({
            filePath: _this.data.posterUrl, //仅为示例,并非真实的资源
            success(res) {
              console.log('res: ', res)
              wx.$api.showToast('下载成功!')
            }
          })
        }
        // _this.modelcloseFn();
        wx.hideLoading()
      },
      fail:(err)=>{
        wx.$api.showToast('下载失败')
        // console.log(err)
      }
    })
  },
  authFail(){
    wx.showToast({
      title: "下载海报前需要您授权'添加到相册'权限",
      icon: "none",
      duration: 2500,
    });
  },
  authSuccess(){
    this.download()
  },
  // //模态框关闭
  // modelClose() {
  //   this.triggerEvent("modelclose", false);
  // },
  // 图片加载事件
  // onloadFn(event) {
  //   // console.log("event.detail", event.detail);
  //   this.setData({
  //     imgHeight: event.detail.height / 5,
  //     imgWidth: event.detail.width / 5,
  //   });
  // },
  // 图片视频加载回调拿到url
  getImgInfo(actNum) {
    wx.showLoading({
      title: '加载中'
    })
    let _this = this
    wx.getImageInfo({
      src: `https://img02.glsx.com.cn/weapp/resource/saas/business-assistant/index/longpic${actNum + 1}.jpg?v=${Date.now()}`,
       // src: `https://img02.glsx.com.cn/weapp/resource/saas/business-assistant/index/longpic${actNum + 1}.png`,
      success: async res => {
        // console.log('res图片信息: ', res)

        wx.hideLoading()
        wx.nextTick(() => {
          _this.setData({
            // isShow: true,
            imgPath: res.path
          })
        })
      },
      fail:(err) => {
        console.log('err: ', err);
      }
    })
  },
  // 分享获取懂得用户数
  authorizedFn(e) {
    let res = e.detail
    this.onLoad(null)
    wx.nextTick(() => {
      //储存手机号
      //  console.log("储存手机号",res.phone)
      wx.$storage.set('authphone', res.phone)
      this.setData({
        // isShare: res.isShare,
        phone: res.phone
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载 (扫码,分享链接)
   */
  async onLoad(options) {
    await this.getData()
    // console.log('分享onLoad: ', options)
    // actNum,activeNavIdx isShare
    if (!options || utils.isEmptyObj(options)) return

    // this.analysisOption();
    // 解析二维码参数
    if (options.scene) {
      this.setData({
        isShare: true
      })
      let ercodeParams = await this.analysisQRcode(options.scene)
      console.log(ercodeParams)
      options = JSON.parse(ercodeParams.scene)
      this.options = options
      console.log('====================',this.options)
      this.onLoad(null)
    }
    let { senceData } = this.data
    //  扫码进来
    let { actNum, activeNavIdx, isShare } = options
    console.log('actNum, activeNavIdx, isShare: ', actNum, activeNavIdx, isShare)
    if (isShare) {
      this.setData({
        isShow: false
      })
    } else {
      wx.showLoading({
        title: '加载图片中'
      })
    }

    this.setData({
      actNum,
      activeNavIdx,
      isShare: true,
      outshowVideo: false, //显示视频列表
      share_phone: options.sharePhone
    });
    // 发请求
    console.log()
    let senceItem = senceData[actNum]
    let item = senceData[actNum]?.productList[activeNavIdx]
    this.shareQuery = `sceneCode=${senceItem?.sceneCode}&productCode=${item?.productCode}&isShare=${true}&productDesc=${item?.productName}&category=${item?.category}&actNum=${actNum}&activeNavIdx=${activeNavIdx}`
    this.shareTrackData = {
      sceneCode: senceItem?.sceneCode,
      productCode: item?.productCode,
      productName: item?.productName,
      category: item?.category,
      productDesc: item?.productName
      // actNum,
      // activeNavIdx,
    }

    // 有手机号就不用再一次授权昵称,手机号
    let phone = wx.$storage.get('authphone')
    console.log('储存手机号', phone)
    if (phone) {
      this.setData({
        isAuthphone: false,
        outshowVideo: true,
        isShare: false
      })
    }
  },
  // 解析二维码回调
  // async analysisOption() {},

  // 解析扫码进来参数
  async analysisQRcode(str) {
    let id = str.split('%3D')[1]
    let res = await sceneByIdApi({
      id
    })
    // console.log('res: ', res);
    return res
  },
  // 获取用户昵称
  getUserProfile(e) {
    this.setData({
      hasUserInfo: true
    })
    let _this = this
    // 推荐使用 wx.getUserProfile 获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: res => {
        // console.log('res: ', res.userInfo.nickName);
        // userInfo.nickName
        this.setData({
          userInfo: res.userInfo
        })
        let wx_user_info = wx.$storage.get('wx_user_info')
        // console.log('wx_user_info: ', wx_user_info);
        let obj = {
          ...wx_user_info,
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl
        }
        // console.log('obj',obj)
        wx.$storage.set('wx_user_info', obj)

        _this.onLoad(null)
      }
    })
  },
  onPageScroll: (function () {
    let timer = null
    return function (e) {
      // console.log("在滚动");
      // 监听页面的滚动开始和结束
      clearTimeout(timer)
      timer = setTimeout(() => {
        // console.log("滚动结束");
        wx.$eventbus.emit('evt_page_scroll', { scrollTop: e.scrollTop })
      }, 500)
    }
  })(),
  //视频弹窗
  videoplay(){
    wx.$eventbus.on('getvideo',(e)=>{
      // console.log('getvideo event bus: ', e);
      let obj = {
        videoTitle:e.title,
        videoSrc:e.src
      }
      this.getVideoUrl(obj)
      wx.nextTick(() => {
        this.videocomp.play();
      });
        
    })
  },
  //设置视频url
  getVideoUrl(params){
    this.setData(params)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
   onReady: function() {
    this.videocomp = this.selectComponent("#videocomp1");
    this.videoplay()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {
    // wx.nextTick(()=>{
    //   let {senceData ,actNum, activeNavIdx} = this.data
    //   console.log('senceData: ', senceData,actNum,activeNavIdx);
    //   let item = senceData[actNum]?.productList[activeNavIdx].proName;
    //   console.log('item: ', item);
    //   wx.setNavigationBarTitle({
    //     title: item.proName,
    //   })
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  /**
   * 浏览埋点
   */
  onShareTimeline() {},
  onViewTrack: true
})