<template>
  <CustomNav title="健康提醒" leftType="back" />
  <view class="content">
    <view class="notification-toggle">
      <text class="notification-label">消息通知</text>
      <switch :checked="notificationsEnabled" @change="onNotificationChange" />
    </view>
    <view class="template-info">
      <text class="tmpl-title">每日健康上报提醒</text>
      <text class="tmpl-meta">模板编号：7536 · 模板ID：ACS7cwcbx0F0Y_YaB4GZr7rWP7BO2-7wQOtYsnUjmFI</text>
    </view>

    <view class="reminder-list">
      <view class="reminder-item" v-for="(reminder, index) in reminders" :key="index">
        <view class="reminder-info">
          <text class="reminder-title">{{ reminder.title }}</text>
          <text class="reminder-time">{{ reminder.time }}</text>
        </view>
        <switch :checked="reminder.enabled" @change="toggleReminder(index)" />
      </view>
    </view>
  </view>
  <TabBar />
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

import CustomNav from '@/components/custom-nav.vue'
import TabBar from '@/components/tab-bar.vue'

interface Reminder {
  title: string
  time: string
  enabled: boolean
}

const reminders = ref<Reminder[]>([
  { title: '喝水提醒', time: '08:00', enabled: true },
  { title: '运动提醒', time: '18:00', enabled: false },
  { title: '测量血压', time: '07:00', enabled: true },
  { title: '测量血糖', time: '12:00', enabled: false },
  { title: '服药提醒', time: '09:00', enabled: true }
])

// 模板 ID & 其他展示信息
const TEMPLATE_ID = 'ACS7cwcbx0F0Y_YaB4GZr7rWP7BO2-7wQOtYsnUjmFI'
const TEMPLATE_NO = '7536'

// 全局消息开关
const notificationsEnabled = ref<boolean>(false)

// 记录页面进入来源：'healthIndex' | 'subscribe' | 'unknown'
const entrySource = ref<'healthIndex' | 'subscribe' | 'unknown'>('unknown')
const entrySourceText = computed(() => {
  switch (entrySource.value) {
    case 'healthIndex':
      return '来自 健康首页'
    case 'subscribe':
      return '来自 订阅消息'
    default:
      return '来源 未知'
  }
})

onMounted(() => {
  try {
    const val = (uni as any).getStorageSync('notificationsEnabled')
    if (typeof val === 'boolean') notificationsEnabled.value = val
  } catch (e) {
    // 忽略错误
  }
  
  // 检查用户订阅状态
  checkSubscriptionStatus()
  
  // 尝试判断来源：优先检查页面栈的上一个页面；若无（直接打开），则检查 launch options 的 query
  try {
    const pages = (getCurrentPages as any)()
    console.log('当前页面栈:', pages)
    
    if (pages && pages.length >= 1) {
      const currentPage = pages[pages.length - 1]
      const currentRoute = currentPage?.route || currentPage?.__route || currentPage?.$page?.route
      const currentOptions = currentPage?.options || {}
      
      console.log('当前页面路由:', currentRoute)
      console.log('当前页面参数:', currentOptions)
      
      // 检查当前页面是否包含 from=subscribe 参数
      if (currentOptions.from === 'subscribe') {
        entrySource.value = 'subscribe'
        console.log('通过当前页面参数识别为订阅消息来源')
      }
      
      // 检查当前页面是否包含 templateId 相关参数
      if (currentOptions.templateId === TEMPLATE_ID || currentOptions.template_id === TEMPLATE_ID) {
        entrySource.value = 'subscribe'
        console.log('通过当前页面的模板ID参数识别为订阅消息来源')
      }
    }

    if (pages && pages.length >= 2) {
      const prev = pages[pages.length - 2]
      const prevRoute = prev?.route || prev?.__route || prev?.$page?.route
      console.log('上一页路由:', prevRoute)
      if (prevRoute && String(prevRoute).includes('pages/health/index')) {
        entrySource.value = 'healthIndex'
        console.log('识别来源为健康首页')
      }
    } else {
      // 如果没有上一页信息，检查小程序启动参数（例如用户通过订阅消息打开）
      if ((uni as any).getLaunchOptionsSync) {
        const launch = (uni as any).getLaunchOptionsSync()
        console.log('启动参数:', launch)
        if (launch && launch.query) {
          console.log('查询参数:', launch.query)
          // 如果你在推送消息里把 from=subscribe 作为参数传入，这里会命中
          if (launch.query.from === 'subscribe') {
            entrySource.value = 'subscribe'
            console.log('通过 from 参数识别为订阅消息来源')
          }
          // 有些平台会把 templateId 或其它字段放在 query 中，可据此判断
          if (launch.query.templateId === TEMPLATE_ID || launch.query.template_id === TEMPLATE_ID) {
            entrySource.value = 'subscribe'
            console.log('通过模板ID参数识别为订阅消息来源')
          }
        }
      }
    }
  } catch (e) {
    console.error('识别入口来源时出错:', e)
  }
  
  // 显示来源提示（用于测试），延迟一点以保证 UI 已就绪
  try {
    setTimeout(() => {
      console.log('入口来源:', entrySource.value, entrySourceText.value)
    }, 250)
  } catch (e) {
    // 忽略错误
  }
  
  if (entrySource.value === 'unknown') {
    console.log('入口来源默认为未知')
  }
})

/**
 * 检查用户订阅状态
 */
const checkSubscriptionStatus = () => {
  // 使用 uni.getSetting 检查用户授权状态
  if (typeof (uni as any).getSetting === 'function') {
    (uni as any).getSetting({
      withSubscriptions: true, // 启用订阅设置查询
      success: (res: any) => {
        console.log('用户设置:', res)
        
        // 检查订阅消息设置
        if (res.subscriptionsSetting) {
          console.log('订阅设置详情:', JSON.stringify(res.subscriptionsSetting, null, 2))
          
          // 检查主开关
          const mainSwitch = res.subscriptionsSetting.mainSwitch
          console.log('订阅主开关:', mainSwitch)
          
          // 检查针对特定模板的设置
          const itemSettings = res.subscriptionsSetting.itemSettings || {}
          const templateStatus = itemSettings[TEMPLATE_ID]
          console.log(`模板 ${TEMPLATE_ID} 状态:`, templateStatus)
          
          // 如果主开关关闭或特定模板被拒绝，则更新本地状态
          if (mainSwitch === false || templateStatus === 'reject' || templateStatus === 'ban') {
            console.log('用户关闭了订阅设置，正在更新本地状态')
            notificationsEnabled.value = false
            try {
              (uni as any).setStorageSync('notificationsEnabled', false)
            } catch (e) {
              console.error('更新存储失败:', e)
            }
          }
          // 如果模板被接受且主开关开启，更新本地状态为true
          else if (mainSwitch === true && templateStatus === 'accept') {
            console.log('用户开启了订阅设置，正在更新本地状态')
            notificationsEnabled.value = true
            try {
              (uni as any).setStorageSync('notificationsEnabled', true)
            } catch (e) {
              console.error('更新存储失败:', e)
            }
          }
        } else {
          console.log('响应中未找到订阅设置')
        }
      },
      fail: (err: any) => {
        console.error('获取用户设置失败:', err)
      }
    })
  } else {
    console.log('当前环境不支持 uni.getSetting')
  }
}

/**
 * 顶部总开关变更
 * - 打开时：调用 uni.requestSubscribeMessage 请求用户同意订阅 TEMPLATE_ID
 * - 如果用户同意（返回 accept），将状态置为 true 并持久化
 * - 否则回滚并提示
 */
const onNotificationChange = (e: any) => {
  const newVal = e?.detail?.value
  console.log('通知开关更改为:', newVal)
  
  if (newVal) {
    // 先将开关设置为开启状态
    notificationsEnabled.value = true
    
    // 请求订阅（仅在微信/小程序有效）
    ;(uni as any).requestSubscribeMessage({
      tmplIds: [TEMPLATE_ID],
      success(res: any) {
        console.log('订阅消息请求成功结果:', res)
        // res 可能形如 { "ACS7...": 'accept' }
        const result = res && res[TEMPLATE_ID]
        if (result === 'accept') {
          console.log('用户接受了订阅')
          try {
            ;(uni as any).setStorageSync('notificationsEnabled', true)
          } catch (err) {
            // 忽略存储错误
          }
          uni.showToast({ title: '订阅成功', icon: 'success' })
        } else {
          console.log('用户未接受订阅，结果:', result)
          // 用户拒绝或关闭了弹窗
          notificationsEnabled.value = false
          try {
            ;(uni as any).setStorageSync('notificationsEnabled', false)
          } catch (err) {}
          uni.showToast({ title: '订阅被拒绝', icon: 'none' })
        }
      },
      fail(err: any) {
        console.log('订阅消息请求失败:', err)
        notificationsEnabled.value = false
        try {
          ;(uni as any).setStorageSync('notificationsEnabled', false)
        } catch (e) {}
        // 根据错误类型显示不同的提示信息
        if (err.errCode === 20004) {
          uni.showToast({ title: '推送权限已关闭', icon: 'none' })
        } else {
          uni.showToast({ title: '订阅请求失败', icon: 'none' })
        }
      }
    })
  } else {
    // 关闭订阅：不需要额外调用接口，只改变本地记录
    console.log('通知开关已关闭')
    notificationsEnabled.value = false
    try {
      ;(uni as any).setStorageSync('notificationsEnabled', false)
    } catch (err) {}
    uni.showToast({ title: '已关闭通知', icon: 'none' })
  }
}

const toggleReminder = (index: number) => {
  reminders.value[index].enabled = !reminders.value[index].enabled
}
</script>

<style scoped>
.content {
  padding: calc(var(--status-bar-height) + 44px) 50rpx 50rpx 50rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.reminder-list {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  margin-top: 50rpx;
}

.reminder-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.reminder-item:last-child {
  border-bottom: none;
}

.reminder-info {
  flex: 1;
}

.reminder-title {
  font-size: 32rpx;
  color: #000000;
  display: block;
  margin-bottom: 10rpx;
}

.reminder-time {
  font-size: 28rpx;
  color: #5a5a5a;
}

.notification-toggle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-top: 20rpx;
}
.notification-label {
  font-size: 32rpx;
  color: #000;
}
.template-info {
  margin-top: 12rpx;
  padding: 0 10rpx;
  color: #666;
  font-size: 24rpx;
}
.tmpl-title {
  display: block;
  font-size: 26rpx;
  color: #333;
}
.tmpl-meta {
  display: block;
  font-size: 22rpx;
  color: #8a8a8a;
  margin-top: 6rpx;
}
</style>