<template>
  <view class="invite-poster">
    <view v-if="loading" class="poster-loading flex items-center justify-center py-12 text-gray-500 text-sm">
      生成海报中…
    </view>
    <view v-else-if="error" class="poster-error rounded-lg bg-gray-100 p-4 text-center text-gray-500 text-sm">
      海报加载失败，请复制链接分享
    </view>
    <view v-else class="poster-wrap rounded-xl overflow-hidden bg-white">
      <image
        :src="posterUrl"
        mode="widthFix"
        class="poster-image block w-full"
        @load="onImageLoad"
        @error="onImageError"
      />
      <view class="p-4 border-t border-gray-100">
        <view class="text-xs text-gray-500 mb-2">长按上方海报保存图片，或点击下方按钮保存</view>
        <wd-button type="primary" block @click="savePoster">保存海报</wd-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { generateInvitePoster } from '@/api/agent'

const props = defineProps({
  inviteLink: { type: String, default: '' },
})

const loading = ref(true)
const error = ref(false)
const posterUrl = ref('')

// 从后端API获取海报
async function generate() {
  if (!props.inviteLink) {
    loading.value = false
    error.value = true
    return
  }
  loading.value = true
  error.value = false
  try {
    console.log('开始生成海报，邀请链接:', props.inviteLink)
    const { data, error: apiError } = await generateInvitePoster({
      invite_link: props.inviteLink,
    })

    console.log('海报API响应:', { data: data.value, error: apiError.value })

    if (data.value && !apiError.value) {
      if (data.value.code === 200 && data.value.data?.poster_url) {
        posterUrl.value = data.value.data.poster_url
        loading.value = false
        console.log('海报生成成功')
      } else {
        console.error('生成海报失败:', data.value?.msg || data.value)
        uni.showToast({ title: data.value?.msg || '生成海报失败', icon: 'none' })
        error.value = true
        loading.value = false
      }
    } else {
      console.error('生成海报API调用失败:', apiError.value, '响应数据:', data.value)
      uni.showToast({ title: apiError.value || '网络请求失败', icon: 'none' })
      error.value = true
      loading.value = false
    }
  } catch (e) {
    console.error('InvitePoster generate error', e)
    uni.showToast({ title: '生成海报异常: ' + (e.message || String(e)), icon: 'none' })
    error.value = true
    loading.value = false
  }
}

function onImageLoad() {
  console.log('海报图片加载成功')
}

function onImageError() {
  console.error('海报图片加载失败')
  error.value = true
  loading.value = false
}

function savePoster() {
  if (!posterUrl.value) {
    uni.showToast({ title: '请等待海报生成完成', icon: 'none' })
    return
  }
  
  // #ifdef H5
  // H5端：创建a标签下载
  const link = document.createElement('a')
  link.href = posterUrl.value
  link.download = '邀请海报.png'
  link.click()
  uni.showToast({ title: '已保存', icon: 'success' })
  // #endif
  
  // #ifndef H5
  // 小程序端：base64 data URL需要先转换为临时文件
  if (posterUrl.value.startsWith('data:')) {
    // base64 data URL，需要转换为临时文件
    const base64Data = posterUrl.value.split(',')[1]
    const fs = uni.getFileSystemManager()
    const filePath = `${uni.env.USER_DATA_PATH}/invite_poster_${Date.now()}.png`
    
    fs.writeFile({
      filePath: filePath,
      data: base64Data,
      encoding: 'base64',
      success: () => {
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: () => uni.showToast({ title: '已保存到相册', icon: 'success' }),
          fail: (err) => {
            if (err.errMsg && err.errMsg.indexOf('auth') !== -1) {
              uni.showModal({
                title: '提示',
                content: '需要您授权保存图片到相册',
                success: (m) => m.confirm && uni.openSetting(),
              })
            } else {
              uni.showToast({ title: '保存失败', icon: 'none' })
            }
          },
        })
      },
      fail: () => uni.showToast({ title: '转换图片失败', icon: 'none' }),
    })
  } else {
    // 普通URL，直接下载
    uni.downloadFile({
      url: posterUrl.value,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => uni.showToast({ title: '已保存到相册', icon: 'success' }),
            fail: (err) => {
              if (err.errMsg && err.errMsg.indexOf('auth') !== -1) {
                uni.showModal({
                  title: '提示',
                  content: '需要您授权保存图片到相册',
                  success: (m) => m.confirm && uni.openSetting(),
                })
              } else {
                uni.showToast({ title: '保存失败', icon: 'none' })
              }
            },
          })
        } else {
          uni.showToast({ title: '下载失败', icon: 'none' })
        }
      },
      fail: () => uni.showToast({ title: '下载失败', icon: 'none' }),
    })
  }
  // #endif
}

watch(() => props.inviteLink, (val) => {
  if (val) generate()
}, { immediate: false })

onMounted(() => {
  if (props.inviteLink) generate()
})
</script>

<style scoped>
.poster-image {
  display: block;
  max-width: 100%;
  height: auto;
}
</style>
