<template>
  <view class="draw-style1">
    <u-top-tips ref="uTips"></u-top-tips>
    <img :src="tempPic" mode="widthFix" :style="{ width: 750 * zoom + 'px' }" />
    <canvas
      canvas-id="firstCanvas"
      class="sty-box"
      @error="canvasIdErrorCallback"
    ></canvas>
  </view>
</template>

<script>
export default {
  props: {
    autoHeight: {
      type: String,
      default: "0",
    },
    images: {
      type: Array,
      default: [],
    },
    bgType: {
      type: Number,
      default: 0,
    },
    bgColor: {
      type: String,
      default: "",
    },
    info: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      zoom: 1,
      config: {
        images: [],
        bgType: 1,
        bgColor: "",
        info: {},
        loca_images: [],
      },
      ctx: null,
      tempPic: "",
      qrcodepic:""
    };
  },
  watch: {
    images: {
      handler: function (val, oldval) {
        this.config.images = val;
        this.drawCtx();
      },
      deep: true,
    },
    bgType: {
      handler: function (val, oldval) {
        this.config.bgType = val;
        this.drawCtx();
      },
      deep: true,
    },
    bgColor: {
      handler: function (val, oldval) {
        this.config.bgColor = val;
        this.drawCtx();
      },
      deep: true,
    },
    info: {
      handler: function (val, oldval) {
        this.config.info = val;
        this.drawCtx();
      },
      deep: true,
    },
  },
  mounted() {
    console.log("in draw");

    this.zoom = (parseFloat(this.autoHeight) / 1344.0).toFixed(2);
    this.config.images = this.images;
    this.config.bgType = this.bgType;
    this.config.bgColor = this.bgColor;
    this.drawCtx();
  },
  onReady: function (e) {},
  methods: {
    colorRgb(color) {
      var sColor = color.toLowerCase();
      //十六进制颜色值的正则表达式
      var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
      // 如果是16进制颜色
      if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
          var sColorNew = "#";
          for (var i = 1; i < 4; i += 1) {
            sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
          }
          sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
          sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return sColorChange.join(",");
      }
      return sColor;
    },
    saveImage() {
      uni.showLoading({
        title: "正在生成海报",
      });
      let that = this;
      uni.canvasToTempFilePath(
        {
          canvasId: "firstCanvas",
          success: (res) => {
            uni.hideLoading();
            uni.showLoading({
              title: "正在保存海报",
            });
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function () {
                uni.showToast({
                  title: "保存成功",
                });
              },
              fail: function (err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
					uni.authorize({
						scope:'scope.writePhotosAlbum',
						success: (res) => {
							console.log('11111');
						},
						fail: (res) => {
							uni.showModal({
								content:'检测到您没打开保存到相册权限，是否去设置打开？',
								confirmText: "确认",
								cancelText:'取消',
								success: (res) => {
									if(res.confirm){
										uni.openSetting({
											success: (res) => {
												console.log(res);
												if(res.authSetting['scope.writePhotosAlbum']){
													that.saveImage()
												}
											}
										})
									}else{
										console.log('取消');
									}
								}
							})
						}
					})
                }else{
					  that.$refs.uTips.show({
						title: "保存失败，请稍后重试",
						type: "error",
						duration: "2300"
					  });
                }
              },
              complete: function () {
                uni.hideLoading();
              },
            });
          },
          fail: function (e) {
            console.log(e);
            that.$refs.uTips.show({
              title: "生成失败，请稍后重试",
              type: "error",
              duration: "2300",
            });
          },
        },
        this
      );
    },
    drawCtx() {
      uni.showLoading({
        title: "正在生成海报",
      });
      let ctx = uni.createCanvasContext("firstCanvas", this);
      let that = this;
      if (!this.info.avatar_loca) {
        uni.getImageInfo({
          src: this.info.avatar,
          success: function (image) {
            that.info.avatar_loca = image.path;
            uni.getImageInfo({
              src:
                "https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/three-love.png",
              success: function (bxImg) {
                that.drawBg(ctx);
                that.config.bixin = bxImg.path;
                that.drawAvatar(ctx);
                that.drawTitle(ctx);
                that.drawGoodPicture(ctx);
              },
            });
          },
        });
      } else {
        this.drawBg(ctx);
        this.drawAvatar(ctx);
        this.drawTitle(ctx);
        this.drawGoodPicture(ctx);
      }
    },
    drawGoodPicture(ctx) {
      console.log(this.config.images);
      if (this.config.images.length == 1) {
        this.drawOnePic(ctx);
      } else if (this.config.images.length == 2) {
        this.drawTowPic(ctx);
      } else if (this.config.images.length == 3) {
        this.drawThreePic(ctx);
      } else if (this.config.images.length == 4) {
        this.drawFourPic(ctx);
      } else if (this.config.images.length == 5) {
        this.drawFivePic(ctx);
      }
    },
    drawAvatar(ctx) {
      ctx.save();
      ctx.beginPath();
      ctx.arc(85, 90, 50, 0, Math.PI * 2);
      ctx.setFillStyle("#ffffff");
      ctx.fill();
      ctx.clip();
      ctx.drawImage(this.info.avatar_loca, 35, 40, 100, 100);
      ctx.restore();
    },
    drawTitle(ctx) {
      ctx.fillStyle = "#333333";
      ctx.font = "24px 'microsoft yahei'";
      ctx.fillText("我看上了这款商品", 165, 64);
      ctx.fillText("帮我看看咋样啊~", 165, 103);
      ctx.fillText("比心~", 165, 147);
      ctx.drawImage(this.config.bixin, 235, 125, 24, 24);
    },
    drawBg(ctx) {
      if (this.config.bgType == 1) {
        ctx.fillStyle = this.config.bgColor;
        ctx.fillRect(0, 0, 750, 1344);
      } else {
        let g = ctx.createLinearGradient(0, 0, 0, 1344);
        g.addColorStop(0, this.config.bgColor);
        console.log(`rgba(${this.colorRgb(this.config.bgColor)},0.3)`);
        g.addColorStop(1, `rgba(${this.colorRgb(this.config.bgColor)},0.3)`);
        ctx.fillStyle = g;
        ctx.fillRect(0, 0, 750, 1344);
      }
    },
    drawQrCode(ctx) {
      let that = this;
      if (this.qrcodepic == "") {
        uni.getImageInfo({
          src: this.info.qrcode_url,
          success: function(image) {
            that.qrcodepic=image.path
            ctx.drawImage(image.path, 50, 1085, 232, 232);
            that.finishPic(ctx);
          }
        });
      } else {
        
        ctx.drawImage(that.qrcodepic, 50, 1085, 232, 232);
        that.finishPic(ctx);
      }
    },
    finishPic(ctx) {
      let that = this;
      ctx.draw(false, () => {
        uni.canvasToTempFilePath(
          {
            x: 0,
            y: 0,
            width: 750,
            height: 1344,
            destWidth: 750.0,
            destHeight: 1344.0,
            canvasId: "firstCanvas",
            success: res => {
              console.log(res);
              uni.hideLoading();
              that.tempPic = res.tempFilePath;
            },
            fail(e) {
              console.log(e);
            }
          },
          that
        );
      });
    },
    drawOnePic(ctx) {
      let that = this;
      if (!this.config.loca_images[0]) {
        uni.getImageInfo({
          src: this.config.images[0],
          success: function (image) {
            that.config.loca_images[0] = image.path;
            ctx.drawImage(image.path, 36, 176, 678, 678);
            that.otherDraw(ctx);
          },
        });
      } else {
        ctx.drawImage(this.config.loca_images[0], 36, 176, 678, 678);
        that.otherDraw(ctx);
      }
    },
    drawTowPic(ctx) {
      if (this.config.loca_images.length < 2) {
        let that = this;
        uni.getImageInfo({
          src: this.config.images[this.config.loca_images.length],
          success: function (image) {
            that.config.loca_images.push(image);
            that.drawTowPic(ctx);
          },
        });
      } else {
        ctx.fillStyle = "#000";
        ctx.fillRect(36, 176, 678, 339);
        var imgRect = this.coverImg(
          678,
          339,
          this.config.loca_images[0].width,
          this.config.loca_images[0].height
        );
        ctx.drawImage(
          this.config.loca_images[0].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          36,
          176,
          678,
          339
        );

        ctx.fillStyle = "#000";
        ctx.fillRect(36, 515, 678, 339);
        var imgRect = this.coverImg(
          678,
          339,
          this.config.loca_images[1].width,
          this.config.loca_images[1].height
        );
        ctx.drawImage(
          this.config.loca_images[1].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          36,
          515,
          678,
          339
        );

        this.otherDraw(ctx);
      }
    },
    drawThreePic(ctx) {
      if (this.config.loca_images.length < 3) {
        let that = this;
        uni.getImageInfo({
          src: this.config.images[this.config.loca_images.length],
          success: function (image) {
            that.config.loca_images.push(image);
            that.drawThreePic(ctx);
          },
        });
      } else {
        ctx.fillStyle = "#000";
        ctx.fillRect(36, 176, 678, 339);
        var imgRect = this.coverImg(
          678,
          339,
          this.config.loca_images[0].width,
          this.config.loca_images[0].height
        );
        ctx.drawImage(
          this.config.loca_images[0].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          36,
          176,
          678,
          339
        );
        ctx.drawImage(this.config.loca_images[1].path, 36, 515, 339, 339);
        ctx.drawImage(this.config.loca_images[2].path, 375, 515, 339, 339);
        this.otherDraw(ctx);
      }
    },
    drawFourPic(ctx) {
      if (this.config.loca_images.length < 4) {
        let that = this;
        uni.getImageInfo({
          src: this.config.images[this.config.loca_images.length],
          success: function (image) {
            that.config.loca_images.push(image);
            that.drawFourPic(ctx);
          },
        });
      } else {
        ctx.drawImage(this.config.loca_images[0].path, 36, 176, 339, 339);
        ctx.drawImage(this.config.loca_images[1].path, 375, 176, 339, 339);
        ctx.drawImage(this.config.loca_images[2].path, 36, 515, 339, 339);
        ctx.drawImage(this.config.loca_images[3].path, 375, 515, 339, 339);
        this.otherDraw(ctx);
      }
    },
    drawFivePic(ctx) {
      if (this.config.loca_images.length < 5) {
        let that = this;
        uni.getImageInfo({
          src: this.config.images[this.config.loca_images.length],
          success: function (image) {
            console.log(image);
            that.config.loca_images.push(image);
            that.drawFivePic(ctx);
          },
        });
      } else {
        ctx.drawImage(this.config.loca_images[0].path, 36, 176, 339, 339);
        ctx.drawImage(this.config.loca_images[1].path, 36, 515, 339, 339);

        ctx.fillStyle = "#000";
        ctx.fillRect(375, 176, 339, 226);
        var imgRect = this.coverImg(
          339,
          226,
          this.config.loca_images[2].width,
          this.config.loca_images[2].height
        );
        ctx.drawImage(
          this.config.loca_images[2].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          375,
          176,
          339,
          226
        );
        ctx.fillStyle = "#000";
        ctx.fillRect(375, 402, 339, 226);
        imgRect = this.coverImg(
          339,
          226,
          this.config.loca_images[3].width,
          this.config.loca_images[3].height
        );
        ctx.drawImage(
          this.config.loca_images[3].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          375,
          402,
          339,
          226
        );
        ctx.fillStyle = "#000";
        ctx.fillRect(375, 628, 339, 226);
        imgRect = this.coverImg(
          339,
          226,
          this.config.loca_images[4].width,
          this.config.loca_images[4].height
        );
        ctx.drawImage(
          this.config.loca_images[4].path,
          imgRect.sx,
          imgRect.sy,
          imgRect.sWidth,
          imgRect.sHeight,
          375,
          628,
          339,
          226
        );
        this.otherDraw(ctx);
      }
    },
    coverImg(box_w, box_h, source_w, source_h) {
      var sx = 0,
        sy = 0,
        sWidth = source_w,
        sHeight = source_h;
      if (source_w > source_h || (source_w == source_h && box_w < box_h)) {
        sWidth = (box_w * sHeight) / box_h;
        sx = (source_w - sWidth) / 2;
      } else if (
        source_w < source_h ||
        (source_w == source_h && box_w > box_h)
      ) {
        sHeight = (box_h * sWidth) / box_w;
        sy = (source_h - sHeight) / 2;
      }
      return {
        sx,
        sy,
        sWidth,
        sHeight,
      };
    },

    otherDraw(ctx) {
      this.showGoodName(ctx);
      this.showGoodPrice(ctx);
      this.showTips(ctx);
      this.drawQrCode(ctx);
    },
    showGoodPrice(ctx) {
      ctx.fillStyle = "#333";
      ctx.font = "26px 'microsoft yahei'";
      let x = 285;
      let y = 990;
      ctx.fillText("￥", x, y);
      ctx.fillStyle = "#333";
      ctx.font = "40px 'microsoft yahei'";
      ctx.fillText(this.info.min_price, 315, y);

      ctx.beginPath();
      ctx.fillStyle = "#FFF";
      ctx.fillRect(36, 1055, 678, 2);
    },
    showTips(ctx) {
      ctx.fillStyle = "#333";
      ctx.font = "24px 'microsoft yahei'";
      let x = 320;
      let y = 1225;
      ctx.fillText("长按识别小程序码 即可查看~", x, y);
    },
    showGoodName(ctx) {
      ctx.fillStyle = "#333333";
      ctx.font = "30px 'microsoft yahei'";
      let maxWidth = 618;
      let n = this.info.goods_name;
      let lines = 1;

      let x = 60;
      let y = 910;
      for (let i = 0; i < lines; i++) {
        let lineText = "";
        let currentWidth = 0;
        for (let x = 0; x < n.length; x++) {
          currentWidth += ctx.measureText(n[x]).width;
          if (currentWidth > maxWidth) {
            break;
          } else {
            lineText += n[x];
          }
        }
        ctx.fillText(lineText, x, y + i * 55);
        n = n.substring(lineText.length);
        if (n == "") {
          break;
        }
      }
      if (n != "") {
        ctx.fillText("...", x + maxWidth, y);
      }
    },
    canvasIdErrorCallback: function (e) {
      console.error(e.detail.errMsg);
    },
  },
};
</script>

<style>
.draw-style1 {
  width: 100%;
  height: 100%;
  background: #fff;
  position: relative;
  overflow: hidden;
  z-index: 2;
}
.draw-style1 .sty-box {
  width: 750px;
  height: 1344px;
  position: absolute;
  top: -2000px;
  left: -1500px;
}
</style>
