const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
var config = require("../../config/config.js");
const Http = require("../../utils/HttpBasics");
const imgurl = require("../../utils/imgurl");
const QR = require("../../utils/memberqrcode.js");
let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    rightHr: imgurl.rightHr.url,
    navigationBarHeight,
    erweima: imgurl.erweima.url,
    bannerUrl: imgurl.banner.url,
    loadingUrl: imgurl.loading.url,
    nodata: imgurl.noCoupon.url,
    wmhome: imgurl.wmhome.url,
    barcode: imgurl.barcode.url,
    list: [],
    lists: [],
    arrays: [],
    myLists: [],
    page: 1, // 设置加载的第几次，默认是第一次
    pageSize: 10, //返回数据的个数
    searchLoadingComplete: false, //“没有数据”的变量，默认false，隐藏
    allow_load: true, // 是否允许继续加载标识  默认 true 允许，false 加载完成
    myorder: false,
    actUrl: imgurl.act.url,
    loading: true,
    content: '数据正在加载中',
    reloadIf: false,
    creditAmount: '',
    score: '0',
    sort: '',
    hidden: false,
    userCredit: '',
    sortColumn: '',
    sortOrder: '',
    goHomeUrl: "",
    userAvatarUrl: '',//
    userName: '',
    isPhone: false
  },

  gotograde() {
    if (this.data.isPhone) {
      wx.navigateTo({
        url: '/pages3/setUserInfo/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?path=integralmall`,
      })
    }
  },

  qrcodeH() {
    var that = this;
    let memberId = that.data.memberId;
    if (memberId) {
      if (this.data.isPhone) {
        wx.navigateTo({
          url: '/pages/specialcourtesy/specialcourtesy'
        })
      } else {
        wx.navigateTo({
          url: `/pages/getphoneInfo/index?path=integralmall`,
        })
      }
    }
  },
  goback: function () {
    let this_ = this
    wx.switchTab({
      url: this_.data.goHomeUrl,
    })
  },
  onLoad: function (options) {
    console.log(app.globalData.userName, app.globalData.userAvatarUrl, 9999)
    let that = this;
    that.setData({
      goHomeUrl: app.globalData.goHomeUrl,
      userAvatarUrl: app.globalData.userAvatarUrl,
      userName: app.globalData.userName
    })
    var todayDate = new Date().getTime();
    that.getPoints();
    that.setData({
      optionsData: options,
      todayDate: todayDate
    })
    if (options && options.from == 'myhtml') {
      that.getmyList();
    }
    else {
      that.getList(1);
      that.setData({
        lists: null
      })
    }
  },
  onShow() {
    let that = this;
    if (this.data.reloadIf) {
      wx.setNavigationBarTitle({
        title: '积分商城'
      })
      that.getList(1);
      that.setData({
        lists: null
      })
    };
    Http.get({
      url: config.api.getScore,
      data: {}
    }).then(res => {
      if (res.data.address && res.data.name && res.data.sex && res.data.birthdate) {
        that.setData({
          showEdit: true
        })
      }
      that.setData({
        score: res.data.score,
        levelName: res.data.levelName,
        upgradePercent: res.data.upgradePercent,
        upgradeScore: res.data.upgradeScore,
        ismember: true,
        memberId: res.data.id
      })
      var size = this.setCanvasSize();
      var initUrl = JSON.stringify({
        flagid: res.data.id
      });
      that.createQrCode(initUrl, "mycanvas1", size.w, size.h);
    })
      .catch(err => {
        wx.showModal({
          title: '提示',
          content: err.message,
          showCancel: false
        })
      })

    this.checkUserPhone()

  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 500;
      //不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;
      //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
  },
  qrcode: function (e) {
    var that = this;
    that.setData({
      showQrcode: true
    })
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 2000
    });
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize();
      var url = JSON.stringify({
        END: "C",
        TYPE: "memberCode",
        ID: that.data.memberId,
      })
      that.createQrCode(url, "mycanvas1", size.w, size.h);
      that.setData({
        maskHidden: true
      });
      clearTimeout(st);
    }, 1000)
  },
  // 获得积分，渲染页面
  getPoints() {
    let that = this;
    Http.get({
      url: config.api.integralList,
      data: {
        pageNum: 1,
        pageSize: 1,
      }
    }).then(res => {
      wx.stopPullDownRefresh();
      that.setData({
        creditAmount: res.data.list[0].creditAmount,
      });
    })
      .catch(err => {
        wx.stopPullDownRefresh();
        wx.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },

  gotojifen() {
    if (this.data.isPhone) {
      wx.navigateTo({
        url: '/pages/integralmall/integraHistory/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?path=integralmall`,
      })
    }
  },
  //我可换购
  canSort() {
    let that = this;
    if (that.data.creditAmount !== 0) {
      that.setData({
        allow_load: true,
        userCredit: that.data.creditAmount,
        page: 1
      })
      that.getList(1)
    }
    if (that.data.creditAmount == 0) {
      wx.showToast({
        title: '快去补充积分吧！',
        icon: 'none',
        duration: 2000,
        mask: false
      });
    }
  },
  //所需积分
  need: function () {
    var that = this;
    var hid = this.data.hidden;
    if (hid == true) {
      hid = false;
      that.setData({
        allow_load: true,
        sort: imgurl.up.url,
        sortOrder: 'desc',
        sortColumn: 'creditPrice',
        page: 1
      })
      that.getList(1)
    }
    else {
      hid = true;
      that.setData({
        sort: imgurl.down.url,
        sortOrder: 'asc',
        sortColumn: 'creditPrice',
        allow_load: true,
        page: 1
      })
      that.getList(1)
    }
    this.setData({
      hidden: hid // 改变状态
    })
  },
  getList(pageNum) {
    var that = this;
    if (that.data.allow_load) {
      that.setData({
        loading: true,
        content: '小主,我在玩命加载中...'
      })
      var param = {
        pageNum: pageNum,
        pageSize: 10,
        targetAd: 50,
        sortColumn: that.data.sortColumn,
        sortOrder: that.data.sortOrder,
        userCredit: that.data.userCredit
      };
      var url = config.api.couponChannelList;
      // 请求接口
      Http.get({
        url: url,
        data: param,
      }).then(res => {
        console.log(res)
        /**
         * 加载完成
         */
        if (pageNum >= res.data.pages) {
          if (res.data.pages == 0 || res.data.pages == 1) {
            that.setData({
              allow_load: true,
              loading: false,
              content: ""
            });
          } else {
            that.setData({
              allow_load: false,
              loading: true,
              content: "——— 再拉裤子就掉了啦 ———",
            });
          }
        }
        if (pageNum == 1) {
          that.setData({
            lists: [],
          })
        }
        var tmpArr = that.data.lists;
        // tmpArr = [...tmpArr, ...res.data.list];
        tmpArr.push.apply(tmpArr, res.data.list);
        that.setData({
          lists: tmpArr
        })
        wx.stopPullDownRefresh();
      })
        .catch(err => {
          wx.stopPullDownRefresh();
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        })
      setTimeout(function () {
        that.setData({
          loading: false,
        })
      }, 1400);
    } else {
      that.setData({
        loading: true,
        content: "——— 再拉裤子就掉了啦 ———"
      })
      setTimeout(function () {
        that.setData({
          loading: false,
        })
      }, 1400)
    }
  },

  checkUserPhone() {
    const that = this
    Http.get({
      url: config.api.checkPhoneStatus
    }).then(res => {
      that.setData({
        isPhone: true
      })
      console.log(this.data.isPhone, 'isPhone');
    }).catch(err => {
      that.setData({
        isPhone: false
      })
      console.log(this.data.isPhone, 'isPhone');
    })
  },

  /**
   * 
   * @param goto拼团券详情
   */
  invite: function (e) {
    let couponChannelId = e.currentTarget.dataset.id;
    let couponId = e.currentTarget.dataset.couponid;
    if (couponChannelId && couponId) {
      wx.navigateTo({
        url: `/pages/coupon/detail/index?couponChannelId=${couponChannelId}&couponId=${couponId}`
      })
    }
  },
  //加载更多
  onReachBottom: function () {
    let that = this;
    that.data.page++;
    that.setData({
      page: that.data.page
    });
    that.getList(that.data.page, that.data.flag);
  },
  /**
  * 刷新
  */
  onPullDownRefresh: function (e) {
    let that = this;
    that.setData({
      sort: '',
      sortColumn: '',
      sortOrder: '',
      userCredit: '',
      page: 1,
      allow_load: true,
    })
    that.getList(1);
    that.getPoints();
  }
})