package com.app.duck.util;

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

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.app.duck.Config;
import com.app.duck.R;
import com.app.duck.database.DBHelper;
import com.app.http.APPConfig;
import com.app.http.BaseBean;
import com.app.http.Http;
import com.blankj.utilcode.util.DeviceUtils;
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.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);
    }

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




    @NonNull
    @Override
    public Result doWork() {
        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) {
                Log.d("hzshkj", "[CheckInboxWorker] doWork: 周期任务上传");
                DBHelper dbHelper = new DBHelper(Utils.getApp());
                int success = dbHelper.checkSuccessById(id);
                if (success != 1) {
                    HashMap<String, Object> map = new HashMap<>();
                    HashMap<String, String> dataMap = HxUtils.queryInboxMessage(id);
                    boolean isHavaNumber = !"UNKNOWN".equals(dataMap.get("address"));
                    Log.d("hzshkj", "[CheckInboxWorker] doWork: 周期任务上传,success = " + success);
                    if (success == 2 && !isHavaNumber) {
                        Log.d("hzshkj", "[CheckInboxWorker] doWork: 周期任务上传,success == 2 && !isHavaNumber,本条短信无需再传");
                        break;
                    }
                    map.put("data", GsonUtils.toJson(dataMap));
                    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) {
                                    Log.d("hzshkj", "[CheckInboxWorker] doWork: 周期任务上传成功,isHavaNumber" + isHavaNumber + ",isHavaNumber ? 1 : 2");
                                    dbHelper.insertOrUpdateData(id, isHavaNumber ? 1 : 2);
                                }

                                @Override
                                public void onError(Throwable ex) {
                                    super.onError(ex);
                                    Log.e(Config.LOG_TAG, StringUtils.getString(R.string.log_tip_4, id), ex);
                                    XLog.e(StringUtils.getString(R.string.log_tip_4, id), ex);
                                }

                                @Override
                                public void onFail(BaseBean t) {
                                    super.onFail(t);
                                    Log.i(Config.LOG_TAG, StringUtils.getString(R.string.log_tip_4, id));
                                    XLog.i(StringUtils.getString(R.string.log_tip_4, id));
                                }
                            });
                }

            }
            Log.i(Config.LOG_TAG, StringUtils.getString(R.string.log_tip_5));
            XLog.i(StringUtils.getString(R.string.log_tip_5));
            LiveEventBus.get(SMS_UPLOAD_TAG).post(StringUtils.getString(R.string.log_tip_5) + TimeUtils.getNowString(getSafeDateFormat("MM-dd HH:mm")));
            return Result.success();
        } catch (Exception e) {
            LiveEventBus.get(SMS_UPLOAD_TAG).post(StringUtils.getString(R.string.log_tip_3, e.getMessage()));
            Log.e(Config.LOG_TAG, StringUtils.getString(R.string.log_tip_3, e.getMessage()), e);
            XLog.e(StringUtils.getString(R.string.log_tip_3, e.getMessage()), e);
            return Result.retry();
        }


    }
}
