<template>
  <view id="snapshot-content">
    <page-head title="对本页面根view截图"></page-head>
    <view class="uni-padding-wrap">
      <text>this is text</text>
    </view>
    <button class="uni-btn btn-TakeSnapshot" type="primary" @tap="takeSnapshotClick">
      点击截图并替换显示下方图片
    </button>
    <image style="margin-left:auto;margin-right:auto;margin-top:20px;width:90%;" :src="snapImage" :mode="mode"
      @longpress="saveToAlbum"></image>
  </view>
</template>

<script lang="uts">
  export default {
    data() {
      return {
        mode: "center",//aspectFit
        snapImage: "/static/uni.png"
      }
    },
    methods: {
      takeSnapshotClick() {
        const view = uni.getElementById('snapshot-content')!
        view.takeSnapshot({
          success: (res) => {
            console.log(res.tempFilePath)
            this.snapImage = res.tempFilePath
            this.mode = 'widthFix'
            uni.showToast({
              title: '截图成功，路径：' + res.tempFilePath,
              icon: "none"
            })
          },
          fail: (res) => {
            console.log(res)
            uni.showToast({
              icon: 'error',
              title: '截图失败'
            })
          }
        })
      },
      saveToAlbum(e : TouchEvent) {
        // console.log(e.currentTarget!.getAttribute("src"));
        let filePath : string = e.currentTarget!.getAttribute("src") as string
        uni.showActionSheet({
          itemList: ["保存"],
          success: res => {
            // console.log(res.tapIndex);
            if (res.tapIndex == 0) {
              uni.saveImageToPhotosAlbum({
                filePath: filePath,
                success() {
                  uni.showToast({
                    position: "center",
                    icon: "none",
                    title: "图片保存成功，请到手机相册查看"
                  })
                },
                fail(e) {
                  uni.showModal({
                    content: "保存相册失败，errCode：" + e.errCode + "，errMsg：" + e.errMsg + "，errSubject：" + e.errSubject,
                    showCancel: false
                  });
                }
              })
            }
          },
          fail: () => { },
          complete: () => { }
        });
      }
    }
  }
</script>
