package com.common.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.TextView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import tech.starwin.LibConfig;
import tech.starwin.R;

import com.common.base.BaseActivity;

import tech.starwin.base.RecyclerViewHolder;
import tech.starwin.constants.ActionEnum;
import tech.starwin.impl.OnEventClickListener;
import tech.starwin.impl.OnNoShakeClickListener;
import tech.starwin.network.Gateway;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.TrackEventHelper;
import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.ui_utils.DialogFactory;
import tech.starwin.utils.ui_utils.UIHelper;

import com.common.toolbox.app_utils.DeviceInfo;
import com.common.toolbox.tracker.TrackEvent;
import com.common.widget.TopBar;

import java.io.Serializable;

/**
 * Created by SiKang on 2018/11/19.
 * 注册协议及隐私政策
 */
public class AgreementPolicyActivity extends BaseActivity {
    public enum Type implements Serializable {
        AGREEMENT_POLICY,
        AGREEMENT_KSP,
        AGREEMENT_HOOK
    }

    /**
     * 2019/9/6  协议展示改为Dialog
     */
    public static void showPolicyDialog(Activity context, Type type, DialogInterface.OnDismissListener dismissListener) {
        Dialog dialog = DialogFactory.createCustomDialog(context, R.layout.dialog_policy,
                (dialog1, viewHolder) -> {
                    if (type == Type.AGREEMENT_KSP) {
                        viewHolder.getTextView(R.id.dialog_policy_ksp_tv).setVisibility(View.VISIBLE);
                    }
                    UIHelper.bindClickListener((ViewGroup) viewHolder.getItemView(),
                            new OnNoShakeClickListener() {
                                @Override
                                public void onEventClick(View v) {
                                    if (v.getId() == R.id.dialog_policy_agreement_tv) {
                                        String agreement = Gateway.getAgreementPolicyUrl();
                                        if (DeviceInfo.isReviewMachine(context)) {
                                            agreement = "file:///android_asset/web/privacy.html?name=" + LibConfig.APP_NAME.replace(" ", "%20")
                                        }
                                        WebActivity.start(context, context.getString(R.string.login_statement_title), agreement);
                                    } else if (v.getId() == R.id.dialog_policy_ksp_tv) {
                                        String kspUrl = Gateway.getKSPUrl();
                                        if (DeviceInfo.isReviewMachine(context)) {
                                            kspUrl = "file:///android_asset/web/privacyKsp.html?name=" + LibConfig.APP_NAME.replace(" ", "%20")
                                        }
                                        WebActivity.start(context, context.getString(R.string.koperasi_form), kspUrl);
                                    } else if (v.getId() == R.id.dialog_policy_agree_tv) {
                                        viewHolder.getCheckBox(R.id.dialog_policy_checkbox).setChecked(true);
                                    } else if (v.getId() == R.id.dialog_policy_cancel_btn) {
                                        context.finish();
                                    } else if (v.getId() == R.id.dialog_policy_sure_btn) {
                                        if (!viewHolder.getCheckBox(R.id.dialog_policy_checkbox).isChecked()) {
                                            DialogFactory.showMessageDialog(context, context.getString(R.string.check_the_checkbox));
                                            return;
                                        }
                                        PreferencesManager.get().setPolicyStatus(true);
                                        PreferencesManager.get().setPolicyKSPStatus(true);
                                        TrackEventHelper.logEvent(TrackEvent.Click.AGREE_PRIVACY);
                                        dialog1.dismiss();
                                    }
                                }
                            }, R.id.dialog_policy_agreement_tv,
                            R.id.dialog_policy_ksp_tv,
                            R.id.dialog_policy_agree_tv,
                            R.id.dialog_policy_cancel_btn,
                            R.id.dialog_policy_sure_btn);
                });
        dialog.setOnDismissListener(dismissListener);
        dialog.setCancelable(false);
        dialog.show();
    }


    Type agreementType = Type.AGREEMENT_POLICY;

    public static void startForResult(FragmentActivity activity, Type type, int requestCode, EasyActivityResult.OnResultListener listener) {
        Intent intent = new Intent(activity, AgreementPolicyActivity.class);
        if (type != null) {
            intent.putExtra("agreementType", type);
        }
        new EasyActivityResult(activity).startForResult(intent, requestCode, listener);
    }

    public static void startForResult(FragmentActivity activity, int requestCode, EasyActivityResult.OnResultListener listener) {
        Intent intent = new Intent(activity, AgreementPolicyActivity.class);
        new EasyActivityResult(activity).startForResult(intent, requestCode, listener);
    }

    CheckBox mCheckBox;
    WebView webView;

    @Override
    public int bindLayout() {
        return R.layout.activity_policy;
    }

    @Override
    protected void initTopBar(TopBar topBar) {
        topBar.toolBar().setTitleGravity(Gravity.CENTER);
        topBar.toolBar().setTitle(R.string.login_statement_title);
    }

    @Override
    public void initView() {
        if (getIntent().getSerializableExtra("agreementType") != null) {
            agreementType = (Type) getIntent().getSerializableExtra("agreementType");
        }
        EventBus.getDefault().register(this);

        mCheckBox = findViewById(R.id.activity_policy_checkbox);
        webView = findViewById(R.id.activity_policy_webview);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不加载缓存
        WebStorage.getInstance().deleteAllData();//主动清除数据

        UIHelper.bindClickListener(getContentView(), new OnNoShakeClickListener() {
            @Override
            public void onEventClick(View v) {
                if (v.getId() == R.id.activity_policy_ok_btn) {
                    if (mCheckBox.isChecked()) {
                        PreferencesManager.get().setPolicyStatus(true);
                        PreferencesManager.get().setPolicyKSPStatus(true);
                        TrackEventHelper.logEvent(TrackEvent.Click.AGREE_PRIVACY);
                        setResult(RESULT_OK);
                        finish();
                        return;
                    } else {
                        DialogFactory.showMessageDialog(AgreementPolicyActivity.this, getString(R.string.check_the_checkbox));
                    }

                }
            }
        }, R.id.activity_policy_ok_btn);

        //KSP协议
//        if (agreementType == Type.AGREEMENT_KSP) {
//            TextView agreeTv = findViewById(R.id.activity_policy_agreement_tv);
//            String policy = getString(R.string.login_statement_title);
//            String ksp_form = getString(R.string.koperasi_form);
//            String agreeText = String.format(getString(R.string.i_agree_ksp_policy), policy, ksp_form);
//            UIHelper.setTextHighLight(agreeTv, agreeText, LibConfig.MAIN_COLOR, policy, ksp_form);
//
//            agreeTv.setOnClickListener(new OnNoShakeClickListener() {
//                @Override
//                public void onEventClick(View v) {
//                    DialogFactory.createMenuDialog(AgreementPolicyActivity.this, new String[]{policy, ksp_form},
//                            (dialog, which) -> {
//                                dialog.dismiss();
//                                if (which == 0) {
//                                    setTopBarTitle(policy);
//                                    loadPolicy();
//                                } else {
//                                    setTopBarTitle(ksp_form);
//                                    loadKspPolicy();
//                                }
//                            }).show();
//                }
//            });
//        }

        //本地协议
        if (agreementType == Type.AGREEMENT_HOOK) {
            webView.loadUrl("file:///android_asset/web/privacy.html?name=" + LibConfig.APP_NAME.replace(" ", "%20"));
            return;
        }

        loadPolicy();

    }

    private void loadKspPolicy() {
        webView.loadUrl(Gateway.getKSPUrl());
    }

    private void loadPolicy() {
        webView.loadUrl(Gateway.getAgreementPolicyUrl());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveLibAction(String actionEnum) {
        switch (actionEnum) {
            case ActionEnum.GATEWAY_UPDATED:
                webView.loadUrl(Gateway.getAgreementPolicyUrl());
                break;
        }
    }


    public void loadUrlWithParams(WebView webView, String url) {
        String[] urls = url.split("\\?");
        if (urls.length > 1) {
            String[] params = urls[1].split("&");

        }
    }

    @Override
    public void onHttpSuccess(String action, Object result) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
