<template>
  <view class="agreement-detail-page">
    <!-- 顶部渐变背景区域 -->
    <view class="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content">
        <view class="back-btn" @click="handleBack">
          <text class="back-icon">‹</text>
        </view>
        <text class="header-title">{{ pageTitle }}</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <scroll-view scroll-y class="content-scroll">
        <view class="agreement-content">
          <rich-text :nodes="agreementContent"></rich-text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getAgreementContent } from '@/apis/setting'

const { t, locale } = useI18n()

// 状态栏高度
const statusBarHeight = ref(0)

// 协议类型
const agreementType = ref('')

// 协议内容
const agreementContent = ref('')

// 加载状态
const loading = ref(false)

// 页面标题
const pageTitle = computed(() => {
  return agreementType.value === 'user' ? t('aggreement.userAgreementTitle') : t('aggreement.privacyPolicyTitle')
})


onMounted(async () => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  agreementType.value = currentPage.options.type || 'user'
  
  // 获取协议内容
  await fetchAgreementContent()
})

// 返回上一页
const handleBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.reLaunch({
      url: '/pages/home/index'
    })
  }
}

// 获取协议内容
const fetchAgreementContent = async () => {
  try {
    loading.value = true
    
    // 显示加载提示
    uni.showLoading({
      title: t('aggreement.loading'),
      mask: true
    })
    
    // 调用API获取内容
    const response = await getAgreementContent(agreementType.value)
    
    if (response && response.code === 200 && response.data && response.data.content) {
      // 解析JSON字符串
      try {
        const contentObj = JSON.parse(response.data.content)
        
        // 根据当前语言环境选择对应的内容
        const currentLocale = locale.value // 'zh-CN' 或 'en-US'
        const localeKey = currentLocale.replace('-', '_') // 转换为 'zh_CN' 或 'en_US'
        
        // 优先使用当前语言，如果不存在则使用中文，再不存在则使用任意可用语言
        agreementContent.value = contentObj[localeKey] || 
                                 contentObj['zh_CN'] || 
                                 contentObj['en_US'] || 
                                 Object.values(contentObj)[0] || 
                                 ''
      } catch (parseError) {
        console.error('解析协议内容JSON失败:', parseError)
        // 如果解析失败，尝试直接使用原始内容
        agreementContent.value = response.data.content
      }
    } else {
      throw new Error(response?.msg || '获取失败')
    }
  } catch (error) {
    console.error('获取协议内容失败:', error)
    
    uni.showToast({
      title: error.message || t('aggreement.loadFailed'),
      icon: 'none',
      duration: 2000
    })
    
    // 失败时显示默认内容
    agreementContent.value = getDefaultContent()
  } finally {
    loading.value = false
    uni.hideLoading()
  }
}

// 获取默认内容（API失败时的后备方案）
const getDefaultContent = () => {
  if (agreementType.value === 'user') {
    return `
      <div style="padding: 20px; line-height: 1.8; color: #333;">
        <h2 style="text-align: center; color: #1ec9c9; margin-bottom: 20px;">${t('aggreement.userAgreementTitle')}</h2>
        <p>${t('aggreement.loadFailed')}</p>
      </div>
    `
  } else {
    return `
      <div style="padding: 20px; line-height: 1.8; color: #333;">
        <h2 style="text-align: center; color: #1ec9c9; margin-bottom: 20px;">${t('aggreement.privacyPolicyTitle')}</h2>
        <p>${t('aggreement.loadFailed')}</p>
      </div>
    `
  }
}
</script>

<style lang="scss" scoped>
.agreement-detail-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  
  // 顶部渐变背景
  .header-bg {
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    
    .header-content {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      
      .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        
        .back-icon {
          font-size: 56rpx;
          color: #ffffff;
          font-weight: 300;
        }
      }
      
      .header-title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
      }
      
      .placeholder {
        width: 60rpx;
      }
    }
  }
  
  // 页面内容
  .page-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .content-scroll {
      flex: 1;
      width: 100%;
      height: 100%;
      
      .agreement-content {
        padding: 32rpx 24rpx;
        
        ::v-deep h1 {
          font-size: 40rpx;
          font-weight: 700;
          color: #333333;
          margin-bottom: 32rpx;
          line-height: 1.5;
        }
        
        ::v-deep h2 {
          font-size: 36rpx;
          font-weight: 600;
          color: #333333;
          margin: 40rpx 0 24rpx;
          line-height: 1.5;
        }
        
        ::v-deep h3 {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          margin: 32rpx 0 20rpx;
          line-height: 1.5;
        }
        
        ::v-deep p {
          font-size: 28rpx;
          line-height: 1.8;
          color: #666666;
          margin-bottom: 24rpx;
          text-align: justify;
        }
        
        ::v-deep ul, ::v-deep ol {
          padding-left: 40rpx;
          margin-bottom: 24rpx;
          
          li {
            font-size: 28rpx;
            line-height: 1.8;
            color: #666666;
            margin-bottom: 16rpx;
          }
        }
        
        ::v-deep strong, ::v-deep b {
          font-weight: 600;
          color: #333333;
        }
        
        ::v-deep a {
          color: #1ec9c9;
          text-decoration: underline;
        }
        
        ::v-deep div {
          font-size: 28rpx;
          line-height: 1.8;
          color: #666666;
        }
      }
    }
  }
}
</style>
