<template>
  <view class="container">
	  <!-- 禁用弹窗 -->
	  	 <restrictedTip ref="restrictedTip"/>
    <!-- 添加ref以便获取DOM -->
    <view class="imgBox" ref="captureElement" v-if="!generatedImage">
      <view class="imgContainer">
        <image
          style="display: block;"
          src="@/static/images/sharePoster.png"
          mode="widthFix"
          @load="handleBgImageLoad"
          @error="handleBgImageError"
        ></image>
        <!-- 二维码容器 -->
        <view class="qrcode-container">
          <canvas 
            canvas-id="qrcode" 
            class="qrcode-canvas"
            :style="{width: qrcodeSize + 'px', height: qrcodeSize + 'px'}"
          ></canvas>
        </view>
      </view>
    </view>
    <!-- 添加生成的图片预览 -->
	 <view class="preview-container" v-if="generatedImage">
		<image  :src="generatedImage" mode="widthFix" class="preview-image"></image>
	</view>
  </view>
</template>

<script>
import * as environment from "@/environments/environment";
import UQRCode from 'uqrcodejs';
import { elementToImage } from '@/util/htmlToImage';
import api from "@/api/api";
import { initJssdkShare, setWechatShare } from '@/util/fiveshare';
import restrictedTip from '@/components/commonPopup/restrictedTip.vue';
export default {
	components:{
				restrictedTip,
			},
  data() {
    return {
      companyInfo: environment.companyInfo,
      imgType: environment.companyInfo.imgType,
      baseURL: environment.baseURL,
      shareId: '',
      invitationCode: '',
      codeUrl: '',
      loginType: '',
      userInfo: {},
      qrcodeSize: 110, // 二维码大小（单位px）
      generatedImage: '', // 生成的图片
      isBgImageReady: false, // 背景图片是否准备就绪
      retryCount: 0, // 重试次数
      maxRetryCount: 3 // 最大重试次数
    }
  },
  onShow() {
	  if(uni.getStorageSync('loginType')=='codelogin'){
	  				this.queryInfo()
	  			}
    this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
    this.loginType = uni.getStorageSync('loginType')
    if(!this.loginType || this.loginType == 'visitor'){
      this.codeUrl = `${this.baseURL}/pages/index/index`
    } else {
      this.codeUrl = `${this.baseURL}/pages/index/index?invitationCode=${this.userInfo.invitationCode}&inviteUserId=${this.userInfo.userId}&sharePoster=1`
    }
     // 1. 首先检查是否有缓存的图片
      const cachedImage = uni.getStorageSync('savedShareImage');
      if (cachedImage) {
        this.generatedImage = cachedImage;
        return; // 如果有缓存，直接使用，不再执行后续生成逻辑
      }
    // 重置状态
    this.isBgImageReady = false;
    this.retryCount = 0;
    
    // 开始加载背景图片（由@load事件触发后续流程）
    console.log('开始加载背景图片...');
	// #ifdef H5
	initJssdkShare(() => {
	  setWechatShare();
	}, window.location.href);
	// #endif
  },
  methods: {
	  queryInfo() {
	  				api.queryInfo({userId:uni.getStorageSync('cffp_userId')}).then(res=>{
	  					// 保存用户得个人信息
	  					if (res['success']) {
	  						delete res.data.commonResult
	  						
	  						const cffp_userInfo = {
	  							...res.data
	  						}
	  						// 账号禁用用户
	  						if(res.data.userIsActive&&res.data.userIsActive==2){
	  							this.$refs.restrictedTip.open()
	  							uni.setStorageSync('userIsActive',String(res.data.userIsActive))
	  							return
	  						}
	  						if(res.data.userIsActive&&res.data.userIsActive!=2){
	  							this.$refs.restrictedTip.close()
	  							uni.removeStorageSync('userIsActive')
	  						}
	  						
	  						uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo));
	  						uni.setStorageSync('user_mobile', res.data.mobile)
	  						
	  					}
	  					
	  				})
	  			},
    // 背景图片加载成功
    handleBgImageLoad() {
      console.log('背景图片加载完成');
      this.isBgImageReady = true;
      this.generateQrcodeAndCapture();
    },
    
    // 背景图片加载失败
    handleBgImageError() {
      console.error('背景图片加载失败');
      // 即使失败也继续流程，可能会有默认背景
      this.isBgImageReady = true;
      this.generateQrcodeAndCapture();
    },
    
    // 顺序执行：生成二维码 -> 截图
    async generateQrcodeAndCapture() {
		// 再次检查缓存（防止并发情况）
		    if (uni.getStorageSync('savedShareImage')) {
		      return;
		    }
      try {
        uni.showLoading({
          title: '准备生成分享图...'
        });
        
        // 1. 先生成二维码
        console.log('开始生成二维码...');
        await this.makeQrcode();
        console.log('二维码生成完成');
        
        // 2. 等待500ms确保渲染完成
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 3. 执行截图
        console.log('开始截图...');
        await this.captureImage();
        console.log('截图完成');
        
        uni.hideLoading();
      } catch (error) {
        console.error('生成分享图失败:', error);
        uni.hideLoading();
        this.retryGenerate();
      }
    },
    
    // 重试机制
    retryGenerate() {
      if (this.retryCount < this.maxRetryCount) {
        this.retryCount++;
        const delay = 1000 * this.retryCount;
        console.log(`第${this.retryCount}次重试，${delay}ms后重试...`);
        
        
        
        setTimeout(() => {
          this.generateQrcodeAndCapture();
        }, delay);
      } else {
        // uni.showToast({
        //   title: '生成分享图失败，请稍后再试',
        //   icon: 'none'
        // });
      }
    },
    
    // 生成二维码
    makeQrcode() {
      return new Promise((resolve, reject) => {
        // 创建实例
        const qr = new UQRCode();
        
        // 设置二维码内容
        qr.data = this.codeUrl;
        
        // 设置二维码大小
        qr.size = this.qrcodeSize;
        
        // 设置前景色（二维码颜色）
        qr.foregroundColor = '#000000';
        
        // 设置背景色
        qr.backgroundColor = '#FFFFFF';
        
        // 设置边距
        qr.margin = 10;
        
        // 设置纠错等级
        qr.errorCorrectLevel = UQRCode.errorCorrectLevel.H;
        
        try {
          // 调用制作二维码方法
          qr.make();
          
          // 获取canvas上下文
          const ctx = uni.createCanvasContext('qrcode', this);
          
          // 清空画布
          ctx.clearRect(0, 0, this.qrcodeSize, this.qrcodeSize);
          
          // 将二维码绘制到canvas上
          qr.canvasContext = ctx;
          qr.drawCanvas();
          
          // 绘制完成
          ctx.draw(true, () => {
            console.log('二维码绘制完成');
            resolve();
          });
        } catch (err) {
          reject(err);
        }
      });
    },
    
    // 截图方法
    async captureImage() {
      try {
        uni.showLoading({
          title: '正在生成图片...'
        });
        
        // 获取DOM元素（在H5环境下）
        const element = this.$refs.captureElement.$el;
        
        // 调用工具函数生成图片
        const imageData = await elementToImage(element);
        // 压缩图片
		const compressedImage = await this.compressImage(imageData);
		
		this.generatedImage = compressedImage;
		
		uni.setStorageSync('savedShareImage', compressedImage);
        // this.generatedImage = imageData;
        // // 将生成的图片保存到本地存储
        // uni.setStorageSync('savedShareImage', imageData);
      } catch (error) {
        console.error('截图失败:', error);
        throw error; // 抛出错误以便外部捕获
      } finally {
        uni.hideLoading();
      }
    },
     compressImage(base64) {
            return new Promise((resolve) => {
              const img = new Image();
              img.src = base64;
              img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                // 设置压缩后的宽高
                const maxWidth = 800;
                const maxHeight = 1200;
                let width = img.width;
                let height = img.height;
                
                if (width > maxWidth) {
                  height *= maxWidth / width;
                  width = maxWidth;
                }
                
                if (height > maxHeight) {
                  width *= maxHeight / height;
                  height = maxHeight;
                }
                
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                
                // 降低质量
                resolve(canvas.toDataURL('image/jpeg', 0.7));
              };
            });
          },
    saveImage(base64Data) {
      // 实现保存图片到相册的逻辑
      // 注意：在H5中可能需要不同的处理方式
      if (uni.downloadFile) {
        uni.downloadFile({
          url: base64Data,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                  uni.showToast({
                    title: '保存成功',
                    icon: 'success'
                  });
                },
                fail: (err) => {
                  console.error('保存失败:', err);
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  });
                }
              });
            }
          },
          fail: (err) => {
            console.error('下载图片失败:', err);
          }
        });
      } else {
        // H5环境下的处理方式
        const link = document.createElement('a');
        link.href = base64Data;
        link.download = 'share-image.png';
        link.click();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  
  
  .imgBox {
    width: 100%;
    height: auto;
    
    .imgContainer {
      width: 100%;
      position: relative;
      
      image {
        width: 100%;
        height: auto;
        display: block;
      }
      
      .qrcode-container {
        position: absolute;
        bottom: 10rpx;
        right: 10rpx;
        background: #fff;
        padding: 10rpx;
        border-radius: 10rpx;
        box-shadow: 0 0 10rpx rgba(0,0,0,0.1);
        
        .qrcode-canvas {
          display: block;
        }
      }
    }
  }
  
  .preview-container {
    flex: 1;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      overflow: hidden;
    
    .preview-image {
     height: 100%;  /* 让高度占满屏幕 */
       width: auto;   /* 宽度自动调整 */
       object-fit: fill;
    }
  }
}
.container {
  display: flex;
  flex-direction: column;
  width: 100vw;
  overflow: hidden;
  
  /* 默认手机端样式 */
  height: 100vh;
  
  /* iPad竖屏 (768px-1024px) */
  @media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) {
    height: 100vh;
    .imgBox {
      height: 100vh;
      overflow: hidden;
      .imgContainer {
        height: 100%;
        image {
          height: 100%;
          width: auto;
          max-width: 100%;
          object-fit: contain;
        }
      }
    }
  }
  
  /* iPad横屏 (1024px-1366px) */
  @media only screen and (min-width: 1024px) and (max-width: 1366px) and (orientation: landscape) {
    height: 100vh;
	width: 35vw;
    .imgBox {
      height: 100vh;
      overflow: hidden;
      .imgContainer {
        height: 100%;
        image {
          height: 100%;
          width: auto;
          max-width: 100%;
          object-fit: contain;
        }
      }
    }
  }
  
  /* PC端 (大于1366px) */
  @media only screen and (min-width: 1366px) {
    height: 100vh;
	width: 35vw;
    .imgBox {
      height: 100vh;
      overflow: hidden;
      .imgContainer {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        image {
          height: auto;
          max-height: 100%;
          width: 500px;
          max-width: 100%;
          object-fit: contain;
        }
      }
    }
  }

  .imgBox {
    width: 100%;
    height: auto;
    
    .imgContainer {
      width: 100%;
      position: relative;
      
      image {
        width: 100%;
        height: auto;
        display: block;
      }
      
      .qrcode-container {
        position: absolute;
        bottom: 10rpx;
        right: 10rpx;
        background: #fff;
        padding: 10rpx;
        border-radius: 10rpx;
        box-shadow: 0 0 10rpx rgba(0,0,0,0.1);
        
        .qrcode-canvas {
          display: block;
        }
      }
    }
  }
  
  .preview-container {
    flex: 1;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    overflow: hidden;
    
    .preview-image {
      height: 100%;
      width: auto;
      object-fit: contain;
      
      /* 大屏幕设备调整 */
      @media only screen and (min-width: 768px) {
        max-height: 100vh;
        width: auto;
      }
    }
  }
}

</style>