<template>
  <div class="push-test">
    <van-nav-bar
      title="推送测试"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
    
    <div class="content">
      <van-cell-group title="推送状态">
        <van-cell title="推送支持" :value="pushSupported ? '支持' : '不支持'" />
        <van-cell title="推送启用" :value="pushEnabled ? '已启用' : '未启用'" />
        <van-cell title="客户端ID" :value="clientId || '未获取'" />
        <van-cell title="force_notification模式" :value="forceNotificationMode ? '已启用' : '已禁用'" />
      </van-cell-group>
      
      <van-cell-group title="推送操作" style="margin-top: 20px;">
        <van-cell title="请求推送权限" is-link @click="requestPermission" />
        <van-cell title="检查推送权限" is-link @click="checkPermission" />
        <van-cell title="设置推送标签" is-link @click="showTagDialog = true" />
        <van-cell title="发送测试推送" is-link @click="sendTestPush" />
        <van-cell 
          :title="forceNotificationMode ? '禁用force_notification模式' : '启用force_notification模式'" 
          is-link 
          @click="toggleForceNotificationMode" 
        />
      </van-cell-group>
      
      <van-cell-group title="推送历史" style="margin-top: 20px;">
        <van-cell 
          v-for="(message, index) in pushHistory" 
          :key="index"
          :title="message.title"
          :value="message.time"
          @click="viewMessageDetail(message)"
        />
      </van-cell-group>
    </div>
    
    <!-- 标签设置对话框 -->
    <van-dialog 
      v-model:show="showTagDialog" 
      title="设置推送标签"
      show-cancel-button
      @confirm="setTags"
    >
      <div class="tag-dialog">
        <van-field
          v-model="tagInput"
          label="标签"
          placeholder="请输入标签，多个标签用逗号分隔"
        />
        <div class="current-tags">
          <span>当前标签：</span>
          <van-tag 
            v-for="(tag, index) in currentTags" 
            :key="index"
            type="primary"
            style="margin-right: 5px;"
          >
            {{ tag }}
          </van-tag>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import pushInstance from '@/utils/push'
import pushService from '@/service/push'
import { Toast } from 'vant'

export default {
  name: 'PushTest',
  data() {
    return {
      pushSupported: false,
      pushEnabled: false,
      clientId: null,
      forceNotificationMode: false,
      showTagDialog: false,
      tagInput: '',
      currentTags: [],
      pushHistory: [
        { title: '测试推送消息1', time: '2024-01-01 10:00', content: '这是一条测试推送消息' },
        { title: '测试推送消息2', time: '2024-01-01 09:00', content: '这是另一条测试推送消息' }
      ]
    }
  },
  async mounted() {
    await this.initPushInfo()
  },
  methods: {
      async initPushInfo() {
        this.pushSupported = await pushInstance.checkPermission()
        this.pushEnabled = pushInstance.pushEnabled
        this.forceNotificationMode = pushInstance.forceNotificationMode || false
        
        if (pushInstance.clientId) {
          this.clientId = pushInstance.clientId
        }
        
        // 获取当前标签
        try {
          this.currentTags = await pushInstance.getTags() || []
        } catch (error) {
          console.error('获取标签失败:', error)
        }
      },
     
      async requestPermission() {
      try {
        await pushInstance.requestPermission()
        Toast.success('推送权限请求成功')
        await this.initPushInfo()
      } catch (error) {
        Toast.fail('推送权限请求失败')
        console.error('请求推送权限失败:', error)
      }
    },
    
    async checkPermission() {
      const hasPermission = await pushInstance.checkPermission()
      Toast(hasPermission ? '已开启推送权限' : '未开启推送权限')
    },
    
    async setTags() {
      if (!this.tagInput.trim()) {
        Toast.fail('请输入标签')
        return
      }
      
      const tags = this.tagInput.split(',').map(tag => tag.trim()).filter(tag => tag)
      
      try {
        await pushInstance.setTags(tags)
        Toast.success('标签设置成功')
        this.currentTags = tags
        this.tagInput = ''
        this.showTagDialog = false
      } catch (error) {
        Toast.fail('标签设置失败')
        console.error('设置标签失败:', error)
      }
    },
    
    async sendTestPush() {
      if (!this.clientId) {
        Toast.fail('请先获取客户端ID')
        return
      }
      
      try {
        const result = await pushService.sendTestPush(this.clientId, {
          title: '测试推送',
          content: '这是一条测试推送消息',
          payload: {
            page: 'message',
            type: 'test'
          }
        })
        
        Toast.success('测试推送发送成功')
        console.log('推送结果:', result)
      } catch (error) {
        Toast.fail('测试推送发送失败')
        console.error('发送测试推送失败:', error)
      }
    },
    
    viewMessageDetail(message) {
      this.$dialog.alert({
        title: message.title,
        message: message.content
      })
    },
    
    // 切换 force_notification 模式
    toggleForceNotificationMode() {
      this.forceNotificationMode = !this.forceNotificationMode
      pushInstance.setForceNotificationMode(this.forceNotificationMode)
      
      Toast.success(`force_notification 模式 ${this.forceNotificationMode ? '已启用' : '已禁用'}`)
      
      // 显示模式说明
      if (this.forceNotificationMode) {
        this.$dialog.alert({
          title: 'force_notification 模式已启用',
          message: '在此模式下：\n• 应用在线时推送会直接显示通知栏\n• 应用在线时不会触发消息接收监听器\n• 用户点击通知后才会触发消息处理'
        })
      }
    }
  }
}
</script>

<style scoped>
.push-test {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 16px;
}

.tag-dialog {
  padding: 16px;
}

.current-tags {
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}
</style>