<template>
  <view class="agreement-detail-page">
    <!-- 自定义头部 -->
    <view class="custom-header" :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-body" :style="{ paddingTop: headerHeight + 'px' }">
      <view class="content-wrapper">
        <scroll-view scroll-y class="content-scroll">
          <rich-text :nodes="agreementContent" class="agreement-content"></rich-text>
        </scroll-view>
      </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 headerHeight = computed(() => {
  return statusBarHeight.value + 44 // 44px是导航栏高度
})

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

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

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

// 页面标题
const pageTitle = computed(() => {
  return agreementType.value === 'user' 
    ? t('pagesContent.my.agreement.userAgreement')
    : t('pagesContent.my.agreement.privacyPolicy')
})


onMounted(async () => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  agreementType.value = currentPage.options.type || 'user'
  
  console.log('协议详情页面已加载, 类型:', agreementType.value)
  
  // 获取协议内容
  await fetchAgreementContent()
})

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

// 获取协议内容
const fetchAgreementContent = async () => {
  try {
    loading.value = true
    
    // 显示加载提示
    uni.showLoading({
      title: t('common.message.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] || 
                                 ''
        
        console.log('已加载协议内容，语言:', localeKey)
      } 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 || '获取协议内容失败',
      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: #667eea; margin-bottom: 20px;">用户服务协议</h2>
        <p>协议内容加载失败，请稍后重试。</p>
      </div>
    `
  } else {
    return `
      <div style="padding: 20px; line-height: 1.8; color: #333;">
        <h2 style="text-align: center; color: #667eea; margin-bottom: 20px;">隐私政策</h2>
        <p>协议内容加载失败，请稍后重试。</p>
      </div>
    `
  }
}
</script>

<style lang="scss" scoped>
.agreement-detail-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #f0f4ff 0%, #f8f9fa 100%);
  
  // 自定义头部
  .custom-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    border-bottom: 1rpx solid #e5e5e5;
    z-index: 100;
    
    .header-content {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 32rpx;
      
      .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .back-icon {
          font-size: 56rpx;
          color: #333333;
          font-weight: 300;
        }
      }
      
      .header-title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 500;
        color: #000000;
      }
      
      .placeholder {
        width: 60rpx;
      }
    }
  }
  
  // 页面内容
  .page-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .content-wrapper {
      flex: 1;
      margin: 40rpx;
      background-color: #ffffff;
      border-radius: 20rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
      overflow: hidden;
      
      .content-scroll {
        width: 100%;
        height: 100%;
        
        .agreement-content {
          padding: 40rpx;
          
          ::v-deep h2 {
            font-size: 36rpx;
            font-weight: bold;
            margin-bottom: 30rpx;
          }
          
          ::v-deep h3 {
            font-size: 30rpx;
            font-weight: 600;
            margin: 30rpx 0 20rpx;
          }
          
          ::v-deep p {
            font-size: 28rpx;
            line-height: 1.8;
            margin-bottom: 20rpx;
            text-align: justify;
          }
          
          ::v-deep ul {
            padding-left: 40rpx;
            margin-bottom: 20rpx;
            
            li {
              font-size: 28rpx;
              line-height: 1.8;
              margin-bottom: 10rpx;
              list-style-type: disc;
            }
          }
        }
      }
    }
  }
}
</style>
