// packageH/liveAuthorization/liveAuthorization_collection/liveAuthorization_collection.js
const app = getApp();
import util from '../../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    windowWidth: wx.getSystemInfoSync().windowWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    saveShow: false,
    canShow: false,
    popShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
    }
    this.getData();
    wx.setNavigationBarTitle({
      title: '直播授权码',
    });
  },
  init() {
    this.setData({
      posterId: '',
      page: 1,
      last_page: 1,
      current_page: 1
    });
  },
  cancelPopshow(e) {
    this.setData({
      popShow: false,
      posterId: '',
      shareName: ''
    });
  },
  tapCatch(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.key;
    this.setData({
      posterId: item.id,
      shareName: item.level_name
    });
    if (item.is_sold == "1") {
      this.setData({
        popShow: true
      });
    } else {
      this.data.info[index].show = !this.data.info[index].show;
      this.setData({
        info: this.data.info
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.current_page >= this.data.last_page) {
      return;
    } else {
      let pages = this.data.page + 1;
      this.setData({
        page: pages
      });
      this.getMore();
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let tit = '';
    let url = '';
    if (this.data.posterId) {
      tit = this.data.shareName;
      url = "/packageH/liveAuthorization/liveAuthorization_pay/liveAuthorization_pay?id=" + this.data.posterId;
    } else {
      tit = '直播授权码',
      url = "/packageH/liveAuthorization/liveAuthorization_collection/liveAuthorization_collection?id=" + this.data.id;
    }
    return {
      title: tit,
      path: url,
    };
  },
  getData() {
    let that = this;
    let uelStr = app.getNetAddresss("plugin.room.frontend.code.waitPay");
    app._getNetWork({
      url: uelStr,
      data: {
        level_id: that.data.id,
        page: that.data.page
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          for (let i = 0; i < res.data.data.length; i++) {
            res.data.data[i].show = false;
            res.data.data[i].created_at = util.formatTimeTwo(res.data.data[i].created_at, 'Y/M/D h:m:s');
          }
          that.setData({
            info: res.data.data,
            current_page: res.data.current_page,
            last_page: res.data.last_page
          });
          console.log(that.data.info);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMore() {
    let that = this;
    let uelStr = app.getNetAddresss("plugin.room.frontend.code.waitPay");
    app._getNetWork({
      url: uelStr,
      data: {
        level_id: that.data.id,
        page: that.data.page
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          for (let i = 0; i < res.data.data.length; i++) {
            res.data.data[i].show = false;
          }
          that.setData({
            info: that.data.info.concat(res.data.data),
            current_page: res.data.current_page,
            last_page: res.data.last_page
          });
          console.log(that.data.info);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getPoster() {
    this.setData({
      canShow: true,
      popShow: false
    });
    let that = this;
    setTimeout(() => {
      let query = wx.createSelectorQuery();
      query.select('.mycanvas').boundingClientRect(rect => {
        console.log('rect', rect);
        that.setData({
          canvasWidth: rect.width,
          canvasHeight: rect.height
        });
      }).exec();
    }, 300);
    wx.showLoading({
      title: '海报加载中',
    });
    let uelStr = app.getNetAddresss("plugin.room.frontend.goods-poster.new-goods-poster");
    app._getNetWork({
      url: uelStr,
      data: {
        id: that.data.posterId,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          // that.bgImg(res.data)\
          wx.hideLoading({
            success: (res) => {},
          });
          that.downfile(res.data);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  downfileCode(code) {
    wx.downloadFile({
      url: code, // 服务器返回的图片地址
      success: (res) => {
        let Path = res.tempFilePath;
        this.setData({
          codeImg: Path,
        });
        this.bgImg();
      },
      fail: function (res) {
        console.log(res);
        // 失败回调
      },
    });
  },
  downfile(e) {

    let that = this;
    let qrcode = e.qrcode;
    wx.downloadFile({
      url: e.backgroundImg, // 服务器返回的图片地址
      success: (res) => {
        let Path = res.tempFilePath;
        this.setData({
          backgroundImg: Path,
        });
        that.downfileCode(qrcode);
      },
      fail: function (res) {
        console.log(res);
        // 失败回调
      },
    });
  },
  bgImg: function () {
    //注意这里的 canvas 要与wxml文件的canvas-id属性命名一样
    const ctx = wx.createCanvasContext('canvas');
    let bgPicturePath = this.data.backgroundImg; //图片路径不要出错
    let bgCodeImg = this.data.codeImg;
    ctx.drawImage(bgPicturePath, 0, 0, this.data.canvasWidth, this.data.canvasHeight);
    ctx.drawImage(bgCodeImg, this.data.canvasWidth - 110, this.data.canvasHeight - 110, 90, 90);
    ctx.draw(true, this.popClose); //绘制背景图片
  },
  popClose() {
    let that = this;
    setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.data.canvasWidth,
        height: this.data.canvasHeight,
        destWidth: this.data.canvasWidth,
        destHeight: this.data.canvasHeight,
        canvasId: 'canvas',
        success(res) {
          wx.hideLoading({
            success: (res) => {},
          });
          that.setData({
            saveShow: true,
            saveImg: res.tempFilePath,
          });
        },
        fail:function(err){
          console.log(err);
        }
      });
    }, 300);
  },
  saveImge(e) {
    console.log('11111111');
    wx.saveImageToPhotosAlbum({
      filePath: this.data.saveImg,
      success(result) {
        wx.showToast({
          title: "图片保存成功",
          icon: "success",
          duration: 2000,
        });
      },
      fail: (res) => {
        console.log(res);
      },
    });
    wx.getSetting({
      success: function (res) {
        console.log(res.authSetting['scope.writePhotosAlbum']);
        if (res.authSetting['scope.writePhotosAlbum'] == false) {
          wx.showModal({
            content: "检测到您拒绝相册授权，是否去设置打开？",
            confirmText: "确认",
            cancelText: "取消",
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {}
                });
              }
            }
          });
        }
      }
    });

  },
  onClose(e) {
    this.setData({
      canShow: false,
      saveShow: false,
    });
  }
});