const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const util = require("../../../utils/util");
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({
  data: {
    showIdFalg: false,
    navigationBarHeight,
    code: "",
    topLine: imgurl.topLine.url,
    btomLine: imgurl.btomLine.url,
    lineUrl: imgurl.line.url,
    wm01Url: imgurl.wm01.url,
    wm02Url: imgurl.wm02.url,
    wm03Url: imgurl.wm03.url,
    upDataRqUrl: imgurl.upDataRq.url,
    upDataRqUrlF: imgurl.upDataRqF.url,
    wm04Url: imgurl.wm04.url,
    teljpgUrl: imgurl.teljpg.url,
    newUrl: imgurl.new1.url,
    data: {
      salePrice: null,
      price: null,
      usePrice: null
    },
    createDate: "",
    expiredTime: "",
    validStartDate: "",
    validEndDate: "",
    updateDate: "",
    //存储计时器
    setInter: "",
    staticGamedata: {},
    showIf: false,
    curHtml: '',
    showhieRq: false,
    dynamicRq: "",
    expiredSeconds: 0,
    templTiem: "",
    mallList: []
  },
  onUnload: function () {
    let that = this;
    clearInterval(that.data.setInter);
    clearInterval(that.data.templTiem);
  },
  onHide: function () {
    let that = this;
    clearInterval(that.data.setInter);
    clearInterval(that.data.templTiem);
  },
  gotogame: function () {
    let that = this;
    wx.redirectTo({
      url: '/pages/game/index?url=' + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
    })
  },
  // 获取游戏
  getStaticGame(token) {
    let _this = this;
    Http.get({
      url: config.api.getGame,
      data: {
        triggleAction: 4 // 核销触发
      }
    }).then(res => {
      if (res.data.id) {
        _this.setData({
          showIf: true
        })
      }
      _this.setData({
        staticGamedata: res.data
      })
    })
      .catch(err => {
        wx.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  // onShow(options) {
  //   setTimeout(function () {
  //     wx.setScreenBrightness({
  //       value: 0.7,
  //     })
  //   }, 200)
  // },
  setRq() {
    let _this = this
    _this.setData({
      showhieRq: false,
    })
    Http.get({//获取动态二维码
      url: config.api.dynamicId,
      data: {
        couponOrderId: _this.data.code
      }
    }).then(res => {
      console.log(res, "res")
      _this.setData({
        dynamicRq: res.data.dynamicId,
        expiredSeconds: res.data.expiredSeconds
      })
      let url = JSON.stringify({
        END: "C",
        TYPE: "couponorder",
        ID: _this.data.dynamicRq
      })
      if (res.data.expiredSeconds == 0) {

      } else {

        let inre = setInterval(() => {
          if (_this.data.expiredSeconds > 1) {
            _this.setData({
              expiredSeconds: _this.data.expiredSeconds - 1
            })
            console.log("有效", _this.data.expiredSeconds)
          } else {
            console.log("无效", _this.data.expiredSeconds)
            clearInterval(_this.data.templTiem)
            _this.setData({
              showhieRq: true
            })
          }
        }, 1000)
        _this.setData({
          templTiem: inre
        })
      }
      // util.qrcode("qrcode", url, 350, 350);
      _this.createQrCode(url, "qrcode", 350, 350);
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },

  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
      })
    }
  },

  onLoad: function (options) {
    console.log(options, 'options');
    let that = this;
    that.setData({
      code: options.quancode,
      codeS: options.quancode.slice(0, 4) + `******` + options.quancode.slice(14),
      couponorderstatus: options.couponorderstatus
    });

    if (
      options.quancode &&
      that.data.couponorderstatus == 0
    ) {
      //aaa
      that.setRq()//动态二维码 //这个方法必须在拿到 options.quancode 后调用
      that.getHtml(options.quancode);
      // Http.get({
      //   url: config.api.couponMerchant,
      //   data: {
      //     couponChannelId: options.quancode
      //   }
      // }).then(res => {
      //   const keys = Object.keys(res.data)
      //   const mallList = []
      //   keys.forEach(item => {
      //     const arr = item.split('|')
      //     const obj = {
      //       tenantId: arr[0],
      //       mallName: arr[1],
      //       merchantVoList: res.data[item],
      //       expand: true
      //     }
      //     mallList.push(obj)
      //   })
      //   this.setData({
      //     mallList: mallList
      //   })
      //   console.log(this.data.mallList, 'mallList');
      // })
    }
    //获得优惠券的详情
    that.data.setInter = setInterval(function () {
      if (
        options.quancode &&
        that.data.couponorderstatus == 0
      ) {

        Http.get({
          url: config.api.couponOrderDetail,
          data: {
            couponOrderId: options.quancode
          }
        }).then(res => {
          that.setData({
            couponorderstatus: res.data.couponOrderStatus,
            data: res.data,
          });
          if (res.data.couponOrderStatus == 1) {
            /**
             * 动态改变上一级页面的核销状态
             */

            that.getStaticGame()
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; //上一个页面
            //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
            prevPage.setData({
              mystatus: res.data.couponOrderStatus
            });
          }
          that.setData({
            expiredTime: util.formatTime(that.data.data.expiredTime, "yyyy-MM-dd hh:mm:ss"),
            updateDate: util.formatTime(that.data.data.updateDate, "yyyy-MM-dd hh:mm:ss"),
            createDate: util.formatTime(that.data.data.createDate, "yyyy-MM-dd hh:mm:ss")
          });
          if (that.data.data.soldStartTime && that.data.data.soldEndTime) {
            that.setData({
              soldStartTime: util.formatTime(that.data.data.soldStartTime, "yyyy-MM-dd hh:mm:ss"),
              soldEndTime: util.formatTime(that.data.data.soldEndTime, "yyyy-MM-dd hh:mm:ss"),
              validStartDate: util.formatTime(res.data.validStartDate, "yyyy-MM-dd hh:mm:ss"),
              validEndDate: util.formatTime(res.data.validEndDate, "yyyy-MM-dd hh:mm:ss"),
            })
          }

        })
          .catch(err => {
            wx.showToast({
              title: err.errMsg,
              icon: 'none',
              duration: 2000,
              mask: false
            });
          })
      }
    }, 2000);

    /**
     * 页面需要初始渲染的效果
     */
    Http.get({
      url: config.api.couponOrderDetail,
      data: {
        couponOrderId: options.quancode
      }
    }).then(res => {
      that.setData({
        couponorderstatus: res.data.couponOrderStatus,
        data: res.data
      });
      that.setData({
        expiredTime: util.formatTime(that.data.data.expiredTime, "yyyy-MM-dd hh:mm:ss"),
        updateDate: util.formatTime(that.data.data.updateDate, "yyyy-MM-dd hh:mm:ss"),
        createDate: util.formatTime(that.data.data.createDate, "yyyy-MM-dd hh:mm:ss")
      });
      if (that.data.data.validStartDate && that.data.data.validEndDate) {
        that.setData({
          validStartDate: util.formatTime(that.data.data.validStartDate, "yyyy-MM-dd hh:mm:ss"),
          validEndDate: util.formatTime(that.data.data.validEndDate, "yyyy-MM-dd hh:mm:ss")
        })
      }

    })
      .catch(err => {
        wx.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  getHtml(couponChannelId) {
    Http.get({
      url: config.api.couponHtmlDetailForPkg,
      data: {
        // couponChannelId: '433119630735183872'
        couponOrderId: couponChannelId
      }
    }).then(res => {
      if (res.code == 200 && res.data.html) {
        this.setData({
          curHtml: decodeURI(res.data.html),
        })
      }
    })
  },
  upDataRq() {
    console.log(1123)
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    let that = this;
    QR.api.draw(url, canvasId, cavW, cavH, function (res) {
      that.setData({
        tempFilePath: res
      })
    });
  },
  phone: function (e) {
    let that = this;
    if (e.currentTarget.dataset.merchantlinkphone) {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.merchantlinkphone
      });
    }
  }
});