<template>
  <view
    class="share-page"
    style="display: flex; flex-direction: column; height: 100vh"
  >
    <view id="shareContainer" class="share-container">
      <!-- 默认场景 -->
      <DefaultSharePage
        v-if="isDefaultScene"
        :qrCodeImage="qrCodeImage"
        :userInfo="userInfo"
        :isWechat="isWechat"
        :isLoaded="isLoaded"
        @share-generated="handleShareGenerated"
        ref="defaultSharePage"
      />

      <!-- 特殊场景 -->
      <SpecialSharePage
        v-if="isSpecialScene && sourceVisible"
        :qrCodeImage="qrCodeImage"
        :specialBackgroundImage="userInfo.sharePosterImage"
        :userInfo="userInfo"
        :isWechat="isWechat"
        :isLoaded="isLoaded"
        @share-generated="handleShareGenerated"
        ref="specialSharePage"
      />

      <!-- 微信环境全屏图片显示 -->
      <view class="wechat-fullscreen-overlay" v-show="generatedImageUrl">
        <img
          class="fullscreen-image"
          :src="generatedImageUrl"
          width="100%"
          height="100%"
          @click.stop=""
        />
      </view>
    </view>
    <view v-show="!generatedImageUrl" class="mask-loading"></view>
    <cl-tabbar class="tabbar" :current="2" />
  </view>
</template>

<script>
import { getShareCode } from '@/config/share'
import clTabbar from '@/components/cl-tabbar.vue'
import DefaultSharePage from '@/components/share/DefaultSharePage.vue'
import SpecialSharePage from '@/components/share/SpecialSharePage.vue'

export default {
  name: 'ShareQRCode',
  components: {
    'cl-tabbar': clTabbar,
    DefaultSharePage,
    SpecialSharePage,
  },
  data() {
    return {
      qrCodeImage: '',
      canvasWidth: 375,
      canvasHeight: 800,
      isLoaded: false,
      isWechat: false,
      generatedImageUrl: '',
      userInfo: uni.getStorageSync('User'),
      sourceVisible: true,
    }
  },
  computed: {
    isSpecialScene() {
      return this.userInfo && this.userInfo.sharePosterImage
    },
    isDefaultScene() {
      return !this.isSpecialScene
    },
  },
  onLoad() {
    this.checkWechatEnvironment()
    this.handleGetShareCode()
    // 获取屏幕尺寸
    uni.getSystemInfo({
      success: res => {
        this.canvasWidth = res.windowWidth
        this.canvasHeight = res.windowHeight
      },
    })
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
  },
  onReady() {
    // 短暂延迟后启用加载动画
    setTimeout(() => {
      this.isLoaded = true
    }, 100)
  },
  methods: {
    // 检测微信环境
    checkWechatEnvironment() {
      const ua = navigator.userAgent.toLowerCase()
      this.isWechat = ua.includes('micromessenger')
      console.log('微信环境检测:', this.isWechat)
    },

    // 获取分享二维码
    handleGetShareCode() {
      getShareCode()
        .then(res => {
          if (res.code === 200 && res.data && res.data.dataStr) {
            this.qrCodeImage = 'data:image/png;base64,' + res.data.dataStr
            this.$nextTick(() => {
              this.generateShareImage()
            })
          } else {
            uni.showToast({
              title: '获取分享码失败',
              icon: 'none',
            })
          }
        })
        .catch(err => {
          console.error('getShareCode error:', err)
          uni.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none',
          })
        })
    },

    // 生成分享图片
    async generateShareImage() {
      try {
        if (this.isSpecialScene) {
          await this.$refs.specialSharePage.generateShareImage()
        } else {
          // 默认场景生成图片
          await this.$refs.defaultSharePage.sharePage()
        }
      } catch (error) {
        console.error('生成分享图片失败:', error)
      }
    },

    // 处理分享图片生成完成
    handleShareGenerated(dataUrl) {
      uni.hideLoading()
      this.$nextTick(() => {
        this.sourceVisible = false
      })
      uni.hideLoading()

      this.generatedImageUrl = dataUrl
    },

    // 下载图片
    downloadImage(dataUrl) {
      const link = document.createElement('a')
      link.href = dataUrl
      link.download = `share_page_${Date.now()}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
  },
}
</script>

<style lang="scss" scoped>
.share-container {
  flex: 1;
  height: 0;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 微信环境全屏覆盖样式 */
.wechat-fullscreen-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100%;
  background-color: transparent;
  z-index: 999;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: stretch;
  padding: 0;
  margin: 0;
}

.fullscreen-image {
  width: 100vw;
  height: 100%;
  margin: 0;
  padding: 0;
  border: none;
  display: block;
}

.tabbar {
  position: static;
  bottom: 0;
  z-index: 1000;
  width: 100%;
  height: 50px;
  :v-deep .u-tabbar--fixed {
    height: 100px !important;
  }
}

@media screen and (max-height: 667px) {
  .tabbar {
    height: 70px !important;
  }
}

@media screen and (min-height: 812px) {
  .tabbar {
    height: 80px !important;
  }
}
.mask-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000;
  background-color: #fff;
}
</style>
