const app = getApp();
const utils = require('../../utils/util')
const wxService = require('../../utils/wxService')

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    avater: { // 图片
      type: String,
      value: ''
    },
    productDesc: { // 产品描述
      type: String,
      value: ''
    },
    userAvatar: { // 头像
      type: String,
      value: ''
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    productCode: "",
    showpost: false,
    imgHeight: 0,
    productCode: "" //二维码
  },

  attached() {
    // 获取小程序二维码 url
    this.getMiniCode()
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 关闭modal
    closePoste(){
      this.setData({
        showpost: false
      })
    },
    
    //下载产品图片
    getAvaterInfo: function () {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      });
      var that = this;
      that.setData({
        showpost: true
      })
      var productImage = that.data.avater;
      if (productImage) {
        wx.downloadFile({
          url: productImage,
          success: function (res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              var productSrc = res.tempFilePath;
              that.calculateImg(productSrc, function (data) {
                that.getQrCode(productSrc, data);
              })
            } else {
              wx.showToast({
                title: '产品图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var productSrc = "";
                  that.getQrCode(productSrc);
                }
              })
            }
          }
        })
      } else {
        wx.hideLoading();
        var productSrc = "";
        that.getQrCode(productSrc);
      }
    },

    //获取二维码
    getMiniCode() {
      const urls = utils.getCurrentPageUrlWithArgs()
      const page = urls && urls.split("?")[0]

      let data = {
        "autoColor": true,
        "page": 'pages/index/index',
        "scene": 'qwe',
        "width": 100
      }

      wxService.post(`/merchant/contentMobileTerminal/getAppletQrCode`, data).then(res => {
        const { result, data } = res.data
        if(result == 0){
          this.setData({
            // codeImg: data.codeUrl
            codeImg: "https://hwimagecdn.ihotwind.cn/usr/201908/miniQrCode-f00c5051fef7479395efb193431762c4.jpg"
          })
        }
        // if (result == 0) {
        //   const fsm = wx.getFileSystemManager();
        //   const FILE_BASE_NAME = 'tmp_base64src';

        //   const base64src = function (data) {
        //     return new Promise((resolve, reject) => {

        //       const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.png`;
        //       const buffer = wx.base64ToArrayBuffer(data);
        //       fsm.writeFile({
        //         filePath,
        //         data: buffer,
        //         encoding: 'binary',
        //         success() {
        //           resolve(filePath);
        //         },
        //         fail() {
        //           reject(new Error('ERROR_BASE64SRC_WRITE'));
        //         },
        //       });
        //     });
        //   };
        //   base64src(data).then(res => {
        //     console.log(res)
        //     this.setData({
        //       codeImg: res
        //     })
        //   })

        // }
      })
    },

    //下载二维码
    getQrCode: function (productSrc, imgInfo = "") {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      });
      var that = this;
      var productCode = that.data.codeImg;
      if (productCode) {
        wx.downloadFile({
          url: productCode,
          success: function (res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              var codeSrc = res.tempFilePath;
              that.sharePosteCanvas(productSrc, codeSrc, imgInfo);
            } else {
              wx.showToast({
                title: '二维码下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var codeSrc = "";
                  that.sharePosteCanvas(productSrc, codeSrc, imgInfo);
                }
              })
            }
          }
        })
      } else {
        wx.hideLoading();
        var codeSrc = "";
        that.sharePosteCanvas(productSrc, codeSrc);
      }
    },

    //canvas绘制分享海报
    sharePosteCanvas: function (avaterSrc, codeSrc, imgInfo) {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      })
      var that = this;
      const ctx = wx.createCanvasContext('myCanvas', that);
      var width = "";
      const query = wx.createSelectorQuery().in(this);
      query.select('#canvas-container').boundingClientRect(function (rect) {
        var height = rect.height;
        var right = rect.right;
        width = rect.width;
        var left = rect.left;
        console.log(rect)
        ctx.setFillStyle('#fff');
        ctx.fillRect(0, 0, rect.width, height);

        // 图片
        if (avaterSrc) {
          if (imgInfo) {
            var imgheght = parseFloat(imgInfo);
          }
          ctx.drawImage(avaterSrc, 0, 0, width, 270);
          ctx.setFontSize(14);
          ctx.setFillStyle('#d8d8d8');
          ctx.setTextAlign('left');
        }

        // 品牌头像
        if (that.data.userAvatar) {
          console.log(imgheght)
          // ctx.drawImage(that.data.userAvatar, 12, 306, 25, 25);
          ctx.drawImage(that.data.userAvatar, 12, 290, 40, 40);
          ctx.setFontSize(14);
          ctx.setFillStyle('#d8d8d8');
          ctx.setTextAlign('left');
          // ctx.fillText(that.data.userAvatar, left - 15, imgheght + 110); //电话
        }
        // title
        if (that.data.productDesc){
          ctx.setFontSize(12);
          ctx.setFillStyle('#333333');
          ctx.setTextAlign('left');
          ctx.fillText(that.data.productDesc, 61, 300); 
        }


        //产品金额
        // if (that.data.price || that.data.price == 0) {
        //   ctx.setFontSize(25);
        //   ctx.setFillStyle('#F57509');
        //   ctx.setTextAlign('left');
        //   var price = that.data.price;
        //   if (!isNaN(price)) {
        //     price = "¥" + that.data.price
        //   }
        //   ctx.fillText(price, left - 15, imgheght + 110); //电话
        // }


        //  绘制二维码
        if (codeSrc) {
          ctx.drawImage(codeSrc, 190, 281, 61.5, 61.5)
          ctx.setFontSize(10);
          ctx.setFillStyle('#000');
          // ctx.fillText("微信扫码或长按保存图片", left + 165, imgheght + 110);
        }
      }).exec()
      setTimeout(function () {
        ctx.draw();
        wx.hideLoading();
      }, 1000)
    },

    textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
      let strLength = 0; // text byte length
      let rows = 1;
      let str = 0;
      let arr = [];
      for (let j = 0; j < text.length; j++) {
        if (text.charCodeAt(j) > 255) {
          strLength += 2;
          if (strLength > rows * num) {
            strLength++;
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        } else {
          strLength++;
          if (strLength > rows * num) {
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        }
      }
      arr.push(text.slice(str, text.length));
      return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
    },

    //点击保存到相册
    saveShareImg: function () {
      var that = this;
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function (res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showModal({
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function (res) {
                    that.closePoste();
                    if (res.confirm) { }
                  },
                  fail: function (res) {
                    console.log(res)
                  }
                })
              },
              fail: function (res) {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
          fail: function (err) {
            console.log(err)
          }
        }, that);
      }, 1000);
    },


    //计算图片尺寸
    calculateImg: function (src, cb) {
      var that = this;
      wx.getImageInfo({
        src: src,
        success(res) {
          wx.getSystemInfo({
            success(res2) {
              var ratio = res.width / res.height;
              var imgHeight = 352.5;
              that.setData({
                imgHeight: imgHeight
              })
              cb(imgHeight - 130);
            }
          })
        }
      })
    },
    //快速分享到朋友圈
    quickShare() {
      console.log('222')
      this.setData({
        showpost: false
      })
      wxService.nextTick(() => {
      this.triggerEvent('showMiniCard', true)
      })
    }
  },

  
  
})