checkProduct.js 8.94 KB
const navStyle = "background-color: #fff";
import { senceData } from "~/pages/tab/discovery/constant/data";
import Draw from "~/utils/Draw.js";
import { IMG_URL,IMG_VERSION } from "~/utils/constantData.js";
import {
  commonApi
} from '~/api/api.js'
const IMGURL = IMG_URL
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navStyle,
    img_version:IMG_VERSION(),
    headerHeight: 0,
    senceData,
    actNum: 0,
    activeNavIdx: 0,
    fromLocal: 0,
    // 模态框
    isShow: true,
    showAuth: false,
    btnList: [
      {
        src: `${IMGURL}down.png`,
        name: "下载海报",
      },
      {
        src: `${IMGURL}wechat.png`,
        name: "转发给好友",
      }
    ],
    posterUrl: "", //海报url
  },
  navbarReady(e) {
    let {
      height
    } = e.detail;
    this.setData({
      headerHeight: height,
    });
  },
  onPageScroll({
    scrollTop
  }) {
    let opacity = scrollTop / 100
    let color = `rgba(255,255,255${opacity > 1 ? 1 : opacity})`
    this.setData({
      navStyle: scrollTop == 0 ? navStyle : `background-color:${color};`
    })
    wx.$eventbus.emit('evt_page_scroll',{scrollTop})
  },
  // 分享按钮
  sharehandle() {
    this.setData({
      isShow: true,
    });
  },
  setRouteParams(obj){
    const {actNum, activeNavIdx, fromLocal} = obj
    let name = wx.$storage.get('userInfo') ? wx.$storage.get('userInfo').name : ''
    this.shareTitle = `${name}给你分享一个${senceData[actNum].productList[activeNavIdx].proName}~`
    this.shareQuery = `actNum=${actNum}&activeNavIdx=${activeNavIdx}`
    wx.setNavigationBarTitle({
      title: senceData[actNum].name || '特色产品'
    })
    this.setData({
      actNum,
      activeNavIdx,
      fromLocal
    })
  },
  createImg(){
    if(this.data.fromLocal==1){
      let { actNum,activeNavIdx,senceData } = this.data;
      let v = new Date().getTime()
      let img = `${IMGURL}scene/longpic${actNum + 1}.jpg?v=${v}`
      wx.showLoading({
        title: '海报生成中...',
      })
      wx.getImageInfo({
        src: img,
        success:(res)=> {
          let imgW = res.width/4, imgH =res.height/4; 
          let pradH = 288*imgW/1029,  qrcodeH = 100;
          let drawFun = new Draw({
            width: imgW ,
            height: imgH + pradH
          });
          // let scene = {
          //   actNum,
          //   activeNavIdx
          // }
          let params = {
            scene: `actNum=${actNum}&activeNavIdx=${activeNavIdx}`,
            path: 'pages/checkProduct/checkProduct'
          }
          commonApi.createQrcode(params).then(response => {
            wx.showLoading({
              title: '海报生成中...',
            })
            if(response?.data){
              let qrcode = response?.data
              this.setData({
                imgH: (imgH/imgW)*450
              })
              console.log( actNum,activeNavIdx,senceData)
              // let textList = [
              //   {
              //     x: imgW/4+22,
              //     y: 15,
              //     text: senceData[actNum].productList[activeNavIdx].proName,
              //     textBaseline: 'top'
              //   },
              //   {
              //     x: imgW/4+22,
              //     y: (imgW/4+12)/2,
              //     color: '#7A8299',
              //     text: `${senceData[actNum].productList[activeNavIdx].varType==1?'三年售后存量数':'新车销量'} ${senceData[actNum].productList[activeNavIdx].sale}`,
              //   },
              //   {
              //     x: imgW/4+22,
              //     y: imgW/4,
              //     text: '预估收益',
              //     maxWidth: 50,
              //     color: '#7A8299'
              //   },
              //   {
              //     x: imgW/4+77,
              //     y: imgW/4,
              //     text: `¥${senceData[actNum].productList[activeNavIdx].profit}`,
              //     color: '#F35251',
              //     fontSize: 14,
              //     fontWeight: 500
              //   }
              // ]
              let imageList = [
                {
                  x: 0,
                  y: 0,
                  width: imgW,
                  height: pradH,
                  url: `${IMGURL}canvas/${senceData[actNum].productList[activeNavIdx].img}.png`,
                },
                {
                  x: 0,
                  y: pradH,
                  width: imgW,
                  height: imgH,
                  url: img,
                },
                {
                  x: imgW-qrcodeH,
                  y:  imgH + pradH -qrcodeH -20,
                  width: qrcodeH,
                  height: qrcodeH,
                  url: qrcode, //二维码
                },
              ];
              drawFun.begin({
                imageList
              }).then(resp => {
                this.setData({
                  posterUrl: resp.path,
                });
                wx.hideLoading()
                if(resp.path){
                  wx.saveImageToPhotosAlbum({
                    filePath: resp.path, //仅为示例,并非真实的资源
                    success:(res)=> {
                      wx.$api.showToast('下载成功!')
                    }
                  })
                }
              })
            }else{
              wx.$api.showToast('接口异常')
            }
          })
        },
        fail:(err)=>{
          wx.$api.showToast(err || '接口异常')
        }
      })
    }  
  },
  // 分享按钮
  handleClick(e) {
    let { index } = e.currentTarget.dataset;
    switch (index) {
      case 0:
        this.download();
        break;
      case 1:
        this.wechatFn();
        break;
    }
  },
  // 微信转发
  wechatFn() {
    // this.data.onShareAppMessage()
    this.modelClose();
  },
  // 下载海报
  download() {
    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.createImg()
              }
            }
          })
        }
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  authFail(){
    wx.showToast({
      title: "下载海报前需要您授权'添加到相册'权限",
      icon: "none",
      duration: 2500,
    });
  },
  authSuccess(){
    this.setData({
      showAuth:false
    })
    this.createImg()
  },
  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,
                  });
                }
              }
            })
          }
        }
      })
    })
  },
  //模态框关闭
  modelClose() {
    // this.setData({
    //   isShow: false
    // });
  },
  // 图片加载事件
  onloadFn(event) {
    this.setData({
      imgHeight: (event.detail.height * 0.2).toFixed(0),
    });
  },
  onRoute(options) {
   
    
  },
  noPageAuth : true,
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    wx.nextTick(()=>{
      let { actNum, activeNavIdx, scene } = this.options
      // let name = wx.$storage.get('staff_name') || (wx.$storage.get('userInfo') ? wx.$storage.get('userInfo').name : '')
      if(scene){
        let qrcodeQuery = decodeURIComponent(scene)
        let id = qrcodeQuery.split('=').pop()
        let paramsObj = {}
        if(id){
          commonApi.getQrcodeParams({id}).then(res => {
            if(res.code=='0'){
              let paramsArr = res?.data?.scene?.split('&');
              paramsArr.forEach(item => {
                let keyValArr =  item?.split('=');
                paramsObj[keyValArr[0]] = keyValArr[1]
              })
              this.setRouteParams({...paramsObj, fromLocal: 0})
            }
          })
        }
      }else{
        this.setRouteParams(this.options)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {},
  onShareTimeline() {},

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});