package com.cooleshow.student.helper;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Author by pq, Date on 2022/5/27.
 */
public class PushIntentParseHelper {

    public static final String RONG_PUSH_SCHEME = "rong";//融云推送scheme
    public static final String RONG_PUSH_ACTION_TAG = "rongIM";//融云推送action


    /**
     * 处理点击事件，当前启动配置的Activity都是使用
     * Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
     * 方式启动，只需要在onCreat中调用此方法进行处理
     */

    /**
     * 通知附加字段
     **/
    private static final String KEY_EXTRAS = "n_extras";

    private static String parsePushIntent(Intent intent) {
        String data = null;

        //获取华为平台附带的jpush信息
        if (intent.getData() != null) {
            data = intent.getData().toString();
        }
        //获取fcm/oppo/小米/vivo/魅族 平台附带的jpush信息
        if (TextUtils.isEmpty(data) && intent.getExtras() != null) {
            data = intent.getExtras().getString("JMessageExtra");
        }
        Log.i("pq", "msg content is " + String.valueOf(data));
        return data;
    }

    private static String getMemoFromPushIntent(String intent) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(intent);
            JSONObject n_extras = (JSONObject) jsonObject.opt(KEY_EXTRAS);
            if (n_extras != null) {
                return n_extras.optString("memo");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String getIntentMemoFrom(Intent intent) {
        String memo = "";
        Uri data = intent.getData();
        if (data != null && data.isHierarchical()) {
            //判断是否是融云推送
            if (TextUtils.equals(RONG_PUSH_SCHEME, data.getScheme())) {
                memo = RONG_PUSH_ACTION_TAG;
            }
        }
        if (TextUtils.isEmpty(memo)) {
            //判断是否是极光推送
            String result = parsePushIntent(intent);
            if (!TextUtils.isEmpty(result)) {
                memo = getMemoFromPushIntent(result);
            }
        }

        if (TextUtils.isEmpty(memo)) {
            memo = intent.getStringExtra("memo");
        }
        return memo;
    }
}
