var app = getApp()
var that=null
var sopenFrame=null
var  mCanvas

Page( {
  data: {
    loadingHidden:false,
    ewmpic:"",
    width:300,
    height:400,
    sjylmoney: 0,
    smzemoney: 0,
    zsymoney: 0,
    jrmoney:0,
    zrmoney:0,
    IFDefault:false,
    savetitle:"保存商家收款码到相册"
  },
  onLoad: function() {
      that = this
      that.rdata()
    }, // 下拉刷新
    onPullDownRefresh: function () {
      that.rdata()
    },rdata: function() {
      
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var userInfodata = wx.getStorageSync("userInfo")
      var userInfo = JSON.parse(userInfodata)
      
      wx.request({
        url: app.globalData.apiurl + "/xapiajax.ashx", 
        data: { 
          action:"getmybusinessdata",
           userId:(!userId?"":userId),
           LoginId:(!LoginId?"":LoginId)
        },
        method:"GET",
        dataType:"json", 
        success (res) { 
         
          if(res.data.status==1){
            that.setData({
              sjylmoney: res.data.sjylmoney,
              smzemoney: res.data.smzemoney,
              zsymoney: res.data.zsymoney,
              jrmoney:res.data.jrmoney,
              zrmoney:res.data.zrmoney,
              IFDefault:(res.data.userInfo.Paypush==1?true:false),
              width:300,
              height:400,
              loadingHidden:true
             })
             wx.createSelectorQuery().select('#myCanvas')
             .fields({ node: true, size: true })
             .exec((res0) => {
                 let textCanvas = res0[0].node;  // 重点1
                 mCanvas=textCanvas
                 let textCtx = textCanvas.getContext('2d');  // 重点2
                 const dpr = wx.getSystemInfoSync().pixelRatio
                 var w=res0[0].width
                 var h=res0[0].height
                 textCanvas.width = w * dpr
                 textCanvas.height = h * dpr
                 textCtx.scale(dpr, dpr)
                 textCtx.clearRect(0,0,textCanvas.width,textCanvas.height)
                 textCtx.beginPath(); 
                 //绘制背景
                 textCtx.fillStyle = '#fff'
                 textCtx.clearRect(0,0, textCanvas.width, textCanvas.height)
                 textCtx.fillRect(0, 0, textCanvas.width, textCanvas.height)
                 
                 const bg = textCanvas.createImage();
                 bg.src = '../../images/skm.png';
                 bg.onload = () => {
                       textCtx.drawImage(bg, 0, 0, w, h)
                       let text1 = res.data.sjname
                       let len=((w-text1.length*20)/2)
                 textCtx.fillStyle = "#000";
                 textCtx.font = "22px Arial";
                 textCtx.fontWeight = 'bold'
                 //textCtx.textAlign = 'center'
                 that.getWarpText(textCtx, text1, len, 100, w, 52, 1)
                 
                 if(res.data.ewmpic!=""){
                  const bg0 = textCanvas.createImage();
                  bg0.src = res.data.ewmpic;
                  bg0.onload = () => {
                   
                        textCtx.drawImage(bg0, ((w-145)/2), 130, 145, 145) 
                  } 
                 }
                 }
                 
                 
                
           })
          }else{
            
          }
        }
        })
            
    },onxz: function(e) {
      that.setData({
        savetitle:"保存中，请稍候..."
      })
      
      // 检查权限
      wx.getSetting({
        success: function(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            // 未授权，请求授权
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function() {
                // 授权成功，执行保存
                that.saveImage();
              },
              fail: function() {
                // 授权失败，引导用户去设置
                wx.showModal({
                  title: '提示',
                  content: '需要授权保存到相册权限',
                  confirmText: '去授权',
                  success: function(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function(settingRes) {
                          if (settingRes.authSetting['scope.writePhotosAlbum']) {
                            that.saveImage();
                          }
                        }
                      })
                    }
                  }
                })
              }
            })
          } else {
            // 已授权，直接保存
            that.saveImage();
          }
        }
      })
    },
    
    // 提取保存图片的逻辑到单独函数
    saveImage: function() {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      
      wx.canvasToTempFilePath({
        canvasId: "myCanvas",
        destWidth: 520,
        destHeight: 720,
        canvas: mCanvas,
        success: function(res0) {
          const tempFilePath = res0.tempFilePath;
          
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              console.log(res);
              wx.showModal({
                title: '图片保存成功',
                content: '图片成功保存到相册了，去发圈噻~',
                showCancel: false,
                confirmText: '好哒',
                confirmColor: '#72B9C3',
                success: function (res0) {
                  if (res0.confirm) {
                  
                  }
                  that.setData({
                    QRcodeHidden: true,
                    savetitle:"保存商家收款码到相册"
                  })
                }
              })
            },
            fail: function(err) {
              console.log('saveImageToPhotosAlbum fail:', err);
              wx.showToast({
                title: '保存失败：' + err.errMsg,
                icon: "none",
                duration: 3000
              })
              that.setData({
                savetitle:"保存商家收款码到相册"
              })
            }
          })
        },
        fail: function(err) {
          console.log('canvasToTempFilePath fail:', err);
          wx.showToast({
            title: '生成图片失败：' + err.errMsg,
            icon: "none",
            duration: 3000
          })
          that.setData({
            savetitle:"保存商家收款码到相册"
          })
        }
      })
    },onsmlog: function(e) {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var userInfodata = wx.getStorageSync("userInfo")
      if(userId&&LoginId&&userInfodata){
          var t = e.currentTarget.dataset.id
           wx.navigateTo({  
               url: "../mybusiness_smlog/index?t=" + t
           })
       }else{
         wx.navigateTo({  
            url: "../login/index"
         })   
      }
    },onzzlog:function(e) {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      if(!userId||!LoginId){
            wx.navigateTo({  
              url: "../login/index"
             })
      }else{
              wx.navigateTo({  
                  url: "../zzjf_log/index"
              }) 
      }
    },changeisDefault:function(e) {
      var t = (e.detail.value==true?1:0)
      var userId = wx.getStorageSync("userId")
          var LoginId = wx.getStorageSync("LoginId")
        wx.request({
          url: app.globalData.apiurl + "/xapiajax.ashx", 
          data: { 
            action:"updatePaypush",
             userId:(!userId?"":userId),
             LoginId:(!LoginId?"":LoginId),
             t:t
          },
          method:"POST",
          dataType:"json", 
          header: { 
            "content-type": "application/x-www-form-urlencoded" // 默认值
          },
          success (res) { 
            if(res.data.status==1){
              wx.showToast({
                title: res.data.msg,
                icon: "success",
                duration: 3000
               })
               wx.setStorageSync('userInfo', JSON.stringify(res.data.userInfo)) 
                that.rdata()
            }else{
             
               wx.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 3000
               })
            }
            }
        })
    },onsjzl:function(e) {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      if(!userId||!LoginId){
            wx.navigateTo({  
              url: "../login/index"
             })
      }else{
              wx.navigateTo({  
                  url: "../mybusiness_info/index"
              }) 
      }
    },onsylog: function(e) {
      var userId = wx.getStorageSync("userId")
      var LoginId = wx.getStorageSync("LoginId")
      var userInfodata = wx.getStorageSync("userInfo")
      if(userId&&LoginId&&userInfodata){
           wx.navigateTo({  
               url: "../zzjf_sylog/index?t=5"
           })
       }else{
         wx.navigateTo({  
            url: "../login/index"
         })   
      }
    },getWarpTextMulti:function(canvas, arrText, y, gap = 10) {
      for (let index = 0; index < arrText.length; index++) {
        const text = arrText[index];
        let lineArr = getWarpText(canvas, text, MARGIN_LEFT, y, MAX_WIDTH, LINE_HEIGHT)
        y += LINE_HEIGHT * lineArr.length + gap
      }
    },getWarpText:function(canvas, text, x, y, maxWidth, lineHeight, maxLine) {
      // 对入参的类型进行检测
      if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number' || typeof lineHeight != 'number') {
        throw new Error("参数传入出错")
      }
      //如果最大宽度未定义 默认为canvas宽度
      if (typeof maxWidth == 'undefined') {
        maxWidth = (canvas && canvas.width);
      }
      if (typeof lineHeight == 'undefined') {
        lineHeight = (canvas.canvas && parseInt(window.getComputedStyle(canvas.canvas).lineHeight)) ||
          parseInt(window.getComputedStyle(document.body).lineHeight)
      }
      let arrText = text.split('');
      let line = '';
      let lines = [];
      let lastLine = ""
      let ellipsis = canvas.measureText("...");
      let ellipsisWidth = ellipsis.width;
      for (let n = 0; n < arrText.length; n++) {
        //每个循环累加字符
        let testLine = line + arrText[n];
        //检测累加字符 获取累加字符的高度和宽度
        let metrics = canvas.measureText(testLine);
        let testWidth = metrics.width;
        let lineWidth = canvas.measureText(line).width;
    
        // 如果当前添加行是最后一行 则替换最后一个字符为"..." 判断长度是否需要删去最后一个字符
        if (maxLine && maxLine - 1 === lines.length && ((lineWidth + ellipsisWidth) > maxWidth)) {
          line = line.slice(0, line.length - 1) + "...";
          testWidth = lineWidth + ellipsisWidth;
        }
        //如果累加字符的宽度大于定义的绘制文本最大宽度 则绘制累加字符的文本 并且设置换行间距再次进行绘制
        if (testWidth > maxWidth && n > 0) {
          lastLine = line;
          lines.push({
            text: line,
            x: x,
            y: y
          })
          if (maxLine && maxLine <= lines.length) {
            break
          }
          line = arrText[n];
          y += lineHeight;
        } else {
          line = testLine;
        }
      }
      if (lastLine !== line) {
        lines.push({
          text: line,
          x: x,
          y: y
        })
      }
      for (let i = 0; i < lines.length; i++) {
        const item = lines[i];
        canvas.fillText(item.text, item.x, item.y);
      }
      return lines;
    }
})
