<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>代理分享連結</span>
        </div>
      </template>
      <div class="share-link-container">
        <div class="link-label">您的分享連結：</div>
        <div class="link-content">
          <el-input
            v-model="shareLink"
            readonly
            class="link-input"
          >
            <template #append>
              <el-button
                type="primary"
                :icon="DocumentCopy"
                @click="handleCopy"
              >
                複製連結
              </el-button>
            </template>
          </el-input>
        </div>
        <div class="link-tip">
          <el-alert
            title="提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>複製此連結發送給其他人，他們可以通過此連結註冊成為您的會員。</p>
            </template>
          </el-alert>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

// 分享連結的基礎URL
const baseUrl =import.meta.env.VITE_APP_USER_APP_URL+'/#/pages/registerMember'

// 生成分享連結
const shareLink = computed(() => {
  if (!userStore.id || !userStore.name) {
    return ''
  }
  
  // 構建數據對象
  const data = {
    agentId: userStore.id,
    agentName: userStore.name
  }
  
  // 將對象轉換為 JSON 字串，然後進行 base64 編碼
  const jsonStr = JSON.stringify(data)
  const base64Data = btoa(unescape(encodeURIComponent(jsonStr)))
  
  // 構建完整的分享連結
  return `${baseUrl}?data=${base64Data}`
})

// 複製文字到剪貼板
function copyTextToClipboard(text) {
  const element = document.createElement('textarea')
  const previouslyFocusedElement = document.activeElement

  element.value = text
  element.setAttribute('readonly', '')
  element.style.contain = 'strict'
  element.style.position = 'absolute'
  element.style.left = '-9999px'
  element.style.fontSize = '12pt'

  const selection = document.getSelection()
  const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0)

  document.body.append(element)
  element.select()
  element.selectionStart = 0
  element.selectionEnd = text.length

  let isSuccess = false
  try {
    isSuccess = document.execCommand('copy')
  } catch { }

  element.remove()

  if (originalRange) {
    selection.removeAllRanges()
    selection.addRange(originalRange)
  }

  if (previouslyFocusedElement) {
    previouslyFocusedElement.focus()
  }

  return isSuccess
}

// 複製連結
function handleCopy() {
  if (!shareLink.value) {
    ElMessage.warning('分享連結生成失敗，請稍後再試')
    return
  }
  
  // 優先使用現代 Clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(shareLink.value).then(() => {
      ElMessage.success('連結已複製到剪貼板，可以貼上發送給其他人了')
    }).catch(() => {
      // 如果 Clipboard API 失敗，回退到傳統方法
      const success = copyTextToClipboard(shareLink.value)
      if (success) {
        ElMessage.success('連結已複製到剪貼板，可以貼上發送給其他人了')
      } else {
        ElMessage.error('複製失敗，請手動複製連結')
      }
    })
  } else {
    // 使用傳統方法
    const success = copyTextToClipboard(shareLink.value)
    if (success) {
      ElMessage.success('連結已複製到剪貼板，可以貼上發送給其他人了')
    } else {
      ElMessage.error('複製失敗，請手動複製連結')
    }
  }
}

onMounted(() => {
  // 確保用戶資訊已載入
  if (!userStore.name && userStore.token) {
    userStore.getInfo().catch(() => {
      ElMessage.error('獲取用戶資訊失敗')
    })
  }
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.box-card {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.share-link-container {
  padding: 20px 0;
}

.link-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  font-weight: 500;
}

.link-content {
  margin-bottom: 20px;
  
  .link-input {
    :deep(.el-input__inner) {
      font-size: 14px;
      color: #303133;
    }
  }
}

.link-tip {
  margin-top: 20px;
  
  :deep(.el-alert) {
    .el-alert__content {
      p {
        margin: 0;
        line-height: 1.6;
        color: #606266;
      }
    }
  }
}
</style>
