package com.common.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
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.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.common.base.BaseActivity;

import tech.starwin.utils.context_utils.DeviceUtils;
import tech.starwin.utils.tracker.TrackEvent;
import com.common.widget.TopBar;

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

import java.io.Serializable;

import tech.starwin.BuildConfig;
import tech.starwin.LibConfig;
import tech.starwin.R;
import tech.starwin.constants.ActionEnum;
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;

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

    /**
     * 注册协议和隐私政策
     */
    public static String getLocalPolicy() {
        String permissions = BuildConfig.NEED_CONTACT ? "12356" : "2356";
        return "file:///android_asset/web/privacy.html?name=" + LibConfig.APP_NAME.replace(" ", "%20") + "&list=" + permissions;
    }

    /**
     * 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) -> {
                    String agreement = context.getString(R.string.login_statement_title);
                    String text = String.format(context.getString(R.string.click_to_read), agreement);
                    UIHelper.setTextHighLight(viewHolder.getTextView(R.id.dialog_policy_agreement_tv), text, R.color.color_blue, agreement);

//                    String collet_desc = context.getString(R.string.text_collect_desc);
//                    UIHelper.setTextHighLight(viewHolder.getTextView(R.id.dialog_policy_desc_tv),collet_desc,R.color.color_blue,"Contact, Location, Camera, Storage","Contact list, Location information");
                    if (type == Type.AGREEMENT_KSP) {
                        agreement = context.getString(R.string.koperasi_form);
                        text = String.format(context.getString(R.string.click_to_read), agreement);
                        UIHelper.setTextHighLight(viewHolder.getTextView(R.id.dialog_policy_ksp_tv), text, R.color.color_blue, agreement);
                        viewHolder.getTextView(R.id.dialog_policy_ksp_tv).setVisibility(View.VISIBLE);
                    }
                    viewHolder.getCheckBox(R.id.dialog_policy_checkbox).setOnCheckedChangeListener((buttonView, isChecked) -> {
                        if (isChecked) {
                            viewHolder.getButton(R.id.dialog_policy_sure_btn).setTextColor(context.getResources().getColor(R.color.color_blue));
                        } else {
                            viewHolder.getButton(R.id.dialog_policy_sure_btn).setTextColor(context.getResources().getColor(R.color.qmui_config_color_gray_5));
                        }
                    });

                    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 (DeviceUtils.getInstance().isReviewMachine(context)) {
                                            agreement = getLocalPolicy();
                                        }
                                        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 (DeviceUtils.getInstance().isReviewMachine(context)) {
                                            kspUrl = "file:///android_asset/web/privacyKsp.html";
                                        }
                                        WebActivity.start(context, context.getString(R.string.koperasi_form), kspUrl);
                                    } else if (v.getId() == R.id.dialog_policy_agree_tv) {
                                        CheckBox checkBox = viewHolder.getCheckBox(R.id.dialog_policy_checkbox);
                                        checkBox.setChecked(!checkBox.isChecked());
                                    } 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() {
        TrackEventHelper.logEvent(TrackEvent.Screen.AGREEMENT);
        EventBus.getDefault().register(this);

        mCheckBox = findViewById(R.id.activity_policy_checkbox);
        Button button = findViewById(R.id.activity_policy_ok_btn);
        mCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                button.setBackgroundResource(R.drawable.shape_mainsolid_round);
            } else {
                button.setBackgroundColor(getResources().getColor(R.color.qmui_config_color_gray_5));
            }
        });

        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();//主动清除数据

        loadPolicy();

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

                }
            }
        }, R.id.activity_policy_ok_btn);

        //KSP协议
        if (BuildConfig.IS_HOST_APP) {
            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) {
                                    TrackEventHelper.logEvent(TrackEvent.Click.VIEW_NORMAL_AGREEMENT);
                                    setTopBarTitle(policy);
                                    loadPolicy();
                                } else {
                                    TrackEventHelper.logEvent(TrackEvent.Click.VIEW_KSP_AGREEMENT);
                                    setTopBarTitle(ksp_form);
                                    loadKspPolicy();
                                }
                            }).show();
                }
            });
        }



    }

    private void loadKspPolicy() {
        if(DeviceUtils.getInstance().isReviewMachine(this)){
            webView.loadUrl("file:///android_asset/web/privacyKsp.html");
        }else{
            webView.loadUrl(Gateway.getKSPUrl());
        }
    }

    private void loadPolicy() {
        if(DeviceUtils.getInstance().isReviewMachine(this)){
            webView.loadUrl(getLocalPolicy());
        }else{
            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);
    }
}
