#!/bin/bash

# OPPO推送 - 通讯与服务类消息测试脚本
# 此脚本使用 HTTP API 直接发送通讯与服务类消息，实现强提醒功能

if [ -z "$1" ]; then
    echo "使用方法: $0 <device_token>"
    echo "device_token: OPPO设备的registration_id"
    echo ""
    echo "示例: $0 OPPO_CN_95ac9afc103d70bb26441ec0cbb06b97"
    exit 1
fi

DEVICE_TOKEN=$1

# OPPO推送配置
APP_KEY="bb0819c889ae40cd8bde5a8ad4e670fe"
APP_SERVER_SECRET="2d8b4e922d60453d987f0d09de6eb4a6"
API_URL="https://api.push.oppomobile.com"

echo "=========================================="
echo "OPPO推送 - 通讯与服务类消息测试"
echo "=========================================="
echo "设备Token: $DEVICE_TOKEN"
echo ""

# 1. 获取 auth_token
echo "步骤1: 获取 auth_token..."
TIMESTAMP=$(date +%s)000

# 生成签名: SHA256(app_key + timestamp + master_secret)
SIGN_STRING="${APP_KEY}${TIMESTAMP}${APP_SERVER_SECRET}"
SIGN=$(echo -n "$SIGN_STRING" | sha256sum | awk '{print $1}')

echo "Timestamp: $TIMESTAMP"
echo "Sign: $SIGN"
echo ""

# 获取 token
AUTH_RESPONSE=$(curl -s -X POST "${API_URL}/server/v1/auth" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "app_key=${APP_KEY}&timestamp=${TIMESTAMP}&sign=${SIGN}")

echo "Auth响应: $AUTH_RESPONSE"
echo ""

# 解析 token
AUTH_TOKEN=$(echo "$AUTH_RESPONSE" | grep -o '"auth_token":"[^"]*' | cut -d'"' -f4)

if [ -z "$AUTH_TOKEN" ]; then
    echo "错误: 无法获取 auth_token"
    echo "响应: $AUTH_RESPONSE"
    exit 1
fi

echo "✓ 获取 auth_token 成功: ${AUTH_TOKEN:0:20}..."
echo ""

# 2. 发送通讯与服务类消息
echo "步骤2: 发送通讯与服务类消息..."
echo ""

# 构建消息体（包含通讯与服务类消息参数）
MESSAGE_JSON=$(cat <<EOF
{
  "target_type": 1,
  "target_value": "$DEVICE_TOKEN",
  "notification": {
    "title": "知你",
    "content": "我是api",
    "channel_id": "previte_message",
    "channel_name": "消息推送",
    "category": "IM",
    "notify_level": 2,
    "offLine": true,
    "offLineTtl": 86400,
    "showTimeType": 0,
    "networkType": 0,
    "style": 1,
    "clickActionType": 0
  }
}
EOF
)

echo "消息体:"
echo "$MESSAGE_JSON" | python -m json.tool 2>/dev/null || echo "$MESSAGE_JSON"
echo ""

# 发送推送
PUSH_RESPONSE=$(curl -s -X POST "${API_URL}/server/v1/message/notification/unicast" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "message=$(echo "$MESSAGE_JSON" | python -c "import sys, json, urllib.parse; print(urllib.parse.quote(json.dumps(json.load(sys.stdin))))" 2>/dev/null || echo "$MESSAGE_JSON")&auth_token=${AUTH_TOKEN}")

echo "推送响应:"
echo "$PUSH_RESPONSE" | python -m json.tool 2>/dev/null || echo "$PUSH_RESPONSE"
echo ""

# 检查结果
if echo "$PUSH_RESPONSE" | grep -q '"code":0'; then
    echo "✓ 推送成功！"
    echo ""
    echo "请检查OPPO手机："
    echo "1. 灭屏状态下应该有声音和振动提醒"
    echo "2. 锁屏界面应该显示通知"
    echo "3. 通知栏应该显示消息"
    echo "4. 消息应该被分类为'通讯与服务'类型"
else
    echo "✗ 推送失败"
    echo "响应: $PUSH_RESPONSE"
fi

echo ""
echo "=========================================="

