package cc.winboll.studio.libaes.views;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import cc.winboll.studio.libaes.R;
import cc.winboll.studio.libaes.enums.ADsMode;
import cc.winboll.studio.libaes.views.ADsControlView;
import cc.winboll.studio.libappbase.LogUtils;
import com.miui.zeus.mimo.sdk.MimoCustomController;
import com.miui.zeus.mimo.sdk.MimoLocation;
import com.miui.zeus.mimo.sdk.MimoSdk;
import cc.winboll.studio.libappbase.ToastUtils;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/11/26 17:51
 * @Describe 广告模式控制控件（Java 7 兼容）
 * 支持：SP持久化、外部静态方法更新、Handler视图同步、外部静态方法读取
 */
public class ADsControlView extends LinearLayout {
	public static final String TAG = "ADsControlView";

	
    // SP存储配置
    private static final String SP_NAME = "ads_control_config";
    private static final String KEY_SELECTED_MODE = "selected_ads_mode";
	// 单机模式与米盟模式标志位
	ADsMode mADsMode;
    private static final String PRIVACY_VALUE = "privacy_value";
	// 隐私协议签约结果 0: 拒绝，1：赞同 2: 未签约
	String privacyAgreeValue;

    // Handler消息标识
    private static final int MSG_UPDATE_MODE = 1001;

    // 控件引用
    private RadioGroup rgAdsMode;
    private RadioButton rbStandalone;
    private RadioButton rbMimoSdk;

    // 外部监听、SP实例、Handler实例
    private OnAdsModeSelectedListener listener;
    private SharedPreferences sharedPreferences;
    private InternalHandler mHandler;
	private Context mContext;

    // 静态列表：存储所有已创建的控件实例（Java 7 标准集合）
    private static final java.util.List<ADsControlView> sControlViews = new java.util.ArrayList<ADsControlView>();

    // 构造方法（Java 7 兼容）
    public ADsControlView(Context context) {
        super(context);
        initView(context);
    }

    public ADsControlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    @SuppressWarnings("deprecation")
    public ADsControlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

	public void setPrivacyAgreeValue(String privacyAgreeValue) {
		this.privacyAgreeValue = privacyAgreeValue;
	}

	public String getPrivacyAgreeValue() {
        String privacyAgreeValue = sharedPreferences.getString(PRIVACY_VALUE, "0");
		return privacyAgreeValue;
	}

	public void setADsMode(ADsMode mADsMode) {
		this.mADsMode = mADsMode;
		sharedPreferences.edit().putString(KEY_SELECTED_MODE, this.mADsMode.name()).apply();
	}

	public ADsMode getADsMode() {
		String savedModeStr = sharedPreferences.getString(KEY_SELECTED_MODE, ADsMode.STANDALONE.name());
        mADsMode = ADsMode.fromValue(savedModeStr);
		return mADsMode;
	}

    /**
     * 初始化视图、SP、Handler
     */
    private void initView(final Context context) {
		this.mContext = context;
        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.view_adscontrol, this, true);

        // 初始化SP
        sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);

        // 绑定控件
        rgAdsMode = (RadioGroup) findViewById(R.id.rg_ads_mode);
        rbStandalone = (RadioButton) findViewById(R.id.rb_standalone);
        rbMimoSdk = (RadioButton) findViewById(R.id.rb_mimo_sdk);

        // 初始化Handler（主线程Looper）
        mHandler = new InternalHandler(Looper.getMainLooper());

        // 注册控件实例到静态列表（线程安全）
        registerControlView(this);

        // 从SP读取初始模式并设置
		ToastUtils.show(String.format("savedMode : %s", getADsMode().name()));
        setSelectedMode(getADsMode());

        // 单选组选择事件监听
        rgAdsMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					if (checkedId == R.id.rb_standalone) {
						setADsMode(ADsMode.STANDALONE);
					} else if (checkedId == R.id.rb_mimo_sdk) {
						showPrivacy(context, new OnPrivacyChangeListener(){
								@Override
								public void onAgreePrivacy() {
									setADsMode(ADsMode.MIMO_SDK);
								}

								@Override
								public void onDisagreePrivacy() {
									setADsMode(ADsMode.STANDALONE);
								}
							});
					}
				}
			});
    }

	/**
     * 【静态】显示隐私协议弹窗（供外部调用，带Context参数）
     * @param context 上下文（需传入Activity Context，用于弹窗显示）
     */
    public static void showPrivacy(Context context, OnPrivacyChangeListener onPrivacyChangeListener) {
        if (context == null) {
            LogUtils.e(TAG, "showPrivacy: Context is null, cannot show privacy dialog");
            return;
        }
        // 校验是否为Activity Context（弹窗必须依附Activity）
        Activity activity = null;
        try {
            activity = (Activity) context;
        } catch (ClassCastException e) {
            LogUtils.e(TAG, "showPrivacy: Context is not Activity Context", e);
            Toast.makeText(context.getApplicationContext(), "请传入Activity上下文以显示隐私协议", Toast.LENGTH_SHORT).show();
            return;
        }
        // 校验Activity状态
        if (activity.isFinishing() || activity.isDestroyed()) {
            LogUtils.e(TAG, "showPrivacy: Activity is finishing or destroyed");
            return;
        }
		
        // 读取隐私协议状态并处理逻辑
        SbhhharedPreferences sp = getPrivacySharedPreferences(context);
        String privacyAgreeValue = sp.getString(PRIVACY_VALUE, null);
        handlePrivacyLogic(activity, privacyAgreeValue, onPrivacyChangeListener);
    }

    /**
     * 【静态】清理SP中存储的隐私协议状态（PRIVACY_VALUE）
     * 函数名：cleanprivacystatus（按要求命名）
     * @param context 上下文（建议使用ApplicationContext）
     */
    public static void cleanPrivacyStatus(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "cleanPrivacyStatus: Context is null, cannot clean privacy status");
            return;
        }
        // 清空PRIVACY_VALUE值（移除该键，恢复初始未选择状态）
        SharedPreferences sp = getPrivacySharedPreferences(context);
        sp.edit().remove(PRIVACY_VALUE).apply();
        LogUtils.i(TAG, "cleanPrivacyStatus: Privacy status cleaned successfully");
		ToastUtils.show("cleanPrivacyStatus: Privacy status cleaned successfully");
        // 清理后同步更新广告模式为单机模式（避免隐私状态为空时仍加载广告）
        //ADsControlView.updateAdsModeByStatic(context, ADsMode.STANDALONE);
    }

    // 【配套静态工具方法】获取隐私协议SP实例（供上述两个静态方法调用，需一并添加）
    private static SharedPreferences getPrivacySharedPreferences(Context context) {
        // 使用ApplicationContext获取SP，避免内存泄漏
        Context appContext = context.getApplicationContext();
        if (appContext != null) {
            return appContext.getSharedPreferences(PRIVACY_FILE, Context.MODE_PRIVATE);
        }
        // 降级方案：若ApplicationContext为空，使用传入的Context
        return context.getSharedPreferences(PRIVACY_FILE, Context.MODE_PRIVATE);
    }

    // 【配套静态工具方法】隐私协议逻辑处理（供上述两个静态方法调用，需一并添加）
    private static void handlePrivacyLogic(final Activity activity, String privacyAgreeValue, final OnPrivacyChangeListener onPrivacyChangeListener) {
        if (TextUtils.equals(privacyAgreeValue, String.valueOf(0))) {
            ADsControlView.updateAdsModeByStatic(activity.getApplicationContext(), ADsMode.STANDALONE);
            LogUtils.i(TAG, "已拒绝隐私协议，广告已处于不可用状态...");
            Toast.makeText(activity.getApplicationContext(), "已拒绝隐私协议，广告已处于不可用状态", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.equals(privacyAgreeValue, String.valueOf(1))) {
            ADsControlView.updateAdsModeByStatic(activity.getApplicationContext(), ADsMode.MIMO_SDK);
            LogUtils.i(TAG, "已同意隐私协议，开始初始化米盟SDK...");
            initMimoSdkStatic(activity.getApplicationContext());
            return;
        } else {
            LogUtils.i(TAG, "开始弹出隐私协议...");
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("用户须知");
            builder.setMessage("小米广告SDK隐私政策: https://dev.mi.com/distribute/doc/details?pId=1688, 请复制到浏览器查看");
            builder.setIcon(R.drawable.ic_launcher);
            builder.setCancelable(false); // 点击对话框以外的区域不消失
            builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						SharedPreferences sp = getPrivacySharedPreferences(activity);
						sp.edit().putString(PRIVACY_VALUE, String.valueOf(1)).apply();
						initMimoSdkStatic(activity.getApplicationContext());
						dialog.dismiss();
						onPrivacyChangeListener.onAgreePrivacy();
					}
				});
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						SharedPreferences sp = getPrivacySharedPreferences(activity);
						sp.edit().putString(PRIVACY_VALUE, String.valueOf(0)).apply();
						ADsControlView.updateAdsModeByStatic(activity.getApplicationContext(), ADsMode.STANDALONE);
						dialog.dismiss();
						onPrivacyChangeListener.onDisagreePrivacy();
					}
				});
            AlertDialog dialog = builder.create();

            // 配置弹窗位置（底部全屏）
            Window window = dialog.getWindow();
            if (window != null) {
                window.setGravity(Gravity.BOTTOM);
                WindowManager m = activity.getWindowManager();
                Display d = m.getDefaultDisplay();
                WindowManager.LayoutParams p = window.getAttributes();
                p.width = d.getWidth();
                window.setAttributes(p);
            }
            dialog.show();
        }
    }

    // 【配套静态工具方法】静态初始化米盟SDK（供上述静态方法调用，需一并添加）
    private static void initMimoSdkStatic(Context appContext) {
        if (appContext == null) {
            LogUtils.e(TAG, "initMimoSdkStatic: ApplicationContext is null");
            return;
        }
        // 初始化SDK，捕获异常避免崩溃
        try {
            MimoSdk.init(appContext, new MimoCustomController() {
					@Override
					public boolean isCanUseLocation() {
						return true;
					}

					@Override
					public MimoLocation getMimoLocation() {
						return null;
					}

					@Override
					public boolean isCanUseWifiState() {
						return true;
					}

					@Override
					public boolean alist() {
						return true;
					}
				}, new MimoSdk.InitCallback() {
					@Override
					public void success() {
						LogUtils.d(TAG, "MimoSdk init success (static)");
					}

					@Override
					public void fail(int code, String msg) {
						LogUtils.e(TAG, "MimoSdk init fail (static), code=" + code + ",msg=" + msg);
					}
				});
            MimoSdk.setDebugOn(true);
        } catch (Exception e) {
            LogUtils.e(TAG, "initMimoSdkStatic: init failed", e);
        }
    }

    /**
     * 静态方法：外部调用更新SP中的模式，并发送消息通知控件更新
     * @param context 上下文（建议使用ApplicationContext）
     * @param mode 要设置的广告模式
     */
    public static void updateAdsModeByStatic(Context context, ADsMode mode) {
        if (context == null || mode == null) {
            return;
        }

        // 1. 更新SP数据
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        sp.edit().putString(KEY_SELECTED_MODE, mode.name()).apply();

        // 2. 发送Handler消息，通知所有控件更新
        InternalHandler.sendUpdateModeMessage(mode);
    }

    /**
     * 新增静态方法：外部调用读取SP中存储的广告模式（Java 7 兼容）
     * @param context 上下文（建议使用ApplicationContext）
     * @return 存储的AdsMode，默认返回单机模式（STANDALONE）
     */
    public static ADsMode getAdsModeFromStatic(Context context) {
        // 空指针校验：上下文为空时返回默认模式
        if (context == null) {
            return ADsMode.STANDALONE;
        }

        // 读取SP数据
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        String savedModeStr = sp.getString(KEY_SELECTED_MODE, ADsMode.STANDALONE.name());

        // 解析枚举并返回（兼容SP中数据异常的情况）
        return ADsMode.fromValue(savedModeStr);
    }

    /**
     * 注册控件实例到静态列表（线程安全）
     */
    private static void registerControlView(ADsControlView view) {
        synchronized (sControlViews) {
            if (!sControlViews.contains(view)) {
                sControlViews.add(view);
            }
        }
    }

    /**
     * 移除控件实例（线程安全）
     */
    private static void unregisterControlView(ADsControlView view) {
        synchronized (sControlViews) {
            sControlViews.remove(view);
        }
    }

    /**
     * 设置选中模式（内部使用，更新UI）
     */
    private void setSelectedMode(final ADsMode mode) {
		final ADsMode mode2;
        if (mode == null) {
            mode2 = ADsMode.STANDALONE;
        } else {
			mode2 = mode;
		}
        // 确保UI操作在主线程
        if (Looper.myLooper() == Looper.getMainLooper()) {
            if (mode2 == ADsMode.STANDALONE) {
                rbStandalone.setChecked(true);
            } else if (mode2 == ADsMode.MIMO_SDK) {
                rbMimoSdk.setChecked(true);
            }
        } else {
            mHandler.post(new Runnable() {
					@Override
					public void run() {
						setSelectedMode(mode2);
					}
				});
        }
    }

    /**
     * 获取当前选中模式
     */
    public ADsMode getSelectedMode() {
        int checkedId = rgAdsMode.getCheckedRadioButtonId();
        return checkedId == R.id.rb_mimo_sdk ? ADsMode.MIMO_SDK : ADsMode.STANDALONE;
    }

    /**
     * 设置外部监听
     */
    public void setOnAdsModeSelectedListener(OnAdsModeSelectedListener listener) {
        this.listener = listener;
    }

    /**
     * 内部Handler类（Java 7 静态内部类，无隐藏API依赖）
     */
    private static class InternalHandler extends Handler {
		static volatile InternalHandler _InternalHandler;
        public InternalHandler(Looper looper) {
            super(looper);
			_InternalHandler = this;
        }

        /**
         * 静态方法：发送模式更新消息
         */
        public static void sendUpdateModeMessage(ADsMode mode) {
            if (mode == null || _InternalHandler == null) {
                return;
            }
            Message msg = _InternalHandler.obtainMessage();
            msg.what = MSG_UPDATE_MODE;
            msg.obj = mode;
            _InternalHandler.sendMessage(msg);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_UPDATE_MODE) {
                ADsMode mode = (ADsMode) msg.obj;
                if (mode == null) {
                    return;
                }

                // 修复：替换isDetachedFromWindow()为isAttachedToWindow()（API 1兼容）
                // 逻辑调整：view.isAttachedToWindow() → 控件已附加到窗口（活跃状态）
                synchronized (sControlViews) {
                    for (ADsControlView view : sControlViews) {
                        // 三重校验：非空 + 可见 + 已附加到窗口（避免操作销毁/未初始化的控件）
                        if (view != null && view.isShown() && view.isAttachedToWindow()) {
                            view.setSelectedMode(mode);
                        }
                    }
                }
            }
        }
    }

    /**
     * 生命周期方法：控件销毁时解除注册，避免内存泄漏
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 移除Handler回调
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        // 从静态列表中移除当前控件
        unregisterControlView(this);
    }

    /**
     * 外部监听接口
     */
    public interface OnAdsModeSelectedListener {
        void onModeSelected(ADsMode selectedMode);
    }

	public interface OnPrivacyChangeListener {
		void onAgreePrivacy();
		void onDisagreePrivacy();
	}
}

