package com.pxkj.jwzs;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.acrabsoft.sdk.ASPSDKUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by 皮蛋 on 2022/03/22.
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected String TAG = getClass().getSimpleName();

    public static String ACTION_LOGIN = "com.ydjw.ua.ACTION_LOGIN";
    public static String ACTION_LOGOUT = "com.ydjw.ua.ACTION_LOGOUT";

    protected static String appId = "320924230000-2-1-32092423SJNB12202507111046530001";
//    protected static String appId = "320500220500-2-1-32050022SJ97122021091XXXXXXXXXX";
    protected static String departId = "320924230000";
//    protected static String departId = "3205002xxxxxx";

    private final String my_service_id = "320924230000-3-0800-5CDEC9969D674E1CBB7E2F86A697B0D7";


    public interface WebViewLogger {
        void logToWebView(String message);
    }

    protected WebViewLogger webViewLogger;

    public void setWebViewLogger(WebViewLogger logger) {
        this.webViewLogger = logger;
    }

    protected void log(String tag, String message) {
        String logMsg = "[" + tag + "] " + message;
        Log.e(tag, message);
        if (webViewLogger != null) {
            webViewLogger.logToWebView(logMsg);
        }
    }


    public interface OnResourceAddressListener {
        String onResourceAddressReady(String address);
    }

    // 保持原有的成员变量
    private OnResourceAddressListener addressListener;

    protected void getResourceAddress(OnResourceAddressListener listener) {
        this.addressListener = listener;
        // 实际获取地址的逻辑...
//        init();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_LOGIN);
        filter.addAction(ACTION_LOGOUT);
        registerReceiver(broadcastReceiver, filter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(ACTION_LOGIN.equals(action)){
                getCredential();
            }else if(ACTION_LOGOUT.equals(action)){
                MyApplication.getInstance().finishAll();
            }
        }
    };

    protected void init(){
        try {
            ASPSDKUtils.AndroidManifestInspect(getApplicationContext(), new ASPSDKUtils.AndroidManifestInspectCallBack() {
                @Override
                public void success(String jsonString) {
                    log(TAG, "success--->"+jsonString);
                    Toast.makeText(getApplicationContext(), "正在加载", Toast.LENGTH_SHORT).show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getCredential();
                        }
                    }).start();
                }

                @Override
                public void fail(final String err) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), ""+err, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void getCredential() {
        log(TAG, "获取用户凭证:"+appId);
        ASPSDKUtils.getCredential(getApplicationContext(), appId, departId, "2", new ASPSDKUtils.CredentialCallBack() {
            @Override
            public void success(String messageId, String userCredential, String appCredential) {
                log(TAG, "用户认证凭证获取 success \nmessageId---->" + messageId + "\nuserCredential---->" + userCredential + "\nappCredential---->" + appCredential);

                try {
                    JSONObject json = new JSONObject(userCredential);
                    JSONObject credential = json.optJSONObject("credential");
                    JSONObject load = credential.optJSONObject("load");
                    JSONObject userInfo = load.optJSONObject("userInfo");
                    String xm = userInfo.optString("xm");
                    String sfzh = userInfo.optString("sfzh");
                    SpUtils.putString(getApplicationContext(), Constant.XM, xm);
                    SpUtils.putString(getApplicationContext(), Constant.SFZH, sfzh);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                SpUtils.putString(getApplicationContext(), Constant.MESSAGE_ID, messageId);
                SpUtils.putString(getApplicationContext(), Constant.USER_CREDENTIAL, userCredential);
                SpUtils.putString(getApplicationContext(), Constant.APP_CREDENTIAL, appCredential);
                getResourceAddress();
            }

            @Override
            public void fail(String messageId, final String errMsg) {
                log(TAG, "用户认证凭证获取 fail \nmessageId---->" + messageId + "\nerrMsg---->" + errMsg);
                if(errMsg!=null && errMsg.startsWith("-1")){
                    // 跳过，不显示对话框
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            createAlertDialog("错误", "" + errMsg, BaseActivity.this);
                        }
                    });
                }
            }
        });
    }

    protected void getResourceAddress() {
        log(TAG, "获取资源地址:"+appId);
        ASPSDKUtils.getResourceAddress(getApplicationContext(),
                SpUtils.getString(getApplicationContext(), Constant.MESSAGE_ID, ""),
                SpUtils.getString(getApplicationContext(), Constant.APP_CREDENTIAL, ""),
                    new ASPSDKUtils.ResourceAddressCallBack() {
                        @Override
                        public void success(String messageId, String resourceList) {
                            log(TAG, "资源寻址成功: " + resourceList);
                            try {
                                JSONArray array = new JSONArray(resourceList);
                                for(int i = 0; i < array.length(); i++) {
                                    JSONObject json = array.getJSONObject(i);
                                    String resourceId = json.getString("resourceId");
                                    String resourceAddress = json.getString("resourceAddress");

                                    if (my_service_id.equals(resourceId)) {
                                        log(TAG, "找到匹配资源地址: " + resourceAddress);
                                        // 关键点：在这里回调给监听器
                                        if (addressListener != null) {
                                            log(TAG, "设置地址: " + resourceAddress);
                                            addressListener.onResourceAddressReady(resourceAddress);
                                        }
                                        SpUtils.putString(BaseActivity.this, "TARGET_URL", resourceAddress);
                                        return;
                                    }
                                }
                                // 没有找到匹配资源
                                if (addressListener != null) {
                                        addressListener.onResourceAddressReady(null);
                                }
                            } catch (JSONException e) {
                                log(TAG, "解析资源列表出错");
                                if (addressListener != null) {
                                        addressListener.onResourceAddressReady(null);
                                }
                            }
                        }

                        @Override
                        public void fail(String messageId, String errMsg) {
                            log(TAG, "资源寻址失败: " + errMsg);
                            if (addressListener != null) {
                                    addressListener.onResourceAddressReady(null);
                            }
                        }
                    });
    }

    protected void createAlertDialog(String title, String content, Context context){
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setCancelable(true);
        alertBuilder.setTitle(""+title);
        alertBuilder.setMessage(""+content);
        alertBuilder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alertBuilder.create().show();
    }

    protected abstract void refresh();
}
