<template>
  <view class="w-full">
    <cu-popup v-model="show" mode="bottom" border-radius="24">
      <view class="max-h-500rpx bg-txBorder">
        <view class="pt-20rpx text-26rpx text-center">分享</view>
        <view class="grid grid-cols-2 text-txGray text-26rpx mt-40rpx px-30rpx">
          <button hover-class="none" open-type="share" class="share-btn cu-btn flex items-center justify-center flex-col">
            <view class="w-110rpx h-110rpx flex items-center justify-center flex-col rounded-full bg-hex-00dd00">
              <image class="w-66rpx h-66rpx" src="/static/images/share/wechat-friends.png" mode=""></image>
            </view>
            <view class="mt-15rpx">小程序</view>
          </button>
          <view @tap="onShowImg" class="flex items-center justify-center flex-col">
            <view class="w-110rpx h-110rpx rounded-full flex items-center justify-center flex-col bg-hex-fa3534">
              <image class="w-66rpx h-66rpx" src="/static/images/share/code.png" mode=""></image>
            </view>
            <view class="mt-15rpx">二维码海报</view>
          </view>
        </view>
        <view class="px-50rpx py-60rpx">
          <view @tap="show = false" class="rounded-full bg-white text-center h-66rpx leading-66rpx text-txBase text-32rpx">取消</view>
        </view>
      </view>
    </cu-popup>
    <!-- 合成的图片显示-->
    <u-mask :show="imgShow" @tap="imgShow = false">
      <view class="warp" @tap="imgShow = false">
        <view class="w-full" @tap.stop="">
          <image class="w-full" :src="url" mode="widthFix"></image>
        </view>
        <view @tap.stop="getWinxinAlbum" class="rounded-15rpx mt-20rpx w-full bg-primary text-center h-66rpx leading-66rpx text-white text-32rpx">
          保存图片到相册</view
        >
      </view>
    </u-mask>
    <canvas
      class="hideCanvas"
      canvas-id="default_PosterCanvasId"
      :style="{ width: (poster.width || 0) + 'px', height: (poster.height || 0) + 'px' }"
    ></canvas>
    <cu-modal
      title="提示"
      v-model="showModel"
      content="没有授权保存图片到相册,点击确定授权"
      show-cancel-button
      async-close
      @confirm="onConfirm"
    ></cu-modal>
  </view>
</template>

<script>
import { getSharePoster } from '@/components/QS-SharePoster/QS-SharePoster.js';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    goods: {
      type: Object,
      default: () => {},
    },
    goodsImage: {
      type: String,
      default: '',
    },
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    user() {
      return this.$store.getters.user ?? {};
    },
  },
  data() {
    return {
      showModel: false,
      imgShow: false,
      canvasId: 'default_PosterCanvasId',
      code: '',
      poster: {},
      url: '',
    };
  },
  mounted() {},
  methods: {
    //获取二维码
    async getCode() {
      let res = await this.$api.get(`/v1/product/products/${this.goods.id}/share`);
      this.code = res.image;
    },
    //保存图片
    saveImage() {
      uni.saveImageToPhotosAlbum({
        filePath: this.url,
        success: (res) => {
          this.$u.toast('保存图片成功');
        },
        complete: (cop) => {
          this.imgShow = false;
        },
      });
    },
    //判断小程序相册功能是否打开
    getWinxinAlbum() {
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success: async (res) => {
          this.saveImage();
        },
        fail: (comp) => {
          uni.getSetting({
            success: (Setting) => {
              if (!Setting.authSetting['scope.writePhotosAlbum']) {
                this.showModel = true;
              }
            },
          });
        },
      });
    },
    onConfirm() {
      this.showModel = false;
      uni.openSetting({
        success: (res) => {},
      });
    },
    //
    async onShowImg() {
      this.show = false;
      this.$u.throttle(async () => {
        await this.getCode();
        await this.shareFc();
      }, 1000);
    },
    //合成图片
    async shareFc() {
      uni.showLoading({
        title: '图片合成中...',
      });
      let t = this;
      try {
        // await t.getLocal()
        const d = await getSharePoster({
          _this: t, //若在组件中使用 必传
          type: 'testShareType',
          background: {
            height: 600, //画布高度
            width: 385, //画布宽度
            backgroundColor: '#ffffff', //画布背景颜色
          },
          setCanvasWH({ bgObj }) {
            //一般必传， 动态设置canvas宽高
            _this.poster = bgObj;
          },
          posterCanvasId: 'default_PosterCanvasId', //canvasId
          delayTimeScale: 2, //延时系数
          drawArray: ({ setBgObj, getBgObj, type, bgScale }) => {
            return new Promise((rs, rj) => {
              rs([
                {
                  type: 'image',
                  url: t.goodsImage,
                  mode: 'aspectFill',
                  infoCallBack(imageInfo) {
                    return {
                      dx: 0,
                      dy: 0,
                      dWidth: 385,
                      dHeight: 385,
                    };
                  },
                }, //顶部图片
                {
                  type: 'text',
                  text: t.goods.name,
                  size: '20',
                  color: '#000000',
                  fontWeight: 'bold',
                  lineFeed: {
                    maxWidth: 220,
                    lineHeight: 30,
                  },
                  infoCallBack(imageInfo) {
                    return {
                      dx: 15,
                      dy: 440,
                    };
                  },
                }, //商品名称
                {
                  type: 'text',
                  text: `￥${t.goods.sell_price}`,
                  size: '20',
                  color: '#fa3534',
                  fontWeight: 'bold',
                  infoCallBack(imageInfo) {
                    return {
                      dx: 15,
                      dy: 520,
                    };
                  },
                }, //价格
                {
                  type: 'text',
                  text: '扫描或长按识别二维码',
                  size: '12',
                  color: '#383838',
                  infoCallBack(imageInfo) {
                    return {
                      dx: 260,
                      dy: 540,
                    };
                  },
                }, //简介
                {
                  type: 'image',
                  url: t.code,
                  //url: 'https://img0.baidu.com/it/u=2711835743,3110561022&fm=253&fmt=auto&app=138&f=JPEG?w=344&h=344',
                  infoCallBack(imageInfo) {
                    return {
                      dx: 265,
                      dy: 400,
                      dWidth: 110,
                      dHeight: 110,
                    };
                  },
                }, //二维码
              ]);
            });
          },
          setCanvasWH: ({ bgObj, type, bgScale }) => {
            // 为动态设置画布宽高的方法，
            t.poster = bgObj;
          },
        });
        t.url = d.poster.tempFilePath;
        this.imgShow = true;
        uni.hideLoading();
      } catch (e) {
        uni.hideLoading();
        this.$u.toast('网络繁忙，请稍后重试');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 70%;
  flex-direction: column;
  margin: 0 auto;
}

.hideCanvas {
  position: fixed;
  top: -9999999px;
  left: -9999999px;
  opacity: 0;
  z-index: -1;
}

.share-btn::after {
  border: none;
}
</style>
