<template>
  <view class="default-share-page">
    <!-- 背景图片，替代CSS background -->
    <img
      class="share-bg-image"
      src="/static/images/share-bg.jpg"
      crossorigin="anonymous"
      @load="onBackgroundImageLoad"
      @error="onBackgroundImageError"
    />

    <view class="share-wrapper">
      <view class="portal-frame" :class="{ 'is-loaded': isLoaded }">
        <!-- 二维码样式区域 - 用户自定义样式位置 -->
        <view class="qr-code-outer">
          <image
            class="qr-code"
            :src="qrCodeImage"
            mode="aspectFit"
            v-if="qrCodeImage"
          ></image>
          <view v-else class="qr-code-placeholder">
            <view class="loader"></view>
          </view>
        </view>

        <!-- 会员编号样式区域 - 用户自定义样式位置 -->
        <text class="member-code-text">{{
          desensitization(userInfo.memberCode)
        }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import html2canvas from 'html2canvas'

export default {
  name: 'DefaultSharePage',
  props: {
    qrCodeImage: {
      type: String,
      default: '',
    },
    userInfo: {
      type: Object,
      default: () => ({}),
    },
    isWechat: {
      type: Boolean,
      default: false,
    },
    isLoaded: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      backgroundImageLoaded: false,
      shareButtonShow: true,
    }
  },
  methods: {
    desensitization(str) {
      if (!str) return ''
      if (str.length <= 8) return str.slice(0, 4) + '****'
      const len = str.length - 6
      const placeholder = '*'.repeat(len)
      return str.slice(0, 4) + placeholder + str.slice(-2)
    },

    // 背景图片加载成功
    onBackgroundImageLoad() {
      this.backgroundImageLoaded = true
      console.log('默认场景背景图片加载成功')
    },

    // 背景图片加载失败
    onBackgroundImageError(e) {
      console.error('默认场景背景图片加载失败:', e)
    },

    async sharePage() {
      if (!this.qrCodeImage) {
        uni.showToast({
          title: '二维码尚未生成',
          icon: 'none',
        })
        return
      }

      uni.showLoading({ title: '加载中...', mask: true })

      try {
        this.shareButtonShow = false
        await this.$nextTick()

        await this.capturePageWithHtml2Canvas()
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: '图片生成失败，请稍后重试', icon: 'none' })
        console.error('sharePage error:', error)
      } finally {
        // 恢复按钮显示
        this.shareButtonShow = true
      }
    },

    // 使用html2canvas截取整个页面
    async capturePageWithHtml2Canvas() {
      console.log('开始使用html2canvas截取页面')

      return new Promise((resolve, reject) => {
        // 确保所有图片都已加载完成
        const waitForImages = () => {
          if (!this.backgroundImageLoaded || !this.qrCodeImage) {
            setTimeout(waitForImages, 100)
            return
          }

          // 额外等待确保渲染完成
          setTimeout(() => {
            const element = this.$el
            if (!element) {
              reject(new Error('找不到组件容器'))
              return
            }

            console.log(
              '开始html2canvas截取，容器尺寸:',
              element.offsetWidth,
              'x',
              element.offsetHeight
            )

            html2canvas(element, {
              useCORS: true,
              allowTaint: true,
              backgroundColor: null,
              scale: 2,
              dpi: 400,
              logging: true,
              width: element.offsetWidth,
              height: element.offsetHeight,
              windowWidth: element.offsetWidth,
              windowHeight: element.offsetHeight,
              scrollX: 0,
              scrollY: 0,
              x: 0,
              y: 0,
            })
              .then(canvas => {
                const dataUrl = canvas.toDataURL('image/jpeg', 1)
                this.$emit('share-generated', dataUrl)
                resolve()
              })
              .catch(err => {
                console.error('html2canvas截取失败:', err)
                reject(err)
              })
          }, 1000)
        }

        // 开始等待图片加载
        waitForImages()
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.default-share-page {
  position: relative;
  width: 600rpx;
  height: 1298rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 背景图片样式 */
.share-bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 600rpx;
  height: 1298rpx;
  z-index: 1;
}

.share-wrapper {
  position: absolute;
  z-index: 2;
  top: 320rpx;
  left: 150rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.portal-frame {
  // padding: 32rpx;
  width: 300rpx;
  border-radius: 40rpx;
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  opacity: 0;
  transform: translateY(20rpx);
  transition: all 0.3s ease;
}

.portal-frame.is-loaded {
  opacity: 1;
  transform: translateY(0);
}

/* 二维码样式区域 - 用户自定义样式位置 */
.qr-code-outer {
  width: 240rpx;
  height: 240rpx;
  // background: rgba(255, 255, 255, 0.98);
  border-radius: 20rpx;
  // box-shadow: 0px 8rpx 20rpx rgba(50, 50, 90, 0.06);
  // border: 1px solid #990;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx;
  box-sizing: border-box;
}

.qr-code,
.qr-code-placeholder {
  width: 100%;
  height: 100%;
}

.qr-code {
  border-radius: 16rpx;
}

.qr-code-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loader {
  width: 100rpx;
  height: 100rpx;
  border: 8rpx solid rgba(0, 0, 0, 0.1);
  border-left-color: #0072ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 会员编号样式区域 - 用户自定义样式位置 */
.member-code-text {
  font-size: 24rpx;
  color: #005bac;
  font-weight: bold;
  margin-top: 10rpx;
}
</style>
