package cc.winboll.studio.contacts.phonecallui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import cc.winboll.studio.contacts.ActivityStack;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.listenphonecall.CallListenerService;
import cc.winboll.studio.libappbase.LogUtils;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author aJIEw, ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/02/13 06:58:04
 * @Describe 接打电话界面，仅支持 Android 6.0（API 23）及以上系统
 */
// Java7不支持@RequiresApi，通过代码内校验替代注解
public class PhoneCallActivity extends AppCompatActivity implements View.OnClickListener {
    // ====================== 常量定义区 ======================
    public static final String TAG = "PhoneCallActivity";
    // Intent传参键常量，替代系统常量避免歧义
    private static final String EXTRA_CALL_TYPE = "extra_call_type";
    private static final String EXTRA_PHONE_NUM = "extra_phone_number";

    // ====================== 控件与成员变量区 ======================
    private TextView tvCallNumberLabel;
    private TextView tvCallNumber;
    private TextView tvPickUp;
    private TextView tvCallingTime;
    private TextView tvHangUp;

    private PhoneCallManager phoneCallManager;
    private PhoneCallService.CallType callType;
    private String phoneNumber;
    private Timer onGoingCallTimer;
    private int callingTime;

    // ====================== 静态跳转方法区 ======================
    /**
     * 启动通话界面
     * @param context 上下文
     * @param phoneNumber 通话号码
     * @param callType 通话类型（来电/去电）
     */
    public static void actionStart(Context context, String phoneNumber, PhoneCallService.CallType callType) {
        if (context == null) {
            LogUtils.e(TAG, "actionStart: 上下文为null，无法启动通话界面");
            return;
        }
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            LogUtils.w(TAG, "actionStart: 通话号码为空");
        }
        if (callType == null) {
            LogUtils.w(TAG, "actionStart: 通话类型为null");
        }

        Intent intent = new Intent(context, PhoneCallActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(EXTRA_CALL_TYPE, callType);
        intent.putExtra(EXTRA_PHONE_NUM, phoneNumber);
        context.startActivity(intent);
        LogUtils.d(TAG, "actionStart: 启动通话界面，号码=" + phoneNumber + "，类型=" + callType);
    }

    // ====================== 生命周期方法区 ======================
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG, "onCreate: 通话界面创建");

        // Java7不支持@RequiresApi，此处补充系统版本校验
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            LogUtils.e(TAG, "onCreate: 系统版本低于Android 6.0，不支持该通话界面");
            finish();
            return;
        }

        setContentView(R.layout.activity_phone_call);
        ActivityStack.getInstance().addActivity(this);
        initData();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy: 通话界面销毁");
        stopTimer();
        if (phoneCallManager != null) {
            phoneCallManager.destroy();
        }
        ActivityStack.getInstance().removeActivity(this);
    }

    // ====================== 初始化方法区 ======================
    /**
     * 初始化数据
     */
    private void initData() {
        phoneCallManager = new PhoneCallManager(this);
        onGoingCallTimer = new Timer();
        parseIntentData();
        LogUtils.d(TAG, "initData: 数据初始化完成，通话类型=" + callType + "，号码=" + phoneNumber);
    }

    /**
     * 解析Intent传递的数据
     */
    private void parseIntentData() {
        Intent intent = getIntent();
        if (intent == null) {
            LogUtils.w(TAG, "parseIntentData: 未获取到启动Intent");
            return;
        }
        phoneNumber = intent.getStringExtra(EXTRA_PHONE_NUM);
        callType = (PhoneCallService.CallType) intent.getSerializableExtra(EXTRA_CALL_TYPE);
    }

    /**
     * 初始化界面控件
     */
    @SuppressLint("SetTextI18n")
    private void initView() {
        // 设置沉浸式导航栏
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
			| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
			| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
			| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        LogUtils.d(TAG, "initView: 设置界面沉浸式样式");

        // 绑定控件
        tvCallNumberLabel = findViewById(R.id.tv_call_number_label);
        tvCallNumber = findViewById(R.id.tv_call_number);
        tvPickUp = findViewById(R.id.tv_phone_pick_up);
        tvCallingTime = findViewById(R.id.tv_phone_calling_time);
        tvHangUp = findViewById(R.id.tv_phone_hang_up);

        // 设置控件事件与初始状态
        tvCallNumber.setText(CallListenerService.formatPhoneNumber(phoneNumber));
        tvPickUp.setOnClickListener(this);
        tvHangUp.setOnClickListener(this);

        setCallTypeUi();
        showOnLockScreen();
        LogUtils.d(TAG, "initView: 界面控件初始化完成");
    }

    // ====================== 界面交互方法区 ======================
    /**
     * 根据通话类型设置界面样式
     */
    private void setCallTypeUi() {
        if (callType == null) {
            LogUtils.w(TAG, "setCallTypeUi: 通话类型为null，使用默认样式");
            tvCallNumberLabel.setText("通话号码");
            tvPickUp.setVisibility(View.GONE);
            return;
        }

        if (PhoneCallService.CallType.CALL_IN == callType) {
            tvCallNumberLabel.setText("来电号码");
            tvPickUp.setVisibility(View.VISIBLE);
        } else if (PhoneCallService.CallType.CALL_OUT == callType) {
            tvCallNumberLabel.setText("呼叫号码");
            tvPickUp.setVisibility(View.GONE);
            if (phoneCallManager != null) {
                phoneCallManager.openSpeaker();
                LogUtils.d(TAG, "setCallTypeUi: 去电模式，开启扬声器");
            }
        }
    }

    /**
     * 设置界面锁屏显示
     */
    private void showOnLockScreen() {
        getWindow().setFlags(
			WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
			| WindowManager.LayoutParams.FLAG_FULLSCREEN
			| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
			| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
			WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
			| WindowManager.LayoutParams.FLAG_FULLSCREEN
			| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
			| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        );
        LogUtils.d(TAG, "showOnLockScreen: 设置界面支持锁屏显示");
    }

    // ====================== 事件点击与计时方法区 ======================
    @Override
    public void onClick(View v) {
        if (v == null) {
            LogUtils.w(TAG, "onClick: 点击空控件");
            return;
        }

        int id = v.getId();
        if (id == R.id.tv_phone_pick_up) {
            LogUtils.d(TAG, "onClick: 点击接听按钮");
            answerCall();
        } else if (id == R.id.tv_phone_hang_up) {
            LogUtils.d(TAG, "onClick: 点击挂断按钮");
            hangUpCall();
        } else {
            LogUtils.w(TAG, "onClick: 点击未知控件，ID=" + id);
        }
    }

    /**
     * 接听通话
     */
    private void answerCall() {
        if (phoneCallManager != null) {
            phoneCallManager.answer();
            tvPickUp.setVisibility(View.GONE);
            tvCallingTime.setVisibility(View.VISIBLE);
            startCallTimer();
            LogUtils.d(TAG, "answerCall: 接听通话成功");
        } else {
            LogUtils.e(TAG, "answerCall: 通话管理器为空，无法接听");
        }
    }

    /**
     * 挂断通话
     */
    private void hangUpCall() {
        if (phoneCallManager != null) {
            phoneCallManager.disconnect();
        } else {
            LogUtils.e(TAG, "hangUpCall: 通话管理器为空，无法挂断");
        }
        stopTimer();
        finish();
    }

    /**
     * 启动通话计时器
     */
    private void startCallTimer() {
        stopTimer();
        onGoingCallTimer = new Timer();
        onGoingCallTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
							@SuppressLint("SetTextI18n")
							@Override
							public void run() {
								callingTime++;
								tvCallingTime.setText("通话中：" + getCallingTime());
							}
						});
				}
			}, 0, 1000);
        LogUtils.d(TAG, "startCallTimer: 通话计时器启动");
    }

    /**
     * 停止通话计时器
     */
    private void stopTimer() {
        if (onGoingCallTimer != null) {
            onGoingCallTimer.cancel();
            onGoingCallTimer = null;
        }
        callingTime = 0;
        LogUtils.d(TAG, "stopTimer: 通话计时器停止");
    }

    /**
     * 格式化通话时长
     */
    private String getCallingTime() {
        int minute = callingTime / 60;
        int second = callingTime % 60;
        String minuteStr = minute < 10 ? "0" + minute : String.valueOf(minute);
        String secondStr = second < 10 ? "0" + second : String.valueOf(second);
        return minuteStr + ":" + secondStr;
    }
}

