<template>
  <view id="shareContainer" class="share-container">
    <!-- Portal Frame: The main content to be saved. -->
    <view class="portal-frame" :class="{ 'is-loaded': isLoaded }">
      <!-- The single, robust QR Code card -->
      <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>

      <!-- The real, clickable button -->
      <button class="share-button" @click="sharePage" v-show="shareButtonShow">
        保存图片并分享
      </button>
    </view>

    <!-- Canvas for generating the share image, positioned off-screen -->
    <canvas
      canvas-id="shareCanvas"
      :style="{
        width: canvasWidth + 'px',
        height: canvasHeight + 'px',
        position: 'fixed',
        left: '200%',
      }"
    />
  </view>
</template>

<script>
import html2canvas from 'html2canvas'
import { getShareCode } from '@/config/share'

export default {
  name: 'ShareQRCode',
  data() {
    return {
      qrCodeImage: '',
      // Set canvas dimensions. It's better to get device screen width for this.
      canvasWidth: 375,
      canvasHeight: 800,
      isLoaded: false,
      shareButtonShow: true,
    }
  },
  onLoad() {
    this.handleGetShareCode()
    // Get screen width to set canvas width dynamically
    uni.getSystemInfo({
      success: res => {
        this.canvasWidth = res.windowWidth
        // Set canvas height to a fixed 800px as requested
        this.canvasHeight = 800
      },
    })
  },
  onReady() {
    // Use a short timeout to ensure the initial render is complete before animation
    setTimeout(() => {
      this.isLoaded = true
    }, 100)
  },
  methods: {
    handleGetShareCode() {
      // Don't show loading toast, use the placeholder loader instead
      // uni.showLoading({ title: '加载中...' })
      getShareCode()
        .then(res => {
          // The screenshot shows the base64 string is in data.datStr
          if (res.code === 200 && res.data && res.data.dataStr) {
            this.qrCodeImage = 'data:image/png;base64,' + res.data.dataStr
          } else {
            uni.showToast({
              title: '获取分享码失败',
              icon: 'none',
            })
          }
        })
        .catch(err => {
          console.error('getShareCode error:', err)
          uni.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none',
          })
        })
    },

    async sharePage() {
      if (!this.qrCodeImage) {
        uni.showToast({
          title: '二维码尚未生成',
          icon: 'none',
        })
        return
      }
      this.shareButtonShow = false
      uni.showLoading({ title: '正在生成图片...' })

      try {
        // --- Button Swap Logic ---
        this.shareButtonShow = false
        // Wait for DOM to update with the fake button
        await this.$nextTick()

        // #ifdef H5
        // Capture the entire container as requested
        await this.captureWithHtml2Canvas()
        // #endif

        // #ifndef H5
        // Draw the entire container using Canvas
        await this.generateImageWithCanvas()
        // #endif
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: '图片生成失败，请稍后重试', icon: 'none' })
        console.error('sharePage error:', error)
      } finally {
        // --- Always swap back to the real button ---
        this.shareButtonShow = true
      }
    },

    // --- H5-specific method ---
    captureWithHtml2Canvas() {
      return new Promise((resolve, reject) => {
        // #ifdef H5
        // Target the entire #shareContainer as per instruction
        const element = document.getElementById('shareContainer')
        if (!element) {
          uni.hideLoading()
          return reject(new Error('Share container element not found'))
        }

        html2canvas(element, {
          useCORS: true,
          allowTaint: true,
          backgroundColor: null,
          scale: window.devicePixelRatio || 2,
          logging: false,
        })
          .then(canvas => {
            this.saveImageToAlbum(canvas.toDataURL('image/png', 1.0))
            resolve()
          })
          .catch(err => {
            console.error('html2canvas capture failed:', err)
            reject(err)
          })
        // #endif
      })
    },

    // A robust canvas-based image generation for all platforms
    async generateImageWithCanvas() {
      try {
        // Load all required images before drawing
        const [bgImageTempPath, qrCodeTempPath] = await Promise.all([
          this.getLocalImageTempPath('/static/images/share-bg.png'),
          this.base64ToTempFilePath(this.qrCodeImage),
        ])

        if (!bgImageTempPath || !qrCodeTempPath) {
          throw new Error('Image resource failed to load')
        }

        const ctx = uni.createCanvasContext('shareCanvas', this)
        // Draw the entire scene to the canvas
        this.drawSceneToCanvas(ctx, bgImageTempPath, qrCodeTempPath)

        return new Promise(resolve => {
          setTimeout(() => {
            ctx.draw(false, () => {
              setTimeout(() => {
                this.saveCanvasToAlbum()
                resolve()
              }, 500)
            })
          }, 100)
        })
      } catch (error) {
        console.error('generateImageWithCanvas error:', error)
        throw error
      }
    },

    // Main drawing function to replicate the entire scene on canvas
    drawSceneToCanvas(ctx, bgPath, qrPath) {
      const canvasWidth = this.canvasWidth
      const canvasHeight = this.canvasHeight // Fixed at 800px

      // 1. Draw background image
      ctx.drawImage(bgPath, 0, 0, canvasWidth, canvasHeight)

      // 2. Draw portal frame (calculations for centering)
      const portalWidth = canvasWidth * 0.85
      const portalPadding = 20
      // The white card's width is the portal's inner width
      const cardWidth = portalWidth - portalPadding * 2
      // The card is a square, so its height is its width
      const cardHeight = cardWidth
      const buttonHeight = 50
      const buttonMargin = 20
      const portalHeight =
        portalPadding * 2 + cardHeight + buttonMargin + buttonHeight
      const portalX = (canvasWidth - portalWidth) / 2
      const portalY = (canvasHeight - portalHeight) / 2
      this.drawPortalFrame(ctx, portalX, portalY, portalWidth, portalHeight)

      // 3. Draw the white QR card
      const cardX = portalX + portalPadding
      const cardY = portalY + portalPadding
      this.drawQrCodeCard(ctx, cardX, cardY, cardWidth, cardHeight)

      // 4. Draw the FAKE button to match the CSS
      const buttonX = cardX
      const buttonY = cardY + cardHeight + buttonMargin
      this.drawStyledButton(
        ctx,
        buttonX,
        buttonY,
        cardWidth,
        buttonHeight,
        '保存图片并分享'
      )

      // 5. Draw the actual QR image (or loader placeholder) on top
      // If qrPath is null/empty, this block is skipped, leaving the white card empty (like a placeholder)
      if (qrPath) {
        // Padding inside the white card
        const imagePadding = cardWidth * 0.1
        const qrCodeSize = cardWidth - imagePadding * 2
        const qrCodeX = cardX + imagePadding
        const qrCodeY = cardY + imagePadding
        ctx.drawImage(qrPath, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize)
      } else {
        // Draw loader manually if QR is not available
        // This part is complex, for now we show an empty card which is better than broken UI
      }
    },

    // Helper: Draws the portal frame to match CSS
    drawPortalFrame(ctx, x, y, width, height) {
      const radius = 25 // 50rpx
      ctx.save()
      this.drawRoundedRect(ctx, x, y, width, height, radius)
      // Frosted glass effect
      const portalGradient = ctx.createLinearGradient(x, y, x, y + height)
      portalGradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)')
      portalGradient.addColorStop(1, 'rgba(255, 255, 255, 0.2)')
      ctx.fillStyle = portalGradient
      ctx.fill()
      // Inner glow border
      ctx.shadowColor = 'rgba(255, 255, 255, 0.5)'
      ctx.shadowBlur = 10
      ctx.strokeStyle = 'rgba(255, 255, 255, 0.6)'
      ctx.lineWidth = 1.5
      ctx.stroke()
      ctx.restore()
    },

    // New/Refactored Helper: Draws the single white QR Code card
    drawQrCodeCard(ctx, x, y, width, height) {
      const borderRadius = 20 // 40rpx

      ctx.save()
      this.drawRoundedRect(ctx, x, y, width, height, borderRadius)
      // Card background
      ctx.fillStyle = 'rgba(255, 255, 255, 0.98)'
      // Card shadow
      ctx.shadowColor = 'rgba(50, 50, 90, 0.1)'
      ctx.shadowBlur = 30
      ctx.shadowOffsetY = 15
      ctx.fill()
      // Card border
      ctx.strokeStyle = '#f0f0f0'
      ctx.lineWidth = 1
      ctx.stroke()
      ctx.restore()
    },

    // Helper: Draws the styled button
    drawStyledButton(ctx, x, y, width, height, text) {
      const radius = height / 2

      ctx.save()
      this.drawRoundedRect(ctx, x, y, width, height, radius)
      // Background gradient
      const gradient = ctx.createLinearGradient(x, y, x + width, y)
      gradient.addColorStop(0, '#0ff0fc')
      gradient.addColorStop(0.5, '#0072ff')
      gradient.addColorStop(1, '#00c6ff')
      ctx.fillStyle = gradient
      // Shadow
      ctx.shadowColor = 'rgba(0, 114, 255, 0.35)'
      ctx.shadowBlur = 20
      ctx.shadowOffsetY = 8
      ctx.fill()
      ctx.restore()

      // Text
      ctx.save()
      ctx.fillStyle = '#ffffff'
      ctx.font = '17px sans-serif'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(text, x + width / 2, y + height / 2)
      ctx.restore()
    },

    // Helper: Draw a rectangle with rounded corners
    drawRoundedRect(ctx, x, y, width, height, radius) {
      if (width < 2 * radius) radius = width / 2
      if (height < 2 * radius) radius = height / 2
      ctx.beginPath()
      ctx.moveTo(x + radius, y)
      ctx.arcTo(x + width, y, x + width, y + height, radius)
      ctx.arcTo(x + width, y + height, x, y + height, radius)
      ctx.arcTo(x, y + height, x, y, radius)
      ctx.arcTo(x, y, x + width, y, radius)
      ctx.closePath()
    },

    saveCanvasToAlbum() {
      try {
        // 统一的canvas转换参数
        const options = {
          canvasId: 'shareCanvas',
          fileType: 'png',
          quality: 1,
          success: res => {
            console.log('canvas转换成功:', res)
            if (res.tempFilePath) {
              this.saveImageToAlbum(res.tempFilePath)
            } else {
              uni.hideLoading()
              uni.showToast({ title: '图片生成失败', icon: 'none' })
            }
          },
          fail: err => {
            console.error('canvas转换失败:', err)
            uni.hideLoading()
            uni.showToast({ title: '图片转换失败', icon: 'none' })
          },
        }

        // 调用canvas转换API
        uni.canvasToTempFilePath(options, this)
      } catch (error) {
        console.error('saveCanvasToAlbum error:', error)
        uni.hideLoading()
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },

    // 新增：统一的图片保存方法
    saveImageToAlbum(filePath) {
      // #ifdef H5
      // For H5, trigger download instead of saving to album
      const link = document.createElement('a')
      link.href = filePath
      link.download = `share_page_${Date.now()}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      uni.hideLoading()
      uni.showToast({
        title: '图片已开始下载',
        icon: 'success',
      })
      // #endif

      // #ifndef H5
      // For App and Mini Programs
      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          uni.hideLoading()
          uni.showToast({
            title: '图片已保存到相册',
            icon: 'success',
          })
        },
        fail: err => {
          uni.hideLoading()
          if (
            err.errMsg &&
            (err.errMsg.includes('auth deny') ||
              err.errMsg.includes('auth denied'))
          ) {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存相册',
              showCancel: false,
              success: () => {
                uni.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      uni.showToast({
                        title: '授权成功，请重试',
                        icon: 'none',
                      })
                    } else {
                      uni.showToast({
                        title: '获取权限失败',
                        icon: 'none',
                      })
                    }
                  },
                })
              },
            })
          } else {
            uni.showToast({ title: '保存失败', icon: 'none' })
            console.error('saveImageToPhotosAlbum fail:', err)
          }
        },
      })
      // #endif
    },

    base64ToTempFilePath(base64) {
      return new Promise((resolve, reject) => {
        try {
          // #ifdef H5
          // For H5, we load the base64 into an Image to ensure it's valid,
          // but resolve with the base64 string to avoid Uniapp's internal errors
          // when its functions expect a string path instead of an Image object.
          const image = new Image()
          // Resolve CORS issue for QR code from different origin
          image.crossOrigin = 'Anonymous'
          image.src = base64
          image.onload = () => {
            // Resolve with the string, not the object.
            resolve(base64)
          }
          image.onerror = err => {
            console.error('Failed to load image for canvas on H5', err)
            reject(new Error('H5图片加载失败'))
          }
          // #endif

          // #ifndef H5
          // For App and Mini Programs, write to a temp file and return the path.
          if (!base64 || typeof base64 !== 'string') {
            reject(new Error('无效的base64数据'))
            return
          }

          const formattedBase64 = base64.replace(/^data:image\/\w+;base64,/, '')
          if (!formattedBase64) {
            reject(new Error('base64数据格式错误'))
            return
          }

          // Use a standard path for user data directory.
          const filePath = `${uni.env.USER_DATA_PATH}/share_${Date.now()}.png`
          const fileManager = uni.getFileSystemManager()

          fileManager.writeFile({
            filePath,
            data: formattedBase64,
            encoding: 'base64',
            success: () => {
              resolve(filePath)
            },
            fail: err => {
              console.error('Failed to write temp file', err)
              reject(new Error('临时文件写入失败'))
            },
          })
          // #endif
        } catch (error) {
          console.error('base64ToTempFilePath error:', error)
          reject(new Error('图片处理失败'))
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.share-container {
  background: url('@/static/images/share-bg.png') no-repeat center center;
  background-size: 100% 100%;
  height: calc(100vh - 80rpx);
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.share-bg {
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}

.portal-frame {
  /* Restyled to match the ideal screenshot */
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  padding: 40rpx;
  margin-top: 450rpx;
  border-radius: 50rpx;
  border: 1.5px solid rgba(255, 255, 255, 0.6);
  box-shadow:
    0 0 0 1.5px rgba(255, 255, 255, 0.4) inset,
    0 15rpx 40rpx rgba(0, 0, 0, 0.1);
  display: flex;
  width: 90%;
  box-sizing: border-box;

  flex-direction: column;
  align-items: center;
  /* Removed margin-top, parent container handles centering */
}

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

.title {
  font-size: 44rpx;
  font-weight: 500;
  color: #1e1e1e;
  margin-bottom: 60rpx;
}

/* The single white card for the QR code */
.qr-code-outer {
  width: 100%;
  /* This creates a responsive square that's always perfect */
  aspect-ratio: 1 / 1;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 40rpx;
  box-shadow: 0px 15rpx 30rpx rgba(50, 50, 90, 0.1);
  border: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx; /* Padding inside the white card */
  box-sizing: border-box;
}

/* The image and the placeholder both live inside the outer card */
.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);
  }
}

.tip {
  font-size: 30rpx;
  color: #888;
}

/* Unified style for both the real button and the fake one (which is a view) */
.share-button {
  margin-top: 40rpx;
  width: 100%; /* Button takes full width of portal frame padding */
  height: 100rpx;
  line-height: 100rpx;
  color: #fff;
  border-radius: 50rpx;
  font-size: 34rpx;
  /* Match the gradient from canvas drawing */
  background: linear-gradient(100deg, #0ff0fc 0%, #0072ff 50%, #00c6ff 100%);
  box-shadow: 0 8rpx 20rpx 0 rgba(0, 114, 255, 0.35);
  border: none;
  padding: 0;
  text-align: center;
  /* Add transition for the button itself if needed */
}

/* The real button needs to override some uni-app defaults */
button.share-button {
  padding: 0;
  line-height: 100rpx; /* Ensure text is centered vertically */
  border: none;
}

.share-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 6rpx 12rpx rgba(0, 114, 255, 0.3);
}
</style>
