package com.swiftcleaner.chovey.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.content.Intent;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.EventUtils;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.databinding.ActivityCleanJunkBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.tool.FileHelps;
import com.swiftcleaner.chovey.model.tool.MediaHelps;
import com.swiftcleaner.chovey.model.util.AppSchedulers;
import com.swiftcleaner.chovey.model.util.FinishMain;
import com.swiftcleaner.chovey.view.BaseActivity;
import com.swiftcleaner.chovey.view.BaseActivityKotlin;
import com.swiftcleaner.chovey.view.MainActivity;
import com.swiftcleaner.chovey.view.adapter.ApkCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.EmptyCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.LogsCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.TempCleanAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.swiftcleaner.chovey.view.dialog.LoadingDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

public class CleanJunkActivity extends BaseActivity<ActivityCleanJunkBinding> {
    private static final int REQUEST_READ_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 101;
    List<CleanFileBean> apkFileInfoList;
    List<CleanFileBean> tempFileInfoList;
    List<CleanFileBean> logsFileInfoList;
    ApkCleanAdapter apkCleanAdapter;
    TempCleanAdapter tempCleanAdapter;
    LogsCleanAdapter logsCleanAdapter;
    EmptyCleanAdapter emptyCleanAdapter;
    public long totalSelectedSize = 0;
    private long selectedSize = 0;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ValueAnimator animator;
    private CountDownTimer countDownTimer;
    private SharedPreferences sharedPreferences;
    @Override
    protected ActivityCleanJunkBinding getViewBinding() {
        return ActivityCleanJunkBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initBar();
    }

    @Override
    protected void initData() {
        EventUtils.INSTANCE.event("page_CleanJunkActivity", "", null);
        initPage();
    }

    private void initPage() {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.flAdDonghua.setVisibility(View.VISIBLE);
        AdmobManager.INSTANCE.showNativeAd(CleanJunkActivity.this, (nativeAd) -> {
            binding.flAdDonghua.removeAllViews();
            binding.flAdDonghua.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
        binding.radarview.setSearching(true);
        initAnimotor();
        countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                binding.radarview.setSearching(false);
                countDownTimer.cancel();
                animator.cancel();
                binding.clRadarview.setVisibility(View.GONE);

                LoadingDialog loadingDialog = new LoadingDialog(CleanJunkActivity.this);
                loadingDialog.show();
                if (AdmobManager.INSTANCE.isShowAdInter()) {
                    AdmobManager.INSTANCE.showInterstitialAd(CleanJunkActivity.this, () -> {
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();

                                return null;
                            }, false);
                } else {
                    checkAndRequestPermissions();
                    loadingDialog.dismiss();
                    binding.flAdDonghua.setVisibility(View.GONE);
                }

            }
        }.start();
        AdmobManager.INSTANCE.showNativeAd(CleanJunkActivity.this, (nativeAd) -> {
            binding.flAd.removeAllViews();
            binding.flAd.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
    }

    private void checkAndRequestPermissions() {
        if (!checkFilesAccessPermission(this)) {
            // 没有权限，请求权限
            requestFilesAccessPermission();
        } else {
            //加载布局
            initDateClean();
        }
    }


    private boolean checkFilesAccessPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else {
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Unable to request permission, please grant manually", Toast.LENGTH_SHORT).show();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }

    private void initDateClean() {

        binding.emptyFilesRecy.setVisibility(View.VISIBLE);
        binding.apkFilesRecy.setVisibility(View.VISIBLE);
        binding.tempFilesRecy.setVisibility(View.VISIBLE);
        binding.logsFilesRecy.setVisibility(View.VISIBLE);
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.apkFilesAllCl.setOnClickListener(v -> {
            if (binding.apkFilesRecy.getVisibility() == View.VISIBLE) {
                binding.apkFilesRecy.setVisibility(View.GONE);
            } else {
                binding.apkFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.tempFilesAllCl.setOnClickListener(v -> {
            if (binding.tempFilesRecy.getVisibility() == View.VISIBLE) {
                binding.tempFilesRecy.setVisibility(View.GONE);
            } else {
                binding.tempFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.logsFilesAllCl.setOnClickListener(v -> {
            if (binding.logsFilesRecy.getVisibility() == View.VISIBLE) {
                binding.logsFilesRecy.setVisibility(View.GONE);
            } else {
                binding.logsFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.emptyFilesAllCl.setOnClickListener(v -> {
            if (binding.emptyFilesRecy.getVisibility() == View.VISIBLE) {
                binding.emptyFilesRecy.setVisibility(View.GONE);
            } else {
                binding.emptyFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        binding.buttonCleanUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view != null) {
                    boolean cleaned = sharedPreferences.getBoolean("cleaned", false);
                    if (!cleaned){
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putBoolean("cleaned", true);
                        editor.commit();
                    }
                    onClickCleanUpButton(view);
                }
            }
        });
        initQueryApkFiles();
        initQueryTempFiles();
        initQueryLogsFiles();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                initQueryEmptyFiles();
            }
        } else {
            initQueryEmptyFiles();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // 权限未授予，提示用户
                    Toast.makeText(this, "Permission not granted, please grant manually", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initQueryEmptyFiles();
            }
        }
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续操作
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void initQueryEmptyFiles() {
        Disposable disposable = Observable.fromCallable(() -> {
                    List<CleanFileBean> emptyFolders = FileHelps.findEmptyFolders();
                    if (emptyFolders != null) {
                        for (CleanFileBean file : emptyFolders) {
                            file.setSelected(true); // 设置为选中状态
                            totalSelectedSize += file.getLength();
                            selectedSize += file.getLength(); // 更新 selectedSize
                        }
                    }
                    return emptyFolders;
                }).subscribeOn(AppSchedulers.io())
                .observeOn(AppSchedulers.mainThread())
                .subscribe(emptyFolders -> {
                    emptyCleanAdapter = new EmptyCleanAdapter(emptyFolders, new EmptyCleanAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(CleanFileBean fileBean) {
                            if (fileBean.isSelected()) {
                                selectedSize += fileBean.getLength();
                                updateButtonStatus();
                            } else {
                                selectedSize -= fileBean.getLength();
                                updateButtonStatus();
                            }

                        }
                    });
                    binding.emptyFilesRecy.setAdapter(emptyCleanAdapter);
                    binding.emptyFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                    binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    private void initQueryApkFiles() {
        apkFileInfoList = new ArrayList<>();

        Disposable disposable = Observable.fromCallable(() -> {
                    List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
                    if (specifiedFiles != null) {
                        for (CleanFileBean file : specifiedFiles) {
                            if ((file.getMineType() != null && (file.getMineType().endsWith(".apk") || file.getMineType().endsWith(".APK"))) ||
                                    (file.getName() != null && file.getName().toLowerCase().endsWith(".apk"))) {
                                file.setSelected(true); // 设置为选中状态
                                apkFileInfoList.add(file);
                                totalSelectedSize += file.getLength();
                                selectedSize += file.getLength(); // 更新 selectedSize
                            }
                        }
                    }
                    return specifiedFiles;
                }).subscribeOn(AppSchedulers.io())
                .observeOn(AppSchedulers.mainThread())
                .subscribe(emptyFolders -> {
                    apkCleanAdapter = new ApkCleanAdapter(apkFileInfoList, new ApkCleanAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(CleanFileBean fileBean) {
                            if (fileBean.isSelected()) {
                                selectedSize += fileBean.getLength();
                                updateButtonStatus();
                            } else {
                                selectedSize -= fileBean.getLength();
                                updateButtonStatus();
                            }
                        }
                    });
                    binding.apkFilesRecy.setAdapter(apkCleanAdapter);
                    binding.apkFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                    binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    private void initQueryTempFiles() {
        tempFileInfoList = new ArrayList<>();
        Disposable disposable = Observable.fromCallable(() -> {
                    List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
                    if (specifiedFiles != null) {
                        for (CleanFileBean file : specifiedFiles) {
                            if ((file.getMineType() != null && (file.getMineType().endsWith(".temp") || file.getMineType().endsWith(".TEMP"))) ||
                                    (file.getName() != null && file.getName().toLowerCase().endsWith(".temp"))) {
                                file.setSelected(true); // 设置为选中状态
                                tempFileInfoList.add(file);
                                totalSelectedSize += file.getLength();
                                selectedSize += file.getLength(); // 更新 selectedSize
                            }
                        }
                    }
                    return specifiedFiles;
                }).subscribeOn(AppSchedulers.io())
                .observeOn(AppSchedulers.mainThread())
                .subscribe(emptyFolders -> {
                    tempCleanAdapter = new TempCleanAdapter(tempFileInfoList, new TempCleanAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(CleanFileBean fileBean) {
                            if (fileBean.isSelected()) {
                                selectedSize += fileBean.getLength();
                                updateButtonStatus();
                            } else {
                                selectedSize -= fileBean.getLength();
                                updateButtonStatus();
                            }
                        }
                    });
                    binding.tempFilesRecy.setAdapter(tempCleanAdapter);
                    binding.tempFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                    binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    private void initQueryLogsFiles() {
        logsFileInfoList = new ArrayList<>();
        Disposable disposable = Observable.fromCallable(() -> {
                    List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
                    if (specifiedFiles != null) {
                        for (CleanFileBean file : specifiedFiles) {
                            if ((file.getMineType() != null && (file.getMineType().endsWith(".log") || file.getMineType().endsWith(".LOG"))) ||
                                    (file.getName() != null && file.getName().toLowerCase().endsWith(".log"))) {
                                file.setSelected(true); // 设置为选中状态
                                logsFileInfoList.add(file);
                                totalSelectedSize += file.getLength();
                                selectedSize += file.getLength(); // 更新 selectedSize
                            }
                        }
                    }
                    return specifiedFiles;
                }).subscribeOn(AppSchedulers.io())
                .observeOn(AppSchedulers.mainThread())
                .subscribe(emptyFolders -> {
                    logsCleanAdapter = new LogsCleanAdapter(logsFileInfoList, new LogsCleanAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(CleanFileBean fileBean) {
                            if (fileBean.isSelected()) {
                                selectedSize += fileBean.getLength();
                                updateButtonStatus();
                            } else {
                                selectedSize -= fileBean.getLength();
                                updateButtonStatus();
                            }
                        }
                    });
                    binding.logsFilesRecy.setAdapter(logsCleanAdapter);
                    binding.logsFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                    binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    private void updateButtonStatus() {
        binding.buttonCleanUp.setText("Clean Up " + formatFileSize(selectedSize));
    }

    //apk 删除
    public void apkCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);

                    // 更新 UI
                    apkCleanAdapter.removeSelectedFiles(selectedFiles);
                    apkCleanAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    //temp 删除
    public void tempCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    tempCleanAdapter.removeSelectedFiles(selectedFiles);
                    tempCleanAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    //logs 删除
    public void logsCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    logsCleanAdapter.removeSelectedFiles(selectedFiles);
                    logsCleanAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    //empty 删除
    public void emptyCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    emptyCleanAdapter.removeSelectedFiles(selectedFiles);
                    emptyCleanAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    public void onClickCleanUpButton(View view) {
        List<CleanFileBean> apkSelectedFiles;
        List<CleanFileBean> tempSelectedFiles;
        List<CleanFileBean> logsSelectedFiles;
        List<CleanFileBean> emptySelectedFiles;
        if (emptyCleanAdapter != null) {
            emptySelectedFiles = emptyCleanAdapter.getSelectedFiles();
            emptyCleanFiles(emptySelectedFiles);
        }
        if (apkCleanAdapter != null) {
            apkSelectedFiles = apkCleanAdapter.getSelectedFiles();
            apkCleanFiles(apkSelectedFiles);
        }
        if (tempCleanAdapter != null) {
            tempSelectedFiles = tempCleanAdapter.getSelectedFiles();
            tempCleanFiles(tempSelectedFiles);
        }
        if (logsCleanAdapter != null) {
            logsSelectedFiles = logsCleanAdapter.getSelectedFiles();
            logsCleanFiles(logsSelectedFiles);
        }

//        selectedSize = 0;
        updateButtonStatus();
        //跳转页面
        initAnimation(formatFileSize(selectedSize));
    }


    private String formatFileSize(long size) {
        if (size <= 0) return "0 Bytes";
        final String[] units = new String[]{"Bytes", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    //进入功能动画
    private void initAnimotor() {
        // 创建ValueAnimator，从1到100
        animator = ValueAnimator.ofInt(1, 100);
        animator.setDuration(5000); // 3秒

        // 设置更新监听器，每帧更新进度文本
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (int) animation.getAnimatedValue();
                binding.parText.setText(currentValue + "%");
            }
        });
        // 开始动画
        animator.start();
    }

    private void initAnimation(String str) {
        Intent intent = new Intent(this, EndCleanJunkActivity.class);
        intent.putExtra("cleanstr", str);
        startActivity(intent);
        finish();
    }

    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(false)  // 状态栏字体颜色为深色
                .navigationBarDarkIcon(true)  // 导航栏图标颜色为浅色
                .init();
    }

    @Override
    public void onBackPressed() {
        initCustDialog();
    }

    private void initCustDialog() {
        Activity activity = this;
        CustomScoreDialog customScoreDialog = new CustomScoreDialog(this);
        customScoreDialog.setOnDialogClickListener(new CustomScoreDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                customScoreDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                if (AdmobManager.INSTANCE.isShowAdBackInter()) {
                    AdmobManager.INSTANCE.showInterstitialAd(CleanJunkActivity.this, () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                return null;
                            },
                            () -> {
                                return null;
                            },
                            () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                return null;
                            }, false);
                } else {
                    FinishMain.INSTANCE.finishToMain(activity);
                }

            }
        });
        customScoreDialog.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (animator != null) {
            animator.cancel();
        }
        compositeDisposable.clear();

        if (sharedPreferences != null) {
            sharedPreferences = null;
        }
        if (binding != null) {
            binding = null;
        }
    }
}