package com.file.clean.q.view;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import com.file.clean.q.business.admob.AdmobManager;
import com.file.clean.q.view.activity.SimilarPhotosActivity;
import com.gyf.immersionbar.ImmersionBar;

import com.file.clean.q.model.tool.MemoryUtils;
import com.file.clean.q.view.activity.AppProcessActivity;
import com.file.clean.q.view.activity.BatteryInfoActivity;
import com.file.clean.q.view.activity.CleanJunkActivity;
import com.file.clean.q.view.activity.InfoActivity;
import com.file.clean.q.view.activity.LargeFileActivity;
import com.file.clean.q.view.activity.ScreenShotActivity;
import com.file.clean.q.view.activity.SettingActivity;

import com.file.clean.q.view.activity.WhatsAppActivity;
import com.file.clean.q.view.dialog.AppExitDialog;
import com.file.clean.q.view.dialog.NoticeDialog;
import com.file.clean.q.R;
import com.file.clean.q.databinding.ActivityMainBinding;

import java.util.concurrent.atomic.AtomicBoolean;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private ObjectAnimator rotateAnimator;
    private ActivityResultLauncher<String[]> multiplePermissionsLauncher;
    private ActivityResultLauncher<Intent> notificationSettingsLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initPermission();
        initShow();
    }

    private void initShow() {
        //判断是否有权限
//        NotificationUtils.INSTANCE.sendNotification(CleanApplication.context, GlobalConfig.ID_CLEAN_JUNK, "app_receiver");
        //动画
        initAnimate();
        new Thread(){
            @Override
            public void run() {
                super.run();
                // 获取总内存
                String totalMemory = MemoryUtils.getUsedDiskMemory(MainActivity.this);
                // 获取当前使用内存
                String usedMemory = MemoryUtils.getTotalDiskMemory(MainActivity.this);
                String usedDiskMemoryPercent = MemoryUtils.getUsedDiskMemoryPercent(MainActivity.this);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //内存赋值
                        binding.phoneMemory.setText(totalMemory + "/" + usedMemory);
                        binding.tvBaifenbi.setText(usedDiskMemoryPercent);
                        binding.progressBar.setProgress(Integer.parseInt(usedDiskMemoryPercent));
                    }
                });
            }
        }.start();
        binding.cleanUp.setOnClickListener(v -> {
            intTempJump();
        });
        binding.ivSetting.setOnClickListener(v -> {
            initSetting();
        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            intTempJump();
        });
        binding.cl3AppManager.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, BatteryInfoActivity.class));
        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, InfoActivity.class));
        });
        binding.appProcess.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, AppProcessActivity.class));
        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, LargeFileActivity.class));
        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, ScreenShotActivity.class));
        });
        binding.whatsApp.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, WhatsAppActivity.class));
        });
        binding.similarPhotos.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, SimilarPhotosActivity.class));
        });
    }
    private void openNotificationSettings() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 对于 Android 8.0 及以上版本
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 对于 Android 5.0 到 7.1 版本
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 对于 Android 5.0 以下版本，跳转到应用详情页
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
        }
        startActivity(intent);
    }
    private void initAnimate() {
        rotateAnimator = ObjectAnimator.ofFloat(binding.animateYuan, "rotation", 360f, 0f);
        rotateAnimator.setDuration(5000);

        rotateAnimator.setRepeatMode(ObjectAnimator.RESTART);
        rotateAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        rotateAnimator.start();


        int width = getResources().getDimensionPixelSize(R.dimen.main_progress_bar_width); // 宽度
        int height = getResources().getDimensionPixelSize(R.dimen.main_progress_bar_height);
        binding.progressBar.getLayoutParams().width = width;
        binding.progressBar.getLayoutParams().height = height;
        binding.progressBar.requestLayout();
    }

    private void initPermission() {
        multiplePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    if (result.get(Manifest.permission.POST_NOTIFICATIONS) != null && result.get(Manifest.permission.POST_NOTIFICATIONS)) {

                    }
                }
        );


        notificationSettingsLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 处理结果
                }
        );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                NoticeDialog noticeDialog = new NoticeDialog(this);
                noticeDialog.setOnDialogClickListener(new NoticeDialog.OnDialogClickListener() {
                    @Override
                    public void onCancel() {
                        noticeDialog.cancel();
                    }

                    @Override
                    public void onSubmit() {
                        // 请求通知权限
//                        PermissionUtils.requestNotificationPermission(MainActivity.this, notificationSettingsLauncher, multiplePermissionsLauncher);
//                        noticeDialog.cancel();
                        openNotificationSettings();
                    }
                });
                noticeDialog.show();
            }

        }



    }
    private void intTempJump() {
        Intent intent = new Intent(this, CleanJunkActivity.class);
        startActivity(intent);
    }

    private void initSetting() {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }

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

    @Override
    public void onBackPressed() {
        AppExitDialog appExitDialog = new AppExitDialog(this);
        appExitDialog.setOnDialogClickListener(new AppExitDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                finishAffinity();
                System.exit(0); // 完全退出应用
            }

            @Override
            public void onSubmit() {
                appExitDialog.dismiss();
            }
        });
        appExitDialog.show();
    }

    private AtomicBoolean bannerShowed = new AtomicBoolean(false);

    @Override
    protected void onResume() {
        super.onResume();
        if (!rotateAnimator.isRunning()) {
            rotateAnimator.start();
        }
        if (bannerShowed.get()) return;
        bannerShowed.set(true);
        AdmobManager.INSTANCE.showBannerAd(this, binding.flBanner, "bottom", null, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (rotateAnimator.isRunning()) {
            rotateAnimator.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rotateAnimator != null) {
            rotateAnimator.end();
            rotateAnimator = null;
        }
    }
}