<template>
  <view class="process" v-if="status == 1">
    <!-- <view class="process-header"> -->
    <!-- 			<view class="process-header-text">
				<view class="process-header-text-neishi" @click="topgi">
					<view class="process-header-text-icon">
						<image src="https://cdn.bjtdba.com/vod/image/2022-08-11/20220811133828415.png" mode="widthFix">
						</image>
					</view>
				</view>
				<view class="process-header-text-title">
					聚合码
				</view>
			</view> -->
    <!-- </view> -->
    <view class="activite-nav">
      <view class="activite-card">
        <image
          class="activite-card-logo"
          src="https://cdn.bjtdba.com/vod/image/2025-02-18/20250218234259970.png"
          mode=""
        ></image>

        <view class="activite-cardImg">
          <image :src="qrcode_src" mode="widthFix" ref="imagRef"></image>
        </view>
        <view class="activite-cardText">{{ code_id }}</view>
        <view class="activite-cardBtn"> 扫码即得养老金 </view>
        <view class="activite-cardPrompt">
          <view class="activite-prompt">
            <view class="activite-prompt-left"></view>
            <view class="activite-prompt-title">支持以下付款</view>
            <view class="activite-prompt-right"></view>
          </view>
          <view class="activite-prompt-img">
            <image
              src="https://cdn.bjtdba.com/vod/image/2022-08-23/20220823141611538.png"
              mode=""
            ></image>
            <image
              src="https://cdn.bjtdba.com/vod/image/2022-08-23/20220823141556288.png"
              mode=""
            ></image>
          </view>
        </view>
      </view>
      <!-- <image class="activite-card-logo" :src="imageUrl" mode=""></image> -->
      <!-- <view class="downLoadButton" @click="clickGeneratePicture">
        <image
          class="downLoad-image"
          src="../../static/saveImage.png"
          mode=""
        ></image>
        <view class="downLoad-text"> 保存图片 </view>
      </view> -->
      <view class="downLoadButton" @click="clickGeneratePicture2">
        <image
          class="downLoad-image"
          src="../../static/saveImage.png"
          mode=""
        ></image>
        <view class="downLoad-text"> 保存图片 </view>
      </view>
    </view>

    <!-- ************************* 海报画板 **********************-->
    <view style="position: absolute; bottom: 10%; left: 0%" v-show="flag">
      <l-painter
        v-if="poster"
        :board="poster"
        css="width: 750rpx;heigth:200rpx"
        isCanvasToTempFilePath
        @success="handleSuccess($event)"
        @fail="handleError($event)"
        @progress="handleProgress($event)"
        ref="posterRef"
      >
      </l-painter>
    </view>

    <!-- ************************* 海报画板 **********************-->
    <canvas
      canvas-id="container"
      id="container"
      :style="{
        width: canvasWidth + 'rpx',
        height: canvasHeight + 'rpx',
        opacity: 1,
      }"
    ></canvas>
  </view>
</template>

<script>
import { queryByKey } from "@/commit/shop.js";
import lPainter from "@/uni_modules/lime-painter/components/l-painter/l-painter.vue";
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";

export default {
  components: {
    lPainter,
  },
  data() {
    return {
      isShowType: false,
      qrcode_src: "",
      code_id: "",
      status: "",
      picture: "",
      isHide: true,
      poster: null,
      image: "",
      flag: false,
      canvasWidth: 300, // 单位：rpx
      canvasHeight: 300,
      imageUrl: "",
    };
  },
  onLoad(e) {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    this.$nextTick(() => {
      this.queryByKey();
    });
    this.qrcode_src = e.qrcode_src;
    this.code_id = e.code_id;
  },
  methods: {
    queryByKey() {
      const _this = this;
      queryByKey({
        key: "merchant_xiaochengxu_shenhe",
      }).then(
        (res) => {
          if (res.data.status == 200) {
            this.status = res.data.data.status;
            uni.hideLoading();

            this.$nextTick(() => {
              _this.drawPoster();
            });
          }
        },
        (fail) => {
          console.log(fail);
          uni.hideLoading();
        }
      );
    },
    async drawImageToCanvas() {
      // const ctx = uni.createCanvasContext("myCanvas", this);
      // 清空画布
      // ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      //  const img = new Image();
      //   img.crossOrigin = 'anonymous'; // 设置跨域属性
      //   img.src = 'https://example.com/your-image.jpg'; // 替换为实际的图片地址
      const _this = this;
      try {
        const resData = await uni.getImageInfo({
          src: decodeURIComponent(this.qrcode_src),
        });
        const res = resData[1] || {};
        // 居中绘制图片（带缩放）
        const imgWidth = res.width;
        const imgHeight = res.height;
        const scale = Math.min(
          this.canvasWidth / imgWidth,
          this.canvasHeight / imgHeight
        );
        const drawWidth = imgWidth * scale;
        const drawHeight = imgHeight * scale;
        const offsetX = (this.canvasWidth - drawWidth) / 2;
        const offsetY = (this.canvasHeight - drawHeight) / 2;
        console.log(res, "resData");
        uni.canvasToTempFilePath({
          x: offsetX,
          y: offsetY,
          width: imgWidth,
          height: imgHeight,
          destWidth: drawWidth,
          destHeight: drawHeight,
          canvasId: "container",
          success: function (res) {
            // 在H5平台下，tempFilePath 为 base64
            // const imageUrl = `data:image/png;base64,${res.tempFilePath}`;
            const imageUrl = `${res.tempFilePath}`;
            const contentPath = _this.$refs.imagRef.contentPath;
            _this.fileDwonload(imageUrl, contentPath);
          },
        });

        // ctx.drawImage(res.path, offsetX, offsetY, drawWidth, drawHeight);
        // ctx.draw();
      } catch (err) {
        console.error("图片加载失败:", err);
      }
    },

    // 绘制图片
    drawPoster() {
      //获取数据后，开始绘画
      const that = this;

      this.poster = {
        width: "750rpx",
        height: "1448rpx",
        background: "#1F7CFF", //画布背景色
        // radius: '20rpx',//画布的圆角

        views: [
          {
            //绘制图片，白色圆角背景
            type: "image", //绘画的类型，具体官网查看
            src: "https://cdn.bjtdba.com/vod/image/2022-08-23/20220823134038776.png", //图片路径
            mode: "scaleToFill",
            css: {
              //css需要使用驼峰命名
              marginLeft: "31rpx",
              marginTop: "154rpx",
              width: "688rpx",
              height: "1053rpx",
            },
            views: [
              {
                //绘制图片，logo
                type: "image", //绘画的类型，具体官网查看
                src: "https://cdn.bjtdba.com/vod/image/2022-08-23/20220823134835742.png", //图片路径
                css: {
                  //css需要使用驼峰命名
                  marginLeft: "271rpx",
                  marginTop: "-52rpx",
                  width: "144rpx",
                  height: "144rpx",
                },
              },
              {
                //绘制图片，二维码
                type: "image", //绘画的类型，具体官网查看
                src: this.qrcode_src, //图片路径
                css: {
                  //css需要使用驼峰命名
                  marginLeft: "164rpx",
                  marginTop: "52rpx",
                  width: "360rpx",
                  height: "360rpx",
                },
              },
              {
                //绘制图片，扫码即得养老金 提示背景
                type: "image", //绘画的类型，具体官网查看
                src: "https://cdn.bjtdba.com/vod/image/2022-08-23/20220823140132620.png", //图片路径
                css: {
                  //css需要使用驼峰命名
                  marginLeft: "71rpx",
                  marginTop: "111rpx",
                  width: "546rpx",
                  height: "94rpx",
                },
                views: [
                  {
                    //绘制图片，扫码即得养老金 提示
                    type: "text", //绘画的类型，具体官网查看
                    text: "扫码即得养老金",
                    css: {
                      //css需要使用驼峰命名
                      marginLeft: "10rpx",
                      marginTop: "18rpx",
                      width: "526rpx",
                      height: "50rpx",
                      fontSize: "36rpx",
                      color: "#ffffff",
                      textAlign: "center",
                    },
                  },
                ],
              },
              {
                //绘制图片，支付类型选择背景
                type: "view",
                css: {
                  marginLeft: "82rpx",
                  marginTop: "24rpx",
                  width: "526rpx",
                  height: "206rpx",
                  background: "#DFEAFD",
                  radius: "30rpx 30rpx 30rpx 30rpx",
                },
                views: [
                  {
                    //绘制图片，支持以下付款 提示
                    type: "text", //绘画的类型，具体官网查看
                    text: "支持以下付款", //图片路径
                    css: {
                      //css需要使用驼峰命名
                      marginLeft: "10rpx",
                      marginTop: "32rpx",
                      width: "506rpx",
                      height: "40rpx",
                      fontSize: "28rpx",
                      color: "#333333",
                      textAlign: "center",
                    },
                  },
                  {
                    //绘制图片，支付宝logo
                    type: "image", //绘画的类型，具体官网查看
                    src: "https://cdn.bjtdba.com/vod/image/2022-08-23/20220823141611538.png", //图片路径
                    css: {
                      //css需要使用驼峰命名
                      marginLeft: "176rpx",
                      marginTop: "32rpx",
                      width: "70rpx",
                      height: "70rpx",
                    },
                  },
                  {
                    //绘制图片，微信logo
                    type: "image", //绘画的类型，具体官网查看
                    src: "https://cdn.bjtdba.com/vod/image/2022-08-23/20220823141556288.png", //图片路径
                    css: {
                      //css需要使用驼峰命名
                      marginLeft: "32rpx",
                      marginTop: "32rpx",
                      width: "70rpx",
                      height: "70rpx",
                    },
                  },
                ],
              },
            ],
          },
        ],
      };
      // let base = this.poster;
      // const painter = that.$refs.posterRef || {};
      // painter.render(base);
    },

    topgi() {
      // 返回按钮事件
      uni.switchTab({
        url: "/pages/cashier/index",
      });
    },
    change(e) {
      console.log("e:", e);
    },

    // 海报  l-painter回调函数
    handleSuccess(path) {
      uni.hideLoading();
      console.log("完成图片绘制");
    },
    handleProgress(number) {
      this.progressNum = number;
    },
    handleError(error) {
      uni.hideLoading();
    },

    // 点击保存图片 - 1.base64字符串转成url地址
    clickGeneratePicture() {
      this.$refs.posterRef.canvasToTempFilePathSync({
        fileType: "jpg",
        quality: 1,
        pathType: "url",
        success: (res) => {
          console.log(res.tempFilePath);
          this.picture = res.tempFilePath;
          // 2.保存
          this.saveImage();
        },
        fail(e) {
          console.log("???????????", e);
        },
      });
    },
    clickGeneratePicture2() {
      //this.drawImageToCanvas();
      let fileName = "pension_分享海报.jpg";
      if (this.qrcode_src == "") {
        uni.showToast({
          title: "无生成二维码",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      let fileUrl = decodeURIComponent(this.qrcode_src);
      if (window.android) {
        window.android.downloadFile(fileName, fileUrl);
      } else {
        uni.showToast({
          title: "未检测到Android环境",
          icon: "none",
          duration: 2000,
        });
      }
    },
    // 保存图片
    saveImage() {
      let that = this;
      console.log("xxxxxxxxxxxx");
      console.log(that.picture);
      if (that.picture !== "") {
        uni.hideLoading();
        uni.getSetting({
          success(res) {
            if (res.authSetting["scope.writePhotosAlbum"]) {
              that.saveImageToAlbum();
            } else if (
              res.authSetting["scope.writePhotosAlbum"] === undefined
            ) {
              uni.authorize({
                scope: "scope.writePhotosAlbum",
                success() {
                  uni.showModal({
                    title: "保存成功",
                    content: "图片已成功保存到相册，快去分享到您的圈子吧",
                    showCancel: false,
                  });
                },
                fail() {
                  that.authConfirm();
                },
              });
            } else {
              that.authConfirm();
            }
          },
        });
      } else {
        uni.showModal({
          title: "提示",
          content: "生成海报失败,请重试",
          showCancel: false,
        });
      }
    },

    fileDwonload(base64Data, path) {
      uni.showLoading({ title: "保存中...", mask: true });
      const _this = this;
      // const blob = this.base64ToBlob(base64Data);
      // const blobUrl = URL.createObjectURL(blob);
      const finName = "海报.jpg";
      uni.downloadFile({
        url: path, //请求地址
        success: (res) => {
          //下载成功
          console.log(res, "下载成功");
          if (res.statusCode === 200) {
            //保存文件
            let filePath = res.tempFilePath;
            // #ifdef H5
            saveAs(filePath, finName);
            uni.showModal({
              title: "保存成功",
              content: "图片已成功保存到相册，快去分享到您的圈子吧",
              showCancel: false,
            });
            // #endif
            //  #ifdef MP-WEIXIN || APP-PLUS
            uni.saveFile({
              tempFilePath: filePath,
              success: function (filRes) {
                console.log(filRes, "=====>");
              },
              fail: function (err) {
                console.log("保存失败");
              },
            });
            // #endif
            uni.hideLoading();
          }
        },
        fail: (e) => {
          console.log(e, "文件下载失败downloadFile");
          uni.hideLoading();
          _this.loadFiles(path, finName);

          // uni.showToast({
          //   title: "文件下载保存失败",
          //   icon: "error",
          // });
        },
      });
    },
    loadFiles(url, fileName) {
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    // 未授权相册功能 重新弹窗
    authConfirm() {
      let that = this;
      wx.showModal({
        content: "检测到您没打开保存图片权限，是否去设置打开？",
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting["scope.writePhotosAlbum"]) {
                  that.saveImg();
                } else {
                  uni.showModal({
                    title: "保存失败",
                    content: "您没有授权，无法保存到相册",
                    showCancel: false,
                  });
                }
              },
            });
          } else {
            uni.showModal({
              title: "保存失败",
              content: "您没有授权，无法保存到相册",
              showCancel: false,
            });
          }
        },
      });
    },
    base64ToBlob(base64) {
      const parts = base64.split(";base64,");
      const mimeType = parts[0].split(":")[1];
      const base64Data = parts[1];
      var binaryData = atob(base64.split(";base64,")[1]);
      // const binaryData = atob(base64Data);
      const arrayBuffer = new ArrayBuffer(binaryData.length);
      const uint8Array = new Uint8Array(arrayBuffer);
      for (let i = 0; i < binaryData.length; i++) {
        uint8Array[i] = binaryData.charCodeAt(i);
      }

      return new Blob([uint8Array], { type: mimeType });
    },
    // 保存到相册
    saveImageToAlbum() {
      uni.saveImageToPhotosAlbum({
        filePath: this.picture,
        success: () => {
          uni.showModal({
            title: "保存成功",
            content: "图片已成功保存到相册，快去分享到您的圈子吧",
            showCancel: false,
          });
        },
      });
    },
  },
};
</script>

<style>
page {
  background-color: #f7f8fc;
}
</style>
<style lang="scss" scoped>
.process {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .activite-nav {
    width: 100%;
    height: 100%;
    // margin-top: 176rpx;
    background-color: red;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: url("https://cdn.bjtdba.com/vod/image/2022-08-23/20220823132549341.png")
      no-repeat;
    background-size: 100%;
    padding-bottom: 242rpx;

    .activite-card {
      width: 688rpx;
      margin-top: 154rpx;
      height: 1053rpx;
      background: url("https://cdn.bjtdba.com/vod/image/2022-08-23/20220823134038776.png")
        no-repeat;
      background-size: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;

      .activite-card-logo {
        width: 144rpx;
        height: 144rpx;
        position: absolute;
        top: -52rpx;
        left: 50%;
        transform: translate(-50%, 0);
      }

      .activite-cardImg {
        width: 360rpx;
        height: 360rpx;
        background: #d8d8d8;
        margin: 144rpx auto 52rpx auto;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .activite-cardText {
        line-height: 45rpx;
        font-size: 32rpx;
      }

      .activite-cardBtn {
        width: 546rpx;
        height: 94rpx;
        background: url("https://cdn.bjtdba.com/vod/image/2022-08-23/20220823140132620.png")
          no-repeat;
        background-size: 100%;
        color: #ffffff;
        font-size: 36rpx;
        text-align: center;
        padding: 20rpx 0 24rpx;
      }

      .activite-cardPrompt {
        width: 526rpx;
        // height: 206rpx;
        background: #dfeafd;
        border-radius: 30rpx;
        padding: 32rpx 0;

        .activite-prompt {
          display: flex;
          align-items: center;
          justify-content: center;

          .activite-prompt-left {
            width: 50rpx;
            height: 2rpx;
            background: linear-gradient(
              90deg,
              rgba(223, 234, 253, 0) 0%,
              #1f7cff 100%
            );
            border-radius: 1rpx;
          }

          .activite-prompt-title {
            font-size: 28rpx;
            margin: 0 16rpx;
          }

          .activite-prompt-right {
            width: 50rpx;
            height: 2rpx;
            background: linear-gradient(
              270deg,
              rgba(223, 234, 253, 0) 0%,
              #1f7cff 100%
            );
          }
        }

        .activite-prompt-img {
          margin-top: 32rpx;
          text-align: center;

          image {
            width: 70rpx;
            height: 70rpx;
          }

          :first-child {
            margin-right: 32rpx;
          }
        }
      }
    }

    .downLoadButton {
      width: 128rpx;
      height: 165rpx;
      margin-top: 9rpx;
      // background-color: red;
      display: flex;
      flex-direction: column;
      align-items: center;

      .downLoad-image {
        width: 128rpx;
        height: 128rpx;
        position: absolute;
      }

      .downLoad-text {
        margin-top: 128rpx;
        color: #ffffff;
        font-size: 26rpx;
        text-align: center;
      }
    }
  }
}
</style>