package cc.winboll.studio.contacts.listenphonecall;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.phonecallui.PhoneCallActivity;
import cc.winboll.studio.contacts.phonecallui.PhoneCallService;
import cc.winboll.studio.libappbase.LogUtils;

/**
 * 终极优化版：onCreate 仅注册前台服务，其他逻辑延迟初始化，避免阻塞
 * 适配 Java7 + Android API30
 */
public class CallListenerService extends Service {
    private static final String TAG = "CallListenerService";
    private static final String CHANNEL_ID = "call_listener_channel";
    private static final int NOTIFICATION_ID = 1003;
    private static final int FOREGROUND_SERVICE_TYPE_PHONE_CALL = 0x80;
    private static final int ANDROID_8_API = 26;
    private static final int ANDROID_10_API = 29;
    private static final int ANDROID_19_API = 19;

    // View 与服务相关属性
    private View phoneCallView;
    private TextView tvCallNumber;
    private Button btnOpenApp;
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;
    private PhoneStateListener phoneStateListener;
    private TelephonyManager telephonyManager;
    private String callNumber;
    private boolean hasShown;
    private boolean isCallingIn;
    // 延迟初始化 Handler
    private Handler mDelayHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d(TAG, "onCreate: 服务启动，立即注册前台服务");
        // ========== 第一步：无条件优先执行前台服务注册，这是唯一必须同步做的事 ==========
        boolean foregroundSuccess = startForegroundImmediately();
        if (!foregroundSuccess) {
            LogUtils.e(TAG, "onCreate: 前台服务注册失败，直接停止服务");
            stopSelf();
            return;
        }

        // ========== 第二步：所有其他逻辑延迟 100ms 执行，让出主线程，避免阻塞 ==========
        mDelayHandler = new Handler(Looper.getMainLooper());
        mDelayHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					initDelayedLogic();
				}
			}, 100);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 核心：仅负责前台服务注册，无任何其他逻辑，确保 5 秒内完成
     * @return true 注册成功，false 失败
     */
    private boolean startForegroundImmediately() {
        try {
            Notification notification = createForegroundNotification();
            if (Build.VERSION.SDK_INT >= ANDROID_10_API) {
                startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_PHONE_CALL);
            } else {
                startForeground(NOTIFICATION_ID, notification);
            }
            LogUtils.d(TAG, "startForegroundImmediately: 前台服务注册成功");
            return true;
        } catch (Exception e) {
            LogUtils.e(TAG, "startForegroundImmediately: 注册失败", e);
            return false;
        }
    }

    /**
     * 简化通知创建逻辑，只保留必要参数，确保最快创建
     */
    private Notification createForegroundNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 8.0+ 创建渠道，极简配置
        if (Build.VERSION.SDK_INT >= ANDROID_8_API && manager != null) {
            NotificationChannel channel = new NotificationChannel(
				CHANNEL_ID, "通话监听", NotificationManager.IMPORTANCE_LOW);
            channel.setSound(null, null);
            channel.enableVibration(false);
            manager.createNotificationChannel(channel);
        }

        // 通知构建：必须确保小图标存在！！！替换为你项目中真实存在的图标资源
        Notification.Builder builder = new Notification.Builder(this);
        // 重点：这里的 ic_launcher 必须是 res/drawable 下存在的图标，否则通知创建失败
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("通话监听");
        builder.setContentText("运行中");
        builder.setPriority(Notification.PRIORITY_LOW);
        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            builder.setChannelId(CHANNEL_ID);
        }
        return builder.build();
    }

    /**
     * 延迟初始化所有非核心逻辑：电话监听、悬浮窗
     */
    private void initDelayedLogic() {
        LogUtils.d(TAG, "initDelayedLogic: 开始初始化延迟逻辑");
        initPhoneStateListener();
        initPhoneCallView();
        LogUtils.d(TAG, "initDelayedLogic: 延迟逻辑初始化完成");
    }

    private void initPhoneStateListener() {
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                callNumber = incomingNumber;
                switch (state) {
                    case TelephonyManager.CALL_STATE_IDLE:
                        dismiss();
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        isCallingIn = true;
                        updateUI();
                        show();
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        updateUI();
                        show();
                        break;
                }
            }
        };

        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    private void initPhoneCallView() {
        windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        if (windowManager == null) {
            return;
        }

        int width = windowManager.getDefaultDisplay().getWidth();
        params = new WindowManager.LayoutParams();
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
        params.width = width;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        params.format = PixelFormat.TRANSLUCENT;

        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        if (Build.VERSION.SDK_INT >= ANDROID_19_API) {
            params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        }

        FrameLayout interceptorLayout = new FrameLayout(this) {
            @Override
            public boolean dispatchKeyEvent(KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return super.dispatchKeyEvent(event);
            }
        };

        phoneCallView = LayoutInflater.from(this).inflate(R.layout.view_phone_call, interceptorLayout);
        tvCallNumber = (TextView) phoneCallView.findViewById(R.id.tv_call_number);
        btnOpenApp = (Button) phoneCallView.findViewById(R.id.btn_open_app);
        btnOpenApp.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					PhoneCallService.CallType type = isCallingIn ? PhoneCallService.CallType.CALL_IN : PhoneCallService.CallType.CALL_OUT;
					PhoneCallActivity.actionStart(CallListenerService.this, callNumber, type);
				}
			});
    }

    private void show() {
        if (!hasShown && phoneCallView != null && windowManager != null) {
            try {
                windowManager.addView(phoneCallView, params);
                hasShown = true;
            } catch (Exception e) {
                LogUtils.e(TAG, "show: 悬浮窗添加失败", e);
            }
        }
    }

    private void dismiss() {
        if (hasShown && phoneCallView != null && windowManager != null) {
            try {
                windowManager.removeView(phoneCallView);
            } catch (Exception e) {
                LogUtils.e(TAG, "dismiss: 悬浮窗移除失败", e);
            } finally {
                hasShown = false;
                isCallingIn = false;
            }
        }
    }

    private void updateUI() {
        if (tvCallNumber == null) {
            return;
        }
        String formatNumber = formatPhoneNumber(callNumber);
        tvCallNumber.setText(formatNumber);
        int drawableId = isCallingIn ? R.drawable.ic_phone_call_in : R.drawable.ic_phone_call_out;
        tvCallNumber.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(drawableId), null);
    }

    public static String formatPhoneNumber(String phoneNum) {
        if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() == 11) {
            return phoneNum.substring(0, 3) + "-" + phoneNum.substring(3, 7) + "-" + phoneNum.substring(7);
        }
        return phoneNum;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismiss();
        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
        if (mDelayHandler != null) {
            mDelayHandler.removeCallbacksAndMessages(null);
        }
        // 清空所有引用
        phoneStateListener = null;
        telephonyManager = null;
        windowManager = null;
        phoneCallView = null;
    }
}

