const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
var config = require("../../config/config.js");
var app = getApp();
const Http = require("../../utils/HttpBasics");
const util = require("../../utils/util");
const imgurl = require("../../utils/imgurl");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight, 
    poterbg: imgurl.poterbg.url, 
    windowWidth: wx.getSystemInfoSync().windowWidth,
    windowHeight: wx.getSystemInfoSync().screenHeight,
    totalHeight: 0,
    isdisable:true,
    mallname: '', //商场名字
    qrCodeL: "", //小程序码
    couponList: [], //活动劵列表
    canvasScale: 1.0 ,// 画布放大的倍数,因为如果保存的是一倍的分享图片的话，分享图会有点虚。所以保存的时候，canvasScale设置为2.0，wxss 里面的left: 500%;打开注释。就可保存两倍的分享图
    qrCode:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    //劵详情
    if (options && options.couponChannelId) {
      that.getDetail(options.couponChannelId);
    } else if (options && options.merchantId) {
      that.getList(options.merchantId);
      that.getCouponList(options.merchantId);
    }
    this.getUserInfo(options);
    
    
  },

  /**
   * 获取劵详情
   */
  getDetail: function(couponChannelId) {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.couponDetail,
      data: {
        couponChannelId: couponChannelId
      }
    }).then(res => {
      that.setData({
        data: res.data
      });
    });
  },
  /**
   * 获取商户详情
   */
  getList: function(id) {
    let that = this;
    let data;
    data = {
      pageNum: 1,
      pageSize: 15,
      id: id
    };
    Http.get({
        url: config.api.merchantList,
        data: data
      })
      .then(res => {
        that.setData({
          data: res.data.list[0]
        });
      })
      .catch(err => {
        wx.showToast({
          title: err.errMsg,
          icon: "none",
          duration: 2000,
          mask: false
        });
      });
  },
  /**
   * 绘制分享海报
   */
  begainDrawShareImage(options) {
    wx.showLoading({
      title: "生成中..."
    });
    var that = this;
    // 适配屏幕
    let scale = this.data.windowWidth / 375.0
    console.log(scale)
    this.setData({
      totalHeight: 667 * scale
    })

    // 获取Canvas
    let ctx = wx.createCanvasContext("myCanvas");
    // 获取宽高
    let wW = that.data.windowWidth;
    let wH = that.data.windowHeight;
    // 放大 因为不放大的话，生成的分享图会模糊。暂时先注释
    ctx.scale(this.data.canvasScale, this.data.canvasScale);
    // 首先要绘制顶部的背景图片，因为它在最底层，然后才能绘制其他内容
    let bgimg1 = that.data.poterbg + `?imageView/2/w/${wW}/h/${wH}`;
    let bgimg2 = util.getProxyImgUrl(bgimg1);
    
    wx.getImageInfo({
      src: bgimg2,
      success: function(res) {
        that.drawshopimg(ctx, scale, options);
        ctx.draw(true);
      }
    });
  },

  //绘制商品图片
  drawshopimg(ctx, scale, options) {
    var that = this;
    let topImageWidth = parseInt(355 * scale); // 因为小数有时候会请求不到图片，所以转成int
    let topImageHeight = parseInt(260 * scale);
    let src1 = "";
    let src2 = "";
    console.log(that.data.data.coverImg, "bgimg2")
    //劵详情海报
    if (options && options.couponChannelId) {
      src1 = that.data.data.coverImg + `?imageView/2/w/${topImageWidth}/h/${topImageHeight}`;
      src2 = util.getProxyImgUrl(src1);
    } else if (options && options.merchantId) {
      //商户详情海报
      src1 = that.data.data.merchantImgUrl + `?imageView/2/w/${topImageWidth}/h/${topImageHeight}`;
      src2 = util.getProxyImgUrl(src1);
    }
    // console.log(, "789")
    let tempArr = src2.split('?')
    if(tempArr.length>2){
      src2 = tempArr[0]+"?"+tempArr[1]+"&"+tempArr[2]
    }
    wx.getImageInfo({
      src: src2,
      success: function(res) {
        // 绘制白色背景   
        ctx.setFillStyle("#fbfbfb");
        ctx.fillRect(0, 0, that.data.windowWidth, that.data.windowHeight);
        ctx.drawImage(res.path, 0, 50, topImageWidth, topImageHeight);
        that.roundRect(ctx, 15 * scale, 270 * scale, 325 * scale, 125 * scale, 10* scale);
        that.drawOtherContent(ctx, scale, options);
        that.drawAvatarimg(ctx, scale);
        that.drawqrCode(ctx, scale);
        wx.hideLoading();
      }
    });
    this.setData({
      isdisable:false,
    })
  },
  //绘制微信头像
  drawAvatarimg(ctx, scale) {
    var that = this;
    //商户详情海报
    let src1 = that.data.avatarUrl + `?imageView/2/w/${100}/h/${100}`;
    let src2 = util.getProxyImgUrl(src1);
    
    wx.getImageInfo({
      src: src2,
      success: function(res) {
        console.log(res.path)
        that.darwAvatarArc(ctx, res.path, 10, 8, 35, 35);
      }
    });
  },
  // 商户海报绘制
  drawOtherContent(ctx, scale, options) {
    let that = this;
    console.log(ctx.measureText(this.data.nickName).width);

    //昵称
    this.drawNormalText(ctx, this.data.nickName, 48 * scale, 24 * scale, 16 * scale, "#000", "left", "middle", scale);

    this.drawNormalText(ctx, " 向您推荐", (ctx.measureText(this.data.nickName).width+60) * scale, 25 * scale, 16 * scale, "#848484", "left", "middle", scale);

    this.drawNormalText(ctx, "---" + this.data.mallname + "---", 175 * scale, 500 * scale, 16 * scale, "#000", "left", "middle", scale);
    if (options && options.merchantId) {
      //店铺名
      this.drawNormalText(ctx, "商户名称:" + this.data.data.merchantName,  30 * scale, 295 * scale, 20 * scale, "#000", "left", "middle", scale);
      // this.drawNormalText(ctx, "商户位置:" + this.data.data.shopVoList[0].buildingName + this.data.data.shopVoList[0].floorName + "--" + this.data.data.shopVoList[0].shopNumber, 30 * scale, 320 * scale, 15 * scale, "#F4AA91", "left", "middle", scale);
      this.drawNormalText(ctx, "商户电话:" + this.data.data.merchantLinkPhone, 30 * scale, 348 * scale, 16 * scale, "#000", "left", "middle", scale);
      this.drawNormalText(ctx, "长按识别，进店去看看", 155 * scale, 470 * scale, 16 * scale, "#000", "left", "middle", scale);
     
    } else if (options && options.couponChannelId) {
      this.drawNormalText(ctx, "长按识别，进店去看看", 155 * scale, 470 * scale, 16 * scale, "#000", "left", "middle", scale);
      // this.drawNormalText(ctx, this.data.data.title, 30 * scale, 295 * scale, 20 * scale, "#000", "left", "middle", scale);
      this.canvasTextAutoLine(this.data.data.title, ctx, 30 * scale, 295 * scale, 20 * scale, "#000", "left", "middle", 20, 260,1) 

      this.drawNormalText(ctx, "售价:" + this.data.data.salePriceStr + "元", 30 * scale, 320 * scale, 15 * scale, "#F4AA91", "left", "middle", scale);
      this.drawNormalText(ctx, "适用门店:", 30 * scale, 348 * scale, 16 * scale, "#000", "left", "middle", scale);

      //适用门店字体的排列
      for (let i = 0; i < that.data.data.merchantVoList.length;i++){   
        if(i==0){
          that.drawNormalText(ctx, that.data.data.merchantVoList[i].merchantName, 30, 375 * scale, 14 * scale, "#000", "left", "middle", scale);
        }else if(i==1){
          let width0=ctx.measureText(that.data.data.merchantVoList[0].merchantName).width
          that.drawNormalText(ctx, that.data.data.merchantVoList[i].merchantName, (width0+40)*scale, 375 * scale, 14 * scale, "#000", "left", "middle", scale);
        }else  if(i==2){
          let width0=ctx.measureText(that.data.data.merchantVoList[0].merchantName).width
          let width1=ctx.measureText(that.data.data.merchantVoList[1].merchantName).width
          that.drawNormalText(ctx, that.data.data.merchantVoList[i].merchantName+"...", (width1+width0+45)*scale, 375 * scale, 14 * scale, "#000", "left", "middle", scale);
        }
      }
      ctx.draw(true);
    }
    ctx.draw(true);
  },
  //绘制小程序码
  drawqrCode(ctx, scale) {
    let coImageWidth = parseInt(120 * scale);
    let coImageHeight = parseInt(120 * scale);
    let src1 = "";
    let src2 = "";
    console.log(this.data.qrCode, this.data.data.qrCode,"qrCode")
    if (this.data.qrCode) {
      src1 =
        this.data.qrCode + `?imageView/2/w/${coImageWidth}/h/${coImageHeight}`;
      src2 = util.getProxyImgUrl(src1);
    } else {
      src1 =this.data.data.qrCode +`?imageView/2/w/${coImageWidth}/h/${coImageHeight}`;
      src2 = util.getProxyImgUrl(src1);
    }
    wx.getImageInfo({
      src: src2,
      success: function(res) {
        ctx.drawImage(res.path, 25 * scale, 420 * scale, coImageWidth, coImageHeight);
        ctx.draw(true);
      }
    });
  },

  //截取商品名
  substrTile(str) {
    return str.substr(0, 5) + "...";
  },
  // 绘制只有一行的文字
  drawNormalText(ctx, str, x, y, font, style, align, baseLine) {
    ctx.setFontSize(font);
    ctx.setFillStyle(style);
    ctx.setTextAlign(align);
    ctx.setTextBaseline(baseLine);
    ctx.fillText(str, x, y);
  },
  /*
   *  绘制多行文本，自动换行，超出添加...
   *
   */
  canvasTextAutoLine: function(str,ctx,initX,initY,font,style,align,baseLine,lineHeight,maxWidth,row = 1) {
    var lineWidth = 0;
    var lastSubStrIndex = 0;
    var currentRow = 1;
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > maxWidth) {
        currentRow++;
        let newStr = str.substring(lastSubStrIndex, i);
        if (currentRow > row && str.length > i) {
          newStr = str.substring(lastSubStrIndex, i - 2) + "...";
        }
        ctx.setFontSize(font);
        ctx.setFillStyle(style);
        ctx.setTextAlign(align);
        ctx.setTextBaseline(baseLine);
        ctx.fillText(newStr, initX, initY);
        initY += lineHeight;
        lineWidth = 0;
        lastSubStrIndex = i;

        if (currentRow > row) {
          break;
        }
      }
      if (i == str.length - 1) {
        ctx.setFontSize(font);
        ctx.setFillStyle(style);
        ctx.setTextAlign(align);
        ctx.setTextBaseline(baseLine);
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
      }
    }
  },
  //绘制圆角图像
  darwAvatarArc: function(ctx, src, x, y, w, h = w) {
    /*
      ctx: 画布对象
      src: 头像缓存路径
      x: 头像起始位置 横坐标
      y: 头像起始位置 纵坐标
      w: 头像宽度
      h: 头像高度，不传为w
    */
    // 保存绘图上下文。
    ctx.save();
    // 开始创建一个路径。需要调用 fill 或者 stroke 才会使用路径进行填充或描边
    ctx.beginPath();
    // 设创建一个圆可以指定 起始弧度为 0，终止弧度为 2 * Math.PI。
    // 用 stroke 或者 fill 方法来在 canvas 中画弧线。
    ctx.arc(x + w / 2, y + h / 2, w / 2, 0, Math.PI * 2, false);
    /* 从原始画布中剪切任意形状和尺寸。
    一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内（
    不能访问画布上的其他区域）。可以在使用 clip 方法前通过使用 save 方法对当前画布区域进行保存，并在以后的任意时间通过restore方法对其进行恢复。
    */
    ctx.clip();
    // 画头像
    ctx.drawImage(src, x, y, w, h);
    // 恢复之前保存的绘图上下文。
    ctx.restore();
    // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
    ctx.draw(true);
  },
  //绘制圆角矩形
  roundRect: function(ctx, x, y, w, h, r, c = '#fff') {
    if (w < 2 * r) { r = w / 2; }
  if (h < 2 * r) { r = h / 2; }

  ctx.beginPath();
  ctx.fillStyle = c;

  ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.lineTo(x + w, y + r);

  ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
  ctx.lineTo(x + w, y + h - r);
  ctx.lineTo(x + w - r, y + h);

  ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
  ctx.lineTo(x + r, y + h);
  ctx.lineTo(x, y + h - r);

  ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
  ctx.lineTo(x, y + r);
  ctx.lineTo(x + r, y);

  ctx.fill();
  ctx.closePath();
  },
  //获取商户优惠劵信息
  getCouponList: function(id) {
    let that = this;
    let data;
    data = {
      status: 0, 
      merchantId: id,
      pageNum: 1,
      pageSize: 15
    };
    Http.post({
        url: config.api.listByMerchant,
        data: data
      })
      .then(res => {
        if (res.data && res.data.qrCode) {
          that.setData({
            qrCode: res.data.qrCode,
          })
        }
        that.setData({
          couponList: res.data.page.list
        });
      })
      .catch(err => {
        wx.showToast({
          title: err.errMsg,
          icon: "none",
          duration: 2000,
          mask: false
        });
      });
  },
  //获取头像和昵称
  getUserInfo: function (options) {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.getScore,
      data: {}
    }).then(res => {
      let nickName = '';
      if (res.data.nickName == undefined || res.data.nickName == undefined) {
        wx.getUserInfo({
          success: function (data) {
            nickName = data.userInfo.nickName;
            that.setData({
              nickName: nickName,
              avatarUrl: data.userInfo.avatarUrl
            });
            that.getMallInfo(options);
          }
        })
        
      } else {
        nickName = res.data.nickName;
        that.setData({
          nickName: nickName,
          avatarUrl: res.data.avatarUrl
        });
        that.getMallInfo(options);
      }
      
    });
  },
  //商场信息
  getMallInfo: function (options) {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.getMallInfo,
      data: {}
    }).then(res => {
      console.log(res);
      that.setData({
        mallname: res.data.name
      });
      that.begainDrawShareImage(options);
    });
  },
  /**
   * 保存图片
   */
  saveImage() {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: this.data.windowWidth * this.data.canvasScale,
      height: this.data.totalHeight * this.data.canvasScale,
      canvasId: "myCanvas",
      success: function(res) {
        that.saveImageToPhotos(res.tempFilePath);
      },
      fail: function(res) {
        wx.showToast({
          title: "图片生成失败",
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  
  saveImageToPhotos: function(tempFilePath) {
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success(result) {
        wx.showToast({
          title: "保存成功，从相册中分享到朋友圈吧",
          icon: "none",
          duration: 4000
        });
      },
      fail: function(err) {
        if (
          err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
          err.errMsg === "saveImageToPhotosAlbum:fail auth deny"
        ) {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: "提示",
            content: "需要您授权保存相册",
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata);
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    wx.showModal({
                      title: "提示",
                      content: "获取权限成功,再次点击图片即可保存",
                      showCancel: false
                    });
                  } else {
                    wx.showModal({
                      title: "提示",
                      content: "获取权限失败，将无法保存到相册哦~",
                      showCancel: false
                    });
                  }
                },
                fail(failData) {
                  console.log("failData", failData);
                },
                complete(finishData) {
                  console.log("finishData", finishData);
                }
              });
            }
          });
        }
      }
    });
  }
});