<template>
  <view class="py-base">
    <loading-view v-if="isFirstLoading"></loading-view>
    <view class="w-710rpx mx-auto flex flex-col">
      <swiper @change="swiperChange" class="h-1160rpx" :indicator-dots="false" :autoplay="false" :interval="interval"
        :duration="duration">
        <swiper-item class="h-full" v-for="(item,index) in bgImage" :key="index">
          <view class="h-full invite-bg relative">
            <image :src="item.image" class="w-full h-full"></image>
            <view
              class="flex-1 flex items-center justify-between px-30rpx absolute bottom-0rpx bg-white w-full rounded-t-20rpx py-base">
              <view class="flex items-start flex-col">
                <view class="-mt-60rpx">
                  <cu-avatar size="100" :src="user.avatar?user.avatar:''"></cu-avatar>
                </view>
                <view class="mt-10rpx text-txGray">{{showPhone}}</view>
                <view class="font-extrabold text-xl">积趣自然图书馆</view>
                <view>{{item.remark?item.remark:''}}</view>
              </view>
              <view>
                <image class="w-168rpx h-168rpx" :src="code" mode="scaleToFill" />
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>
    <!-- 指示点 -->
    <view v-if="bgImage.length>1" class="flex items-center justify-center mt-30rpx">
      <view :class="dotIndex==index?'dotBg':''" v-for="(item,index) in bgImage.length" :key="index"
        class="rounded-full mx-10rpx w-20rpx h-20rpx bg-hex-a9a9a9"></view>
    </view>
    <view class="mt-43rpx px-80rpx">
      <!-- #ifdef APP-PLUS -->
      <!-- <view class="login-btn" @tap="saveImgToLocal">保存到相册</view> -->
      <view class=" grid grid-cols-3 text-txGray text-26rpx">
        <view @tap="sharingFriend(0)" class="flex items-center justify-center flex-col">
          <view class="w-110rpx h-110rpx flex items-center justify-center flex-col rounded-15rpx bg-hex-00dd00 ">
            <image class="w-66rpx h-66rpx" src="/static/images/share/wechat-friends.png" mode=""></image>
          </view>
          <view class="mt-10rpx">微信好友</view>
        </view>
        <view @tap="sharingFriend(1)" class="flex items-center justify-center flex-col">
          <view class="w-110rpx h-110rpx flex items-center justify-center flex-col rounded-15rpx bg-hex-ffffff">
            <image class="w-66rpx h-66rpx" src="/static/images/share/wechat-moments.png" mode=""></image>
          </view>
          <view class="mt-10rpx">朋友圈</view>
        </view>
        <view @tap="saveImgToLocal" class="flex items-center justify-center flex-col">
          <view class="w-110rpx h-110rpx flex items-center justify-center flex-col rounded-15rpx bg-hex-fcbd71">
            <image class="w-66rpx h-66rpx" src="/static/images/share/album.png" mode=""></image>
          </view>

          <view class="mt-10rpx">相册</view>
        </view>
      </view>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view class="login-btn" @tap="saveImgToLocal">点击下载长按保存到相册</view>
      <!-- #endif -->
      <!-- #ifdef  MP-WEIXIN -->
      <!-- <view class="login-btn" @tap="saveImgToLocal">保存图片</view> -->
      <view class=" grid grid-cols-2 text-txGray text-26rpx">
        <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-15rpx bg-hex-00dd00 ">
            <image class="w-66rpx h-66rpx" src="/static/images/share/wechat-friends.png" mode=""></image>
          </view>
          <view class="mt-10rpx">微信好友</view>
        </button>
        <view @tap="saveImgToLocal" class="flex items-center justify-center flex-col">
          <view class="w-110rpx h-110rpx flex items-center justify-center flex-col rounded-15rpx bg-hex-fcbd71">
            <image class="w-66rpx h-66rpx" src="/static/images/share/album.png" mode=""></image>
          </view>
          <view class="mt-10rpx">保存到相册</view>
        </view>
      </view>
      <!-- #endif -->
    </view>
    <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';
  import permision from "@/utils/permission.js"

  export default {
    data() {
      return {
        showModel: false,
        isFirstLoading: true,
        bgImage: [],
        qr_code: '',
        interval: 2000,
        duration: 500,
        dotIndex: 0,
        poster: {},
        url: '', //合成的海报
      };
    },
    computed: {
      user() {
        return this.$store.getters.user ?? {}
      },
      showPhone() {
        return this.user.phone?.replace(/^(\d{3})\d+(\d{4})$/, '$1****$2')
      },
      posterbg() {
        return this.bgImage[this.dotIndex]?.image ?? ''
      },
      code() {
        // return 'data:image/png;base64,' + this.qr_code
       return this.qr_code
      },
      remark() {
        return this.bgImage[this.dotIndex]?.remark ?? ''
      },
    },
    onLoad() {
      this.getImage()
      this.getCode()
    },
    //微信分享
    onShareAppMessage(){
      let code = this.user.code ? this.user.code : '';
      let shareObj={
        title:'我正在使用积趣自然图书馆，赶紧跟我一起来体验吧！',
        path:`/pages/index/index?invite_code=${code}`,
        imageUrl:''
      }
      return shareObj
    },
    methods: {
      ///分享到微信
      sharingFriend(val) {
        let scene = val == 0 ? 'WXSceneSession' : 'WXSceneTimeline'
        uni.share({
          provider: "weixin",
          scene: scene,
          type: 0,
          href: `https://wap.zichunsheng.cn/register?code=${this.user.code}`,
          title: '我正在使用积趣自然图书馆，赶紧跟我一起来体验吧！',
          // summary: "我正在使用子春生APP，赶紧跟我一起来体验吧！",
          imageUrl: '/static/images/share/logs.png',
          success: res => {}
        })
      },
      //获取背景图
      async getImage() {
        try {
          let resDate = await this.$api.get('/v1/share-bgs', {})
          this.bgImage = resDate
        } catch (err) {} finally {
          this.isFirstLoading = false
        }
      },
      async getCode() {
        let {
          qr_code
        } = await this.$api.post('/v1/user-qr-code', {})
        this.qr_code = qr_code
      },
      swiperChange(e) {
        this.dotIndex = e.detail.current
      },
      async shareFc() {
        uni.showLoading({
          title: '图片合成中...'
        });
        let t = this;
        try {
          const d = await getSharePoster({
            _this: this, //若在组件中使用 必传
            type: 'testShareType',
            background: {
              height: 670, //画布高度
              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.posterbg,
                    infoCallBack(imageInfo) {
                      return {
                        dx: 0,
                        dy: 0,
                        dWidth: 385,
                        dHeight: 550,
                      }
                    }
                  }, //顶部图片
                  {
                    type: 'image',
                    url: t.user.avatar ? t.user.avatar : '/static/images/user/avatar.png',
                    roundRectSet: {
                      r: 54
                    },
                    infoCallBack(imageInfo) {
                      return {
                        dx: 15,
                        dy: 530,
                        dWidth: 54,
                        dHeight: 54,
                      }
                    }
                  }, //头像
                  {
                    type: 'text',
                    text: t.showPhone,
                    size: '14',
                    color: '#808080',
                    infoCallBack(imageInfo) {
                      return {
                        dx: 15,
                        dy: 600,
                      }
                    }
                  }, //电话
                  {
                    type: 'text',
                    text: '积趣自然图书馆',
                    size: '16',
                    color: '#383838',
                    fontWeight: 'bold',
                    infoCallBack(imageInfo) {
                      return {
                        dx: 15,
                        dy: 620,
                      }
                    }
                  }, //公司名称
                  {
                    type: 'text',
                    text: t.remark,
                    size: '14',
                    color: '#383838',
                    infoCallBack(imageInfo) {
                      return {
                        dx: 15,
                        dy: 645,
                      }
                    }
                  }, //简介
                  {
                    type: 'image',
                    // url: t.code,
                    url: t.code,
                    infoCallBack(imageInfo) {
                      return {
                        dx: 275,
                        dy: 570,
                        dWidth: 84,
                        dHeight: 84,
                      }
                    }
                  }, //二维码
                ]);
              })
            },
            setCanvasWH: ({
              bgObj,
              type,
              bgScale
            }) => { // 为动态设置画布宽高的方法，
              t.poster = bgObj;
            }
          });
          t.url = d.poster.tempFilePath;
          uni.hideLoading()
        } catch (e) {
          uni.hideLoading()
        }
      },
      //保存图片（小程序，app）
      saveImage() {
        uni.saveImageToPhotosAlbum({
          filePath: this.url,
          success: res => {
            this.$u.toast("保存图片成功")
          },
        })
      },
      //h5--保存
      pressSave() {
        let arr = []
        arr.push(this.url)
        uni.previewImage({
          urls: arr
        })
      },
      async saveImgToLocal() {
        this.$u.throttle(async () => {
          // #ifdef MP-WEIXIN
          await this.getWinxinAlbum()
          // #endif
          //#ifdef APP-PLUS
          await this.shareFc()
          await this.saveImage()
          //#endif
          //#ifdef H5
          await this.shareFc()
          await this.pressSave()
          //#endif
        }, 1000)
      },
      //判断小程序相册功能是否打开
      getWinxinAlbum() {
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success: async res => {
            await this.shareFc()
            await this.saveImage()
          },
          fail: (comp) => {
            uni.getSetting({
              success: Setting => {
                if (!Setting.authSetting['scope.writePhotosAlbum']) {
                  this.showModel = true
                }
              }
            });
          }
        })
      },
      onConfirm() {
        this.showModel = false
        uni.openSetting({
          success: res => {
          },
        });
      },
    }
  };
</script>
<style lang="scss" scoped>
  .share-btn::after{ border: none; }
  .dotBg {
    background: #000000 !important;
  }

  .box-card {
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.39);
  }

  .invite-bg {
    background-repeat: no-repeat;
    background-size: contain;
  }

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