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.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.libappbase.LogUtils;
import cc.winboll.studio.libappbase.LogView;
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 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;


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

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

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

        // 初始化工具栏（仅加载基础UI）
        mToolbar = (Toolbar) findViewById(R.id.activitymainToolbar1);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setSubtitle(TAG);

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

        // 创建Fragment列表（仅实例化，不加载数据）
        fragmentList = new ArrayList<Fragment>();
        tabTitleList = new ArrayList<String>();
        fragmentList.add(CallLogFragment.newInstance(0));
        fragmentList.add(ContactsFragment.newInstance(1)); // 延迟加载联系人数据
        fragmentList.add(LogFragment.newInstance(2));
        tabTitleList.add("通话记录");
        tabTitleList.add("联系人");
        tabTitleList.add("应用日志");

        // 设置ViewPager适配器
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList, tabTitleList);
        viewPager.setAdapter(adapter);

        // 关键：关闭预加载，仅当前页初始化
        viewPager.setOffscreenPageLimit(0);

        // 关联TabLayout和ViewPager
        tabLayout.setupWithViewPager(viewPager);

        // 初始化服务状态（延迟启动非核心服务）
        MainServiceBean mMainServiceBean = MainServiceBean.loadBean(this, MainServiceBean.class);
        if (mMainServiceBean == null) {
            mMainServiceBean = new MainServiceBean();
            MainServiceBean.saveBean(this, mMainServiceBean);
        }
        if (mMainServiceBean.isEnable()) {
            // 延迟1秒启动服务，避免阻塞启动
            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);
    }


    // ViewPager适配器（Java 7语法）
    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) {
            return;
        }
        _MainActivity.startActivity(intent);
    }

    // OnPageChangeListener接口实现
    @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();
            }
        }
    }
}

