package cc.winboll.studio.contacts.activities;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.adapters.PhoneConnectRuleAdapter;
import cc.winboll.studio.contacts.bobulltoon.TomCat;
import cc.winboll.studio.contacts.dun.Rules;
import cc.winboll.studio.contacts.model.MainServiceBean;
import cc.winboll.studio.contacts.model.PhoneConnectRuleBean;
import cc.winboll.studio.contacts.model.RingTongBean;
import cc.winboll.studio.contacts.model.SettingsBean;
import cc.winboll.studio.contacts.services.MainService;
import cc.winboll.studio.contacts.views.DuInfoTextView;
import cc.winboll.studio.libaes.interfaces.IWinBoLLActivity;
import cc.winboll.studio.libaes.utils.WinBoLLActivityManager;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/02/21 05:37:42
 * @Describe Contacts 设置页面（完全适配 API 30 + Java 7 语法）
 * 核心优化：1. 移除高版本API依赖 2. Java7规范写法 3. 强化内存泄漏防护 4. 版本判断硬编码
 */
public class SettingsActivity extends WinBollActivity implements IWinBoLLActivity {

    // ====================== 常量定义区 ======================
    public static final String TAG = "SettingsActivity";
    // API版本硬编码常量（替代Build.VERSION_CODES，适配API30）
    private static final int ANDROID_6_API = 23;

    // ====================== 静态控件区 ======================
    static DuInfoTextView _DuInfoTextView;

    // ====================== UI控件区 ======================
    private Toolbar mToolbar;
    private Switch swSilent;
    private SeekBar msbVolume;
    private TextView mtvVolume;
    private Switch mswMainService;
    private EditText etDunTotalCount;
    private EditText etDunResumeSecondCount;
    private EditText etDunResumeCount;
    private Switch swIsEnableDun;
    private RecyclerView recyclerView;
    private EditText etBoBullToonURL;
    private EditText etPhone;

    // ====================== 数据与业务参数区 ======================
    private int mnStreamMaxVolume;
    private int mnStreamVolume;
    private PhoneConnectRuleAdapter adapter;
    private List<PhoneConnectRuleBean> ruleList;

    // ====================== 接口实现区 ======================
    @Override
    public AppCompatActivity getActivity() {
        return this;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    // ====================== 生命周期函数区 ======================
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG, "onCreate: 设置页面开始创建");
        setContentView(R.layout.activity_settings);

        // 初始化工具栏
        initToolbar();
        // 初始化主服务开关
        initMainServiceSwitch();
        // 初始化铃声音量调节
        initVolumeSeekBar();
        // 初始化规则列表
        initRuleRecyclerView();
        // 初始化云盾设置
        initDunSettings();
        // 初始化BoBullToon相关控件
        initBoBullToonViews();

        LogUtils.d(TAG, "onCreate: 设置页面初始化完成");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy: 设置页面开始销毁");
        // 清空静态引用 + 置空所有控件引用，彻底避免内存泄漏
        _DuInfoTextView = null;
        mToolbar = null;
        mswMainService = null;
        msbVolume = null;
        mtvVolume = null;
        recyclerView = null;
        adapter = null;
        ruleList = null;
        LogUtils.d(TAG, "onDestroy: 设置页面销毁完成");
    }

    // ====================== 控件初始化函数区 ======================
    private void initToolbar() {
        LogUtils.d(TAG, "initToolbar: 初始化工具栏");
        mToolbar = (Toolbar) findViewById(R.id.activitymainToolbar1);
        setSupportActionBar(mToolbar);
        // 显示后退按钮（添加空指针防护）
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setSubtitle(getTag());
        }
        // Java7 匿名内部类实现点击监听，禁止Lambda
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					LogUtils.d(TAG, "initToolbar: 点击导航栏返回按钮");
					finish();
				}
			});
    }

    private void initMainServiceSwitch() {
        LogUtils.d(TAG, "initMainServiceSwitch: 初始化主服务开关");
        mswMainService = (Switch) findViewById(R.id.sw_mainservice);
        MainServiceBean mMainServiceBean = MainServiceBean.loadBean(this, MainServiceBean.class);
        // 空指针防护：避免MainServiceBean为null导致崩溃
        if (mMainServiceBean != null) {
            mswMainService.setChecked(mMainServiceBean.isEnable());
        } else {
            mswMainService.setChecked(false);
            LogUtils.w(TAG, "initMainServiceSwitch: MainServiceBean为null，默认关闭开关");
        }

        mswMainService.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					LogUtils.d(TAG, "initMainServiceSwitch: 主服务开关状态变更，checked=" + mswMainService.isChecked());
					if (mswMainService.isChecked()) {
						MainService.startMainServiceAndSaveStatus(SettingsActivity.this);
					} else {
						MainService.stopMainServiceAndSaveStatus(SettingsActivity.this);
					}
				}
			});
    }

    private void initVolumeSeekBar() {
        LogUtils.d(TAG, "initVolumeSeekBar: 初始化音量调节条");
        msbVolume = (SeekBar) findViewById(R.id.bellvolume);
        mtvVolume = (TextView) findViewById(R.id.tv_volume);
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // 空指针防护：AudioManager可能为null
        if (audioManager == null) {
            LogUtils.e(TAG, "initVolumeSeekBar: AudioManager获取失败，跳过音量初始化");
            return;
        }

        // 设置SeekBar最大值和初始进度
        mnStreamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
        msbVolume.setMax(mnStreamMaxVolume);
        mnStreamVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
        msbVolume.setProgress(mnStreamVolume);
        updateStreamVolumeTextView();

        // 音量调节监听（Java7匿名内部类）
        msbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				@Override
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
					if (fromUser) {
						LogUtils.d(TAG, "initVolumeSeekBar: 音量调节至" + progress);
						audioManager.setStreamVolume(AudioManager.STREAM_RING, progress, 0);
						RingTongBean bean = RingTongBean.loadBean(SettingsActivity.this, RingTongBean.class);
						if (bean == null) {
							bean = new RingTongBean();
						}
						bean.setStreamVolume(progress);
						RingTongBean.saveBean(SettingsActivity.this, bean);
						mnStreamVolume = progress;
						updateStreamVolumeTextView();
					}
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {}
			});
    }

    private void initRuleRecyclerView() {
        LogUtils.d(TAG, "initRuleRecyclerView: 初始化规则列表");
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ruleList = Rules.getInstance(this).getPhoneBlacRuleBeanList();
        adapter = new PhoneConnectRuleAdapter(this, ruleList);
        recyclerView.setAdapter(adapter);
        LogUtils.d(TAG, "initRuleRecyclerView: 规则列表加载完成，共" + ruleList.size() + "条规则");
    }

    private void initDunSettings() {
        LogUtils.d(TAG, "initDunSettings: 初始化云盾设置");
        _DuInfoTextView = (DuInfoTextView) findViewById(R.id.tv_DunInfo);
        etDunTotalCount = (EditText) findViewById(R.id.et_DunTotalCount);
        etDunResumeSecondCount = (EditText) findViewById(R.id.et_DunResumeSecondCount);
        etDunResumeCount = (EditText) findViewById(R.id.et_DunResumeCount);
        swIsEnableDun = (Switch) findViewById(R.id.sw_IsEnableDun);

        SettingsBean settingsModel = Rules.getInstance(this).getSettingsModel();
        // 空指针防护：避免SettingsModel为null
        if (settingsModel != null) {
            etDunTotalCount.setText(Integer.toString(settingsModel.getDunTotalCount()));
            etDunResumeSecondCount.setText(Integer.toString(settingsModel.getDunResumeSecondCount()));
            etDunResumeCount.setText(Integer.toString(settingsModel.getDunResumeCount()));
            swIsEnableDun.setChecked(settingsModel.isEnableDun());

            boolean isEnableDun = settingsModel.isEnableDun();
            etDunTotalCount.setEnabled(!isEnableDun);
            etDunResumeSecondCount.setEnabled(!isEnableDun);
            etDunResumeCount.setEnabled(!isEnableDun);
        } else {
            LogUtils.e(TAG, "initDunSettings: SettingsModel为null，云盾设置初始化失败");
        }
    }

    private void initBoBullToonViews() {
        LogUtils.d(TAG, "initBoBullToonViews: 初始化BoBullToon相关控件");
        etBoBullToonURL = (EditText) findViewById(R.id.bobulltoonurl_et);
        etPhone = (EditText) findViewById(R.id.activitysettingsEditText1);
        // 空指针防护：避免Rules.getInstance返回null
        Rules rules = Rules.getInstance(this);
        if (rules != null) {
            etBoBullToonURL.setText(rules.getBoBullToonURL());
        }
    }

    // ====================== 工具函数区 ======================
    private void updateStreamVolumeTextView() {
        // Java7 字符串拼接，避免String.format可能的空指针
        mtvVolume.setText(mnStreamVolume + "/" + mnStreamMaxVolume);
    }

    // ====================== 静态通知函数区 ======================
    public static void notifyDunInfoUpdate() {
        if (_DuInfoTextView != null) {
            LogUtils.d(TAG, "notifyDunInfoUpdate: 更新云盾信息展示");
            _DuInfoTextView.notifyInfoUpdate();
        } else {
            LogUtils.w(TAG, "notifyDunInfoUpdate: 云盾信息控件为空，跳过更新");
        }
    }

    // ====================== 点击事件回调函数区 ======================
    public void onSW_IsEnableDun(View view) {
        LogUtils.d(TAG, "onSW_IsEnableDun: 云盾开关状态变更，checked=" + swIsEnableDun.isChecked());
        boolean isEnableDun = swIsEnableDun.isChecked();
        etDunTotalCount.setEnabled(!isEnableDun);
        etDunResumeSecondCount.setEnabled(!isEnableDun);
        etDunResumeCount.setEnabled(!isEnableDun);

        SettingsBean settingsModel = Rules.getInstance(this).getSettingsModel();
        // 空指针防护：SettingsModel为null时直接返回
        if (settingsModel == null) {
            LogUtils.e(TAG, "onSW_IsEnableDun: SettingsModel为null，操作失败");
            swIsEnableDun.setChecked(false);
            return;
        }

        if (isEnableDun) {
            try {
                String totalCountStr = etDunTotalCount.getText().toString().trim();
                String resumeSecondStr = etDunResumeSecondCount.getText().toString().trim();
                String resumeCountStr = etDunResumeCount.getText().toString().trim();
                // 空字符串校验
                if (totalCountStr.isEmpty() || resumeSecondStr.isEmpty() || resumeCountStr.isEmpty()) {
                    throw new NumberFormatException("参数不能为空");
                }
                int totalCount = Integer.parseInt(totalCountStr);
                int resumeSecond = Integer.parseInt(resumeSecondStr);
                int resumeCount = Integer.parseInt(resumeCountStr);
                settingsModel.setDunTotalCount(totalCount);
                settingsModel.setDunResumeSecondCount(resumeSecond);
                settingsModel.setDunResumeCount(resumeCount);
                // Java7 条件判断 + 字符串拼接
                String toastMsg = (totalCount == 1) ? "电话骚扰防御力几乎为0。" : "以下设置将在连拨" + totalCount + "次后接通电话。";
                ToastUtils.show(toastMsg);
                LogUtils.d(TAG, "onSW_IsEnableDun: 云盾参数更新完成，totalCount=" + totalCount);
            } catch (NumberFormatException e) {
                LogUtils.e(TAG, "onSW_IsEnableDun: 云盾参数格式错误", e);
                ToastUtils.show("参数格式错误，请输入整数");
                swIsEnableDun.setChecked(false);
                return;
            }
        }
        settingsModel.setIsEnableDun(isEnableDun);
        Rules.getInstance(this).saveDun();
        Rules.getInstance(this).reload();

        // 刷新参数显示
        etDunTotalCount.setText(Integer.toString(settingsModel.getDunTotalCount()));
        etDunResumeSecondCount.setText(Integer.toString(settingsModel.getDunResumeSecondCount()));
        etDunResumeCount.setText(Integer.toString(settingsModel.getDunResumeCount()));
    }

    public void onUnitTest(View view) {
        LogUtils.d(TAG, "onUnitTest: 点击进入单元测试页面");
        Intent intent = new Intent(this, UnitTestActivity.class);
        startActivity(intent);
    }

    public void onAddNewConnectionRule(View view) {
        LogUtils.d(TAG, "onAddNewConnectionRule: 添加新的连接规则");
        Rules rules = Rules.getInstance(this);
        if (rules != null) {
            rules.getPhoneBlacRuleBeanList().add(new PhoneConnectRuleBean());
            rules.saveRules();
            adapter.notifyDataSetChanged();
        } else {
            LogUtils.e(TAG, "onAddNewConnectionRule: Rules实例为null，添加规则失败");
        }
    }

    public void onDefaultPhone(View view) {
        LogUtils.d(TAG, "onDefaultPhone: 跳转到默认电话应用设置");
        Intent intent = new Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS);
        startActivity(intent);
    }

    public void onCanDrawOverlays(View view) {
        LogUtils.d(TAG, "onCanDrawOverlays: 检查悬浮窗权限");
        // 版本判断硬编码（替代Build.VERSION_CODES.M），适配API30
        if (Build.VERSION.SDK_INT >= ANDROID_6_API && !Settings.canDrawOverlays(this)) {
            askForDrawOverlay();
        } else {
            ToastUtils.show("悬浮窗已开启");
        }
    }

    public void onCleanBoBullToonData(View view) {
        LogUtils.d(TAG, "onCleanBoBullToonData: 清理BoBullToon数据");
        TomCat tomCat = TomCat.getInstance(this);
        if (tomCat != null) {
            tomCat.cleanBoBullToon();
            ToastUtils.show("BoBullToon数据已清理");
        }
    }

    public void onResetBoBullToonURL(View view) {
        LogUtils.d(TAG, "onResetBoBullToonURL: 重置BoBullToon URL");
        Rules rules = Rules.getInstance(this);
        if (rules != null) {
            rules.resetDefaultBoBullToonURL();
            etBoBullToonURL.setText(rules.getBoBullToonURL());
            ToastUtils.show("已重置 BoBullToon URL。");
        }
    }

    public void onDownloadBoBullToon(View view) {
        LogUtils.d(TAG, "onDownloadBoBullToon: 开始下载BoBullToon数据");
        Rules rules = Rules.getInstance(this);
        if (rules == null) {
            LogUtils.e(TAG, "onDownloadBoBullToon: Rules实例为null，下载失败");
            return;
        }
        String inputUrl = etBoBullToonURL.getText().toString().trim();
        String savedUrl = rules.getBoBullToonURL();
        if (!inputUrl.equals(savedUrl)) {
            rules.setBoBullToonURL(inputUrl);
            LogUtils.d(TAG, "onDownloadBoBullToon: BoBullToon URL已更新为" + inputUrl);
        }

        final TomCat tomCat = TomCat.getInstance(this);
        // Java7 匿名内部类实现Runnable，禁止Lambda
        new Thread(new Runnable() {
				@Override
				public void run() {
					if (tomCat != null && tomCat.downloadBoBullToon()) {
						LogUtils.d(TAG, "onDownloadBoBullToon: BoBullToon 下载成功");
						// 主线程更新UI（Java7 匿名内部类）
						runOnUiThread(new Runnable() {
								@Override
								public void run() {
									ToastUtils.show("BoBullToon download OK!");
								}
							});
						MainService.restartMainService(SettingsActivity.this);
						Rules.getInstance(SettingsActivity.this).reload();
					} else {
						LogUtils.e(TAG, "onDownloadBoBullToon: BoBullToon 下载失败");
					}
				}
			}).start();
    }

    public void onSearchBoBullToonPhone(View view) {
        LogUtils.d(TAG, "onSearchBoBullToonPhone: 搜索BoBullToon号码");
        TomCat tomCat = TomCat.getInstance(this);
        String phone = etPhone.getText().toString().trim();
        if (phone.isEmpty()) {
            ToastUtils.show("请输入要查询的号码");
            return;
        }
        if (tomCat != null && tomCat.loadPhoneBoBullToon()) {
            boolean isBoBullToon = tomCat.isPhoneBoBullToon(phone);
            String toastMsg = isBoBullToon ? "It is a BoBullToon Phone!" : "Not in BoBullToon.";
            ToastUtils.show(toastMsg);
            LogUtils.d(TAG, "onSearchBoBullToonPhone: 号码" + phone + "查询结果：" + (isBoBullToon ? "是" : "否") + "为BoBullToon号码");
        } else {
            ToastUtils.show("没有下载 BoBullToon。");
        }
    }

    public void onAbout(View view) {
        LogUtils.d(TAG, "onAbout: 跳转到关于页面");
        WinBoLLActivityManager.getInstance().startWinBoLLActivity(this, AboutActivity.class);
    }

    public void onLogView(View view) {
        LogUtils.d(TAG, "onLogView: 跳转到日志页面");
        WinBoLLActivityManager.getInstance().startLogActivity(this);
    }

    // ====================== 悬浮窗权限请求函数区 ======================
    private void askForDrawOverlay() {
        LogUtils.d(TAG, "askForDrawOverlay: 弹出悬浮窗权限请求对话框");
        // Java7 匿名内部类实现Dialog监听
        AlertDialog alertDialog = new AlertDialog.Builder(this)
			.setTitle("允许显示悬浮框")
			.setMessage("为了使电话监听服务正常工作，请允许这项权限")
			.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					openDrawOverlaySettings();
					dialog.dismiss();
				}
			})
			.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create();

        if (alertDialog.getWindow() != null) {
            alertDialog.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        }
        alertDialog.show();
    }

    private void openDrawOverlaySettings() {
        LogUtils.d(TAG, "openDrawOverlaySettings: 跳转悬浮窗管理设置界面");
        // 版本判断硬编码
        if (Build.VERSION.SDK_INT >= ANDROID_6_API) {
            try {
                Context context = this;
                Class<?> clazz = Settings.class;
                Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION");
                Intent intent = new Intent(field.get(null).toString());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                context.startActivity(intent);
            } catch (Exception e) {
                LogUtils.e(TAG, "openDrawOverlaySettings: 跳转悬浮窗设置失败", e);
                Toast.makeText(this, "请在悬浮窗管理中打开权限", Toast.LENGTH_LONG).show();
            }
        }
    }
}

