package cc.winboll.studio.contacts;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/08/30 14:32
 * @Describe 主窗口
 */
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.activities.SettingsActivity;
import cc.winboll.studio.contacts.beans.MainServiceBean;
import cc.winboll.studio.contacts.fragments.CallLogFragment;
import cc.winboll.studio.contacts.fragments.ContactsFragment;
import cc.winboll.studio.contacts.fragments.LogFragment;
import cc.winboll.studio.contacts.services.MainService;
import cc.winboll.studio.contacts.utils.AppGoToSettingsUtil;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.LogView;
import cc.winboll.studio.libappbase.utils.ToastUtils;
import cc.winboll.studio.libappbase.winboll.IWinBoLLActivity;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;

final public class MainActivity extends AppCompatActivity implements IWinBoLLActivity, ViewPager.OnPageChangeListener, View.OnClickListener {

    public static final String TAG = "MainActivity";
    public static final int REQUEST_HOME_ACTIVITY = 0;
    public static final int REQUEST_ABOUT_ACTIVITY = 1;
    public static final int REQUEST_APP_SETTINGS = 2;
    public static final String ACTION_SOS = "cc.winboll.studio.libappbase.WinBoLL.ACTION_SOS";

    static MainActivity _MainActivity;
    LogView mLogView;
    Toolbar mToolbar;
    CheckBox cbMainService;
    MainServiceBean mMainServiceBean;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<View> views; 
    ImageView[] imageViews;
    LinearLayout linearLayout;
    int currentPoint = 0;

    private TelephonyManager telephonyManager;
    private MyPhoneStateListener phoneStateListener;
    List<Fragment> fragmentList;
    List<String> tabTitleList;

    private static final int DIALER_REQUEST_CODE = 1;
    private static final int REQUEST_REQUIRED_PERMISSIONS = 1002;
    // 关键修改1：新增 READ_CALL_LOG 权限到必需权限列表（解决通话记录读取崩溃）
    private String[] REQUIRED_PERMISSIONS = new String[]{
		Manifest.permission.READ_CONTACTS,  // 通讯录读取（原）
		Manifest.permission.CALL_PHONE,     // 电话拨号（原）
		Manifest.permission.READ_CALL_LOG   // 通话记录读取（新增，核心修复）
    };


    @Override
    public Activity getActivity() {
        return this;
    }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _MainActivity = this;

        // 优先检查所有必需权限（含新增的 READ_CALL_LOG）
        if (!checkAllRequiredPermissions()) {
            requestAllRequiredPermissions();
        } else {
            initUIAndLogic(savedInstanceState);
        }
		
		//ToastUtils.show("onCreate");
    }

    // 权限检查方法（无需修改，自动包含新增的 READ_CALL_LOG）
    private boolean checkAllRequiredPermissions() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(this, permission) 
				!= PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    // 权限申请方法（无需修改，自动申请新增的 READ_CALL_LOG）
    private void requestAllRequiredPermissions() {
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_REQUIRED_PERMISSIONS);
    }

    // 权限结果回调（无需修改，确保所有权限（含 READ_CALL_LOG）都通过才加载UI）
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_REQUIRED_PERMISSIONS) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                initUIAndLogic(null);
            } else {
                // 关键修改2：更新提示文案，告知用户新增的“通话记录权限”
                showPermissionDeniedDialogAndExit();
            }
        }
    }

    // 核心修改：新增“设置权限”按钮，点击调用 AppGoToSettingsUtil 跳转设置页
    private void showPermissionDeniedDialogAndExit() {
        new AlertDialog.Builder(this)
			.setTitle("权限不足，无法使用")
			// 文案修改：明确新增“通话记录读取”权限
			.setMessage("应用需要「通讯录读取」、「电话」和「通话记录读取」权限才能正常运行，请授予权限后重新打开应用。")
			.setCancelable(false)
			// 新增：左侧“设置权限”按钮（先添加的按钮在左侧）
			.setNegativeButton("设置权限", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(android.content.DialogInterface dialog, int which) {
					dialog.dismiss();
					// 调用工具类跳转应用设置页（按需求实现）
					AppGoToSettingsUtil appGoToSettingsUtil = new AppGoToSettingsUtil();
					appGoToSettingsUtil.GoToSetting(MainActivity.this);
				}
			})
			// 原有：右侧“确定退出”按钮（后添加的按钮在右侧）
			.setPositiveButton("确定退出", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(android.content.DialogInterface dialog, int which) {
					dialog.dismiss();
					finishAndRemoveTask();
				}
			})
			.show();
    }

    // 初始化UI和逻辑（无需修改，权限通过后才加载 CallLogFragment）
    private void initUIAndLogic(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.activitymainToolbar1);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setSubtitle(TAG);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);

        fragmentList = new ArrayList<Fragment>();
        tabTitleList = new ArrayList<String>();
        // CallLogFragment 仅在权限通过后才实例化（避免提前触发读取）
        fragmentList.add(CallLogFragment.newInstance(0));
        fragmentList.add(ContactsFragment.newInstance(1));
        fragmentList.add(LogFragment.newInstance(2));
        tabTitleList.add("通话记录");
        tabTitleList.add("联系人");
        tabTitleList.add("应用日志");

        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList, tabTitleList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(0); // 关闭预加载，避免提前初始化 CallLogFragment
        tabLayout.setupWithViewPager(viewPager);

        // 原有服务启动、电话监听等逻辑...
        MainServiceBean mMainServiceBean = MainServiceBean.loadBean(this, MainServiceBean.class);
        if (mMainServiceBean == null) {
            mMainServiceBean = new MainServiceBean();
            MainServiceBean.saveBean(this, mMainServiceBean);
        }
        if (mMainServiceBean.isEnable()) {
            new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						MainService.startMainService(MainActivity.this);
					}
				}, 1000);
        }

        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        phoneStateListener = new MyPhoneStateListener();
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }


    // 以下为原有代码（无需修改）
    private class MyPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> tabTitleList;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> tabTitleList) {
            super(fm);
            this.fragmentList = fragmentList;
            this.tabTitleList = tabTitleList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabTitleList.get(position);
        }
    }

    public static void dialPhoneNumber(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(android.net.Uri.parse("tel:" + phoneNumber));
        if (ActivityCompat.checkSelfPermission(_MainActivity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(_MainActivity, "拨号权限不足", Toast.LENGTH_SHORT).show();
            return;
        }
        _MainActivity.startActivity(intent);
    }

    @Override
    public void onPageScrollStateChanged(int state) {}
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
    @Override
    public void onPageSelected(int position) {}
    @Override
    public void onClick(View v) {}

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    LogUtils.d(TAG, "电话已挂断");
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    LogUtils.d(TAG, "正在通话中");
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    LogUtils.d(TAG, "来电: " + incomingNumber);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy() SOS");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.item_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public boolean isDefaultPhoneCallApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            TelecomManager manger = (TelecomManager) getSystemService(TELECOM_SERVICE);
            if (manger != null && manger.getDefaultDialerPackage() != null) {
                return manger.getDefaultDialerPackage().equals(getPackageName());
            }
        }
        return false;
    }

    public boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (manager == null) return false;

        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
			Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == DIALER_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(MainActivity.this, getString(R.string.app_name) + " 已成为默认电话应用",
							   Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_APP_SETTINGS) {
			recreate();
		}
    }
}

