<template>
  <view class="share-page">
    <!-- <uv-status-bar></uv-status-bar> -->
    
    <!-- 主要内容区域 -->
    <view class="content">
      <uv-loading-icon text="生成中，请耐心等待" textSize="40rpx" size="60rpx" v-if="isLoading"></uv-loading-icon>
      <!-- 中间图片 -->
      <view class="image-container" v-else>
        <image 
          class="share-image" 
          :src="Qrcode" 
          mode="aspectFit"
        ></image>
      </view>
    </view>
    
    <!-- 底部固定按钮 -->
    <view class="bottom-button-container">
      <uv-button :custom-style="{
        height: '82rpx',
        borderRadius: '198rpx',
        background: '#06DADC',
        border: '2rpx solid #06DADC',
        lineHeight: '82rpx',
        fontSize: '36rpx'
        }" type="primary" @click="save">保存到相册</uv-button>
      <uv-safe-bottom></uv-safe-bottom>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      Qrcode: '',
      isLoading: false,
    }
  },
  methods: {
    handleShare() {
      // 分享逻辑
      uni.showToast({
        title: '分享功能',
        icon: 'none'
      })
    },
    async save() {
      try {
        // 检查相册权限
        const authResult = await this.checkPhotoAlbumAuth();
        
        if (authResult.authSetting['scope.writePhotosAlbum'] === true) {
          // 已有权限，直接保存
          this.saveToAlbum();
        } else if (authResult.authSetting['scope.writePhotosAlbum'] === false) {
          // 权限被拒绝，引导用户到设置页面
          this.showAuthGuide();
        } else {
          // 未授权，请求权限
          this.requestPhotoAlbumAuth();
        }
      } catch (error) {
        console.error('权限检查失败:', error);
        // 如果权限检查失败，直接尝试保存（兼容处理）
        this.saveToAlbum();
      }
    },
    
    // 检查相册权限
    checkPhotoAlbumAuth() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    
    // 请求相册权限
    requestPhotoAlbumAuth() {
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success: () => {
          // 权限请求成功，保存图片
          this.saveToAlbum();
        },
        fail: () => {
          // 权限请求被拒绝，引导用户到设置页面
          this.showAuthGuide();
        }
      });
    },
    
    // 显示权限引导
    showAuthGuide() {
      uni.showModal({
        title: '需要相册权限',
        content: '保存图片需要访问您的相册权限，请在设置中开启相册权限后重试',
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 打开设置页面
            uni.openSetting({
              success: (settingRes) => {
                if (settingRes.authSetting['scope.writePhotosAlbum']) {
                  // 用户在设置页面开启了权限，再次调用保存
                  this.saveToAlbum();
                } else {
                  uni.showToast({
                    title: '未开启相册权限',
                    icon: 'none'
                  });
                }
              }
            });
          }
        }
      });
    },
    
    // 保存图片到相册
    saveToAlbum() {
      if (!this.Qrcode) {
        uni.showToast({
          title: '图片还未加载完成',
          icon: 'none'
        });
        return;
      }
      
      uni.saveImageToPhotosAlbum({
        filePath: this.Qrcode,
        success: (res) => {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('保存失败:', err);
          if (err.errMsg.includes('auth')) {
            // 如果是权限问题，再次引导用户
            this.showAuthGuide();
          } else {
            uni.showToast({
              title: '保存失败，请重试',
              icon: 'none'
            });
          }
        }
      });
    },

    // 获取二维码
    async getQrcode() {
      this.isLoading = true
      uni.getImageInfo({
        src: `${this.$config.baseURL}/promotion/qrCode?token=${uni.getStorageSync('token')}`
		// #ifdef H5
		+ '&type=official'
		// #endif
        ,
        success: (image) => {
          
          this.Qrcode = image.path;
          this.$store.commit('setQrcode', this.Qrcode)
          this.isLoading = false
        },
        fail: (err) => {
          console.error('获取二维码失败:', err);
          this.isLoading = false
        }
      });
    }
  },
  onLoad() {
    if (this.$store.state.Qrcode){
      this.Qrcode = this.$store.state.Qrcode
    }else {
      this.getQrcode()

    }
  }
  
}
</script>

<style lang="scss" scoped>
.share-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content {
  height: 100vh;
  flex: 1;
  padding-bottom: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .image-container {
    // background: red;
    display: flex;
    // height: 100%;
    justify-content: center;
    align-items: center;
    
    .share-image {
      height: 90vh;
      width: 670rpx;
      border-radius: 16rpx;
    }
  }
}

// 底部固定按钮
.bottom-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx 40rpx;
  background: rgba(255, 255, 255, 0.95);
  border-top: 1px solid #F1F1F1;
}
</style>