package com.tencent.qian.webview.demo;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;

import com.tencent.qian.webview.TencentQianWebView;
import com.tencent.qian.webview.TencentQianWebViewPrewarmer;
import com.tencent.qian.webview.model.PrewarmConfig;
import com.tencent.qian.webview.model.PrewarmEnvironment;
import com.tencent.qian.webview.model.PrewarmLevel;
import com.tencent.qian.webview.model.SdkEvent;
import com.tencent.qian.webview.model.SignAction;
import com.tencent.qian.webview.model.SignCallback;
import com.tencent.qian.webview.model.SignResult;
import com.tencent.qian.webview.model.SignResultStatus;
import com.tencent.qian.webview.model.TencentQianWebViewConfig;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Demo 主页:
 *
 * <ul>
 *   <li>顶部 EditText:粘贴客户后端发起的真实 flowId URL</li>
 *   <li>三按钮:
 *     <ol>
 *       <li>容器模式打开签署页</li>
 *       <li>配置模式改造既有 WebView</li>
 *       <li>打开自检页(beta URL)</li>
 *     </ol>
 *   </li>
 *   <li>底部 TextView:实时打印最近一次 SignResult / SdkEvent</li>
 * </ul>
 */
public class MainActivity extends AppCompatActivity {

    private EditText urlInput;
    private TextView output;
    private EditText prewarmBizTypeInput;
    private Button prewarmBizTypeSpinner;
    private final List<String> bizTypeOptions = new ArrayList<>(Arrays.asList("single-sign", "batch-sign", "enterprise-register", "join-enterprise"));

    private final SignCallback callback = new SignCallback() {
        @Override
        public void onSignResult(SignResult result) {
            log("⮞ SignResult action=" + result.getAction() + " result=" + result.getResult()
                    + " flowId=" + result.getFlowId() + " extras=" + result.getExtras());

            // 演示客户读取 action 的推荐写法:用常量比对,else 分支兜底未来值
            String human;
            String action = result.getAction();
            if (SignAction.SIGN.equals(action)) {
                human = "签署";
            } else if (SignAction.FILL.equals(action)) {
                human = "填写";
            } else if (SignAction.REJECT_SIGN.equals(action)) {
                human = "拒签";
            } else if (SignAction.REJECT_FILL.equals(action)) {
                human = "拒填";
            } else if (SignAction.VIEW.equals(action)) {
                human = "查看";
            } else if (action.isEmpty()) {
                human = "无 action";
            } else {
                human = "未知 action(" + action + ")";
            }
            boolean ok = SignResultStatus.SUCCESS.equals(result.getResult());
            Toast.makeText(MainActivity.this, human + (ok ? " 成功" : " 未成功"), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onEvent(SdkEvent event) {
            log("• " + event.getClass().getSimpleName() + ": " + event);

            // 演示:客户可在 onEvent 中根据事件类型做 UI 反馈
            if (event instanceof SdkEvent.DownloadStart) {
                String url = ((SdkEvent.DownloadStart) event).getUrl();
                String fileName = url.substring(url.lastIndexOf('/') + 1);
                Toast.makeText(MainActivity.this, "开始下载: " + fileName, Toast.LENGTH_SHORT).show();
            } else if (event instanceof SdkEvent.DownloadFailed) {
                String reason = ((SdkEvent.DownloadFailed) event).getReason();
                Toast.makeText(MainActivity.this, "下载失败: " + reason, Toast.LENGTH_SHORT).show();
            } else if (event instanceof SdkEvent.RenderProcessGone) {
                Toast.makeText(MainActivity.this, "页面异常,正在恢复…", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowCompat.setDecorFitsSystemWindows(getWindow(), true);
        setContentView(R.layout.activity_main);

        urlInput = findViewById(R.id.url_input);
        output = findViewById(R.id.output);
        output.setMovementMethod(ScrollingMovementMethod.getInstance());

        findViewById(R.id.btn_open_container).setOnClickListener(v -> openContainer());
        findViewById(R.id.btn_open_configurator).setOnClickListener(v -> openConfigurator());
        findViewById(R.id.btn_open_compatibility).setOnClickListener(v -> openCompatibility());

        prewarmBizTypeInput = findViewById(R.id.prewarm_biztype);
        findViewById(R.id.btn_prewarm_minimal).setOnClickListener(v -> triggerPrewarm(PrewarmLevel.MINIMAL));
        findViewById(R.id.btn_prewarm_light).setOnClickListener(v -> triggerPrewarm(PrewarmLevel.LIGHT));
        findViewById(R.id.btn_prewarm_heavy).setOnClickListener(v -> triggerPrewarm(PrewarmLevel.HEAVY));
        findViewById(R.id.btn_release_pool).setOnClickListener(v -> handleReleasePool());

        prewarmBizTypeSpinner = findViewById(R.id.prewarm_biztype_spinner);
        prewarmBizTypeSpinner.setOnClickListener(v -> {
            new AlertDialog.Builder(this)
                    .setTitle("选择 bizType")
                    .setItems(bizTypeOptions.toArray(new String[0]), (dialog, which) -> {
                        prewarmBizTypeInput.setText(bizTypeOptions.get(which));
                    })
                    .show();
        });
        // 配置预热（UA 与 buildConfig 对齐，池实例才能复用）
        TencentQianWebViewPrewarmer.configure(
                PrewarmConfig.builder()
                        .environment(PrewarmEnvironment.BETA)
                        .userAgentExtra("qianwv-demo/1.0.0")
                        .preferredLanguage("zh-CN")
                        .build()
        );

        TencentQianWebViewPrewarmer.getMenuBizTypes(bizTypes -> {
            runOnUiThread(() -> {
                bizTypeOptions.clear();
                bizTypeOptions.addAll(bizTypes);
            });
        });

        findViewById(R.id.btn_clear_log).setOnClickListener(v -> output.setText(""));
    }

    // ────────── 三按钮 ──────────

    private void openContainer() {
        String url = urlInput.getText().toString().trim();
        if (url.isEmpty()) {
            Toast.makeText(this, "请先粘贴 flowId URL", Toast.LENGTH_SHORT).show();
            return;
        }
        TencentQianWebView.open(
                this,
                url,
                new TencentQianWebViewConfig.Builder()
                        .topBarTitle("电子签署(容器模式)")
                        .userAgentExtra("qianwv-demo/1.0.0")
                        .confirmBeforeClose(true)
                        .build(),
                callback
        );
    }

    private void openConfigurator() {
        String url = urlInput.getText().toString().trim();
        if (url.isEmpty()) {
            Toast.makeText(this, "请先粘贴 flowId URL", Toast.LENGTH_SHORT).show();
            return;
        }
        // 通过静态方法把 URL + callback 传给 ConfiguratorDemoActivity
        ConfiguratorDemoActivity.start(this, url, callback);
    }

    private void openCompatibility() {
        TencentQianWebView.openCompatibilityTest(
                this,
                null,   // 走 SDK 默认 beta URL
                callback
        );
    }

    // ────────── 预热（真机验证） ──────────

    private void triggerPrewarm(PrewarmLevel level) {
        String bizType = prewarmBizTypeInput.getText().toString().trim();
        if (bizType.isEmpty()) bizType = "single-sign";
        try {
            if (level == PrewarmLevel.MINIMAL) {
                TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.MINIMAL);
                log("[prewarm] MINIMAL (DNS) triggered");
            } else if (level == PrewarmLevel.LIGHT) {
                TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.LIGHT, bizType, this);
                log("[prewarm] LIGHT (kernel init) bizType=" + bizType + " triggered");
            } else {
                TencentQianWebViewPrewarmer.prewarm(PrewarmLevel.HEAVY, bizType, this);
                log("[prewarm] HEAVY (off-screen pool) bizType=" + bizType + " triggered");
            }
            Toast.makeText(this, "已触发预热", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            log("[prewarm] failed: " + e.getMessage());
        }
    }

    private void handleReleasePool() {
        TencentQianWebViewPrewarmer.releaseAll();
        log("[prewarm] pool released (releaseAll)");
        Toast.makeText(this, "已释放预热池", Toast.LENGTH_SHORT).show();
    }

    /**
     * 【接入方示范】业务入口页销毁 == 业务流程结束 → 释放预热池。
     *
     * 建议在承载签署流程的业务入口页/会话终点（如本 Activity 的 onDestroy）调用 releaseAll：
     * 它会销毁预热 WebView 实例 并重置去重状态，使预热系统回到初始态——
     * 这样用户下次再进入同一业务流程时，prewarm 能重新生效。
     * 若只想临时回收内存、仍保留“本会话已预热过”的去重记账，则改用 release()。
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        TencentQianWebViewPrewarmer.releaseAll();
    }

    private void log(String line) {
        runOnUiThread(() -> {
            output.append(line);
            output.append("\n");
        });
    }
}
