questionnaire.js 5.07 KB
// packageMine/pages/questionnaire/questionnaire.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    finish: false
  },
  answerList: {},
  blur(e) {
    const {
      value
    } = e.detail, {
      num
    } = e.currentTarget.dataset
    this.change({
      detail: {
        num,
        value
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(options)
  },
  async getQuestionnaireDetail(options) {
    const res = await wx.p.router.intercept()
    if (!res) {
      const {
        userInfo
      } = this.data
      if (!userInfo.nickName) return this.getNickNameAndHeadUrl()
      try {
        const data = await wx.p.api.questionnaireApi.getQuestionnaireDetail(options)
        if (data.status == -1) {
          return wx.showModal({
            title: '温馨提示',
            content: '问卷活动已结束。',
            showCancel: false,
            confirmText: '返回首页',
            confirmColor: '#3772EC',
            complete: (res) => {
              if (res.confirm) wx.p.router.goHome()
            }
          })
        }
        if (data) {
          data.questions.map(e => {
            if (e.type != 3) {
              let option = e.option.split('\n')
              if (e.type == 5) {
                const [, two, three] = option[0].split('/')
                option.splice(0, 1)
                e.data = this.transformData(option, three ? 3 : two ? 2 : 1)
              } else e.data = option
            }
            e.answer = ''
            e.userFormId = e.formId
          })
          this.setData({
            questionnaireObj: data
          })
          wx.setNavigationBarTitle({
            title: data.title,
          })
          this.shareTitle = data.cardTitle || data.title
          this.shareQuery = `id=${data.id}`
          this.shareImage = data.cardCover || ''
          this.addTrackInfo()
        } else throw '获取问卷失败'
      } catch (error) {
        console.log(error)
        if (error) wx.p.wxApi.showToast(error)
      }
    }
  },
  transformData(data, childrenDepth) {
    const result = []
    data.forEach(item => {
      const levels = item.split('/')
      let currentLevel = result
      for (let i = 0; i < childrenDepth; i++) {
        const text = levels[i],
          value = text,
          existingOption = currentLevel && currentLevel.find((option) => option.text === text)
        if (existingOption) {
          if (i === childrenDepth - 1) {
            continue
          }
          if (existingOption.children) currentLevel = existingOption.children
        } else {
          if (text && value) {
            const newOption = {
              text,
              value,
            }
            if (levels[i + 1]) newOption.children = []
            currentLevel.push(newOption)
            if (i === childrenDepth - 1) delete newOption.children
            currentLevel = newOption.children
          }
        }
      }
    })
    return result
  },
  change(e) {
    const {
      num,
      value
    } = e.detail
    this.answerList[num] = value
  },
  async submit() {
    const {
      questionnaireObj
    } = this.data, {
      merchantId,
    } = wx.p.storage.get('userInfo'), {
      answerList
    } = this
    try {
      let questions = []
      questionnaireObj.questions.map(e => {
        if (e.required && answerList[e.num] == null) throw `请填写第${e.num}题!`
        questions.push({
          userFormId: e.userFormId,
          num: e.num,
          answer: answerList[e.num] || ''
        })
      })
      let params = {
        questions,
        merchantId,
        formId: questionnaireObj.id,
      }
      console.log(params)
      const res = await wx.p.api.questionnaireApi.submitQuestionnaireForm(params)
      if (res) {
        this.setData({
          finish: true
        })
      } else throw '提交失败'
      console.log(res)
    } catch (error) {
      console.log(error)
      if (error) wx.p.wxApi.showToast(error)
    }
  },
  getNickNameAndHeadUrl() {
    const redirectUrl = `https://scrm.glsx.com.cn/wy-wx-oauth`,
      appid = 'wx1cf40dc91c28a7fd',
      wxUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUrl)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    wx.p.router.jumpH5(wxUrl)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const {
      options
    } = this
    if (options.id) this.getQuestionnaireDetail(options)
  },


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

  },
  // 添加埋点信息
  addTrackInfo(){
    const {userInfo} = this.data
    let item = {
      add_way: '104',
      customer_phone: userInfo.phone
    }
    if (userInfo.nickName) {
      item.customer_qw_nickname = userInfo.nickName
    }
    if (userInfo.headImgUrl) {
      item.avatar = userInfo.headImgUrl
    }
    if (userInfo.unionId) {
      item.union_id = userInfo.unionId
    }
    let json = JSON.stringify(item)
    // 数据上报
    wx.p.api.common.trackHttp({ json }).then(response => { })
  }
})