const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px';
const util = require("../../../utils/util.js");
const config = require("../../../config/config.js");
const Http = require("../../../utils/HttpBasics");
let app = getApp();
const imgurl = require("../../../utils/imgurl");
const QR = require("../../../utils/memberqrcode.js");
Page({
  // https://formall.oss-accelerate.aliyuncs.com/cimg/wm01.jpg
  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight,
    topLine: imgurl.topLine.url,
    btomLine: imgurl.btomLine.url,
    upDataRqUrlF: imgurl.upDataRqF.url,
    data: {},
    showIdFalg: false,
    code: '',
    codeS: '',
    tempFilePath: '',
    QRdata: {},
    isShowQR: true,
    showhieRq: false,
    cardId: '',
    showImg: ''
  },

  cardDetail(couponOrderId) {
    let that = this;
    Http.get({
      url: config.api.cardDetail,
      data: {
        couponOrderId: couponOrderId,
      }
    })
      .then(res => {
        console.log(res)
        if (res.code == 200) {
          res.data.expiredTime = util.formatTime(res.data.expiredTime, "yyyy-MM-dd hh:mm:ss")
          that.setData({
            showPage: true,
            data: res.data,
            supportTransfer: res.data.supportTransfer,
            code: res.data.id,
            codeS: res.data.id.slice(0, 4) + `******` + res.data.id.slice(14),
          })

          if (res.data.wxCardInfo.status) {
            this.setData({
              isShowQR: false
            })
          } else {
            that.getQR(res.data.id, res.data.tenantId, res.data.wxCardInfo.ownerUserId)
            const tempObj = {
              id: res.data.id,
              tenantId: res.data.tenantId,
              ownerUserId: res.data.wxCardInfo.ownerUserId
            }
            this.setData({
              QRdata: tempObj
            })
          }

          /**
           * 若可转赠获取用户头像信息
           */
          if (that.data.merchantVoList && that.data.merchantVoList.length <= 4) {
            that.setData({
              height: that.data.merchantVoList.length * 140 + 'rpx',
              showMore: false
            })
          } else if (that.data.merchantVoList && that.data.cardDetail.length > 4) {
            that.setData({
              height: 4 * 140 + 'rpx'
            })
          }
        }
      })
      .catch(err => {
        console.log(err)
      })
  },

  showId() {
    let this_ = this;
    if (!this_.data.showIdFalg) {
      wx.showModal({
        content: '是否查看完整券码',
        success(res) {
          if (res.confirm) {
            this_.setData({
              showIdFalg: true
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      this.setData({
        showIdFalg: false
      })
    }
  },

  reQR() {
    this.setData({
      showhieRq: false
    })
    const QRdata = this.data.QRdata
    this.getQR(QRdata.id, QRdata.tenantId, QRdata.ownerUserId)
  },

  // 获取动态二维码
  getQR(cardId, cardTenantId, cUserId) {
    Http.get({
      url: `/couponOrder/cardDynamicId?cardId=${cardId}&cardTenantId=${cardTenantId}&cUserId=${cUserId}`,
    }).then(res => {
      console.log(res.data);
      let timer
      let expiredSeconds = res.data.expiredSeconds
      if (expiredSeconds) {
        this.setData({
          expiredSeconds: expiredSeconds
        })
        timer = setInterval(() => {
          if (expiredSeconds != 0) {
            this.setData({
              expiredSeconds: expiredSeconds
            })
            expiredSeconds--
          } else {
            clearInterval(timer)
            this.setData({
              showhieRq: true
            })
          }
        }, 1000);
      }

      let url = JSON.stringify({
        END: "C",
        TYPE: "Ecard",
        ID: res.data.dynamicId,
        TENANTID: res.data.cardTenantId,
      })
      this.createQrCode(url, "qrcode", 350, 350);

    }).catch(err => {
      console.log(err, 'err');
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  },

  goGive() {
    wx.navigateTo({
      url: `/pages/ConsumeDetail/ConsumeDetail?cardId=${this.data.data.id}`,
    })
  },

  goSetSecurity() {
    wx.showModal({
      title: '设置支付密码',
      placeholderText: '请设置密码，不设则默认为无密码',
      editable: true,
      complete: (res) => {
        if (res.cancel) {
          console.log(res);
        }

        if (res.confirm) {
          const numReg = /^\d+$/
          const isNum = numReg.test(res.content)
          if (res.content) {
            if (!isNum || (res.content.length != 6)) {
              wx.showToast({
                title: '密码只能为6位数字',
                icon: 'none'
              })
              return
            } else {
              this.setPassword(1, res.content)
            }
          } else {
            this.setPassword(0, '')
          }
        }
      }
    })
  },

  setPassword(payCheck, pwd) {
    Http.post({
      url: config.api.updatePayPassword,
      data: {
        id: this.data.data.id,
        payCheck: payCheck,
        payPassword: pwd
      }
    }).then(res => {
      wx.showToast({
        title: '设置成功！',
        icon: 'success'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500);
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'error'
      })
    })
  },

  goCheck() {
    wx.navigateTo({
      url: `/pages/ConsumeDetail/ConsumeDetail?cardId=${this.data.data.id}`,
    })
  },

  // 无法转赠
  goGiveNone() {
    if (this.data.data.amount !== this.data.data.remainingAmount) {
      wx.showToast({
        title: '该卡已消费，不支持转增',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: '该卡不支持转增',
        icon: "error"
      })
    }

  },

  // 扫一扫去支付
  gotoPay: function () {
    app.globalData.previewFlag = true
    let that = this;
    wx.scanCode({
      success: (res) => {
        if (util.isJSON(res.result)) {
          let value = JSON.parse(res.result);
          if (value.END == 'B' && value.TYPE == 'merchant' && value.ID) {
            Http.get({
              url: config.api.findByCode,
              data: {
                merchantCode: value.ID,
              }
            })
              .then(res => {
                if (res.code == 200) {
                  let merChantDetail = JSON.stringify(res.data);
                  if (merChantDetail && that.data.data.id && (that.data.data.remainingAmount)) {
                    merChantDetail = encodeURIComponent(merChantDetail)
                    console.log(that.data.data, 'data');
                    wx.navigateTo({
                      url: `/pages/scanPay/scanPay?merChant=${merChantDetail}&cardid=${that.data.data.id}&remainingAmount=${that.data.data.remainingAmount / 100}&payCheck=${that.data.data.payCheck}`,
                    })
                  }
                }
              })
              .catch(err => {
                console.log(err)
              })
          } else {
            wx.showToast({
              title: "未识别到商户二维码",
              icon: "none",
              mask: false
            })
          }
        } else {
          wx.showToast({
            title: "未识别到商户二维码",
            icon: "none",
            mask: false
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: "未识别到商户二维码",
          icon: "none",
          mask: false
        })
      }
    })
  },

  createQrCode: function (url, canvasId, cavW, cavH) {
    console.log('createQrCode!');
    //调用插件中的draw方法，绘制二维码图片
    let that = this;
    QR.api.draw(url, canvasId, cavW, cavH, function (res) {
      that.setData({
        tempFilePath: res
      })
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options.cardId) {
      this.cardDetail(options.cardId);
      this.setData({
        cardId: options.cardId,
        showImg: options.showImg
      })
    }
    console.log(this.data.showImg, 'showImg');
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.cardDetail(this.data.cardId);
  },

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

  },

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

  },

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

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

  },

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

  }
})