package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import android.widget.TextView;

import com.kfzs.duanduan.BaseCompatActivity;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.XianWanEntity;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DeviceIDUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.WebviewJs;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.kfzs.duanduan.bean.KFIntentKeys.EXTRA_WEBVIEW_NO_TITLE;

/**
 * 闲玩
 * Created by ljy on 2018/6/25.
 */

public class ActXinwanWeb extends BaseCompatActivity {
    @BindView(R.id.webview)
    WebView mWebView;
    @BindView(R.id.tv_next)
    TextView tv_next;

    private WebSettings webViewSettings;
    private Activity activity;
    private XianWanEntity xianWanEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_on_hook);
        activity = this;

        xianWanEntity = (XianWanEntity) getIntent().getSerializableExtra("xianwan_enty");

        ButterKnife.bind(this);
        TitleBarUtils
                .getInstance()
                .setTitle(this, "闲玩")
                .setTitleFinish(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(mWebView.canGoBack()){
                            mWebView.goBack();
                        }else {
                            activity.finish();
                        }
                    }
                })
                .setRightImgBotton(activity, R.mipmap.question_black_img, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("温馨提示").setBtnLeftText("我知道了")
                                .setMsg("该栏目为现金任务，不参与好友提成。"));
                    }
                });
        tv_next.setVisibility(View.GONE);
        if(xianWanEntity == null){
            return;
        }

        webViewSettings = mWebView.getSettings();
        webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webViewSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (getIntent().hasExtra(EXTRA_WEBVIEW_NO_TITLE)) {//不显示标题
            findViewById(R.id.appbar_act_webview).setVisibility(View.GONE);
        }
        initJsData();
    }

    private void initJsData() {
        OkHttpUtils.get()
                .url(xianWanEntity.getJsUrl()+"")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        G.showToast( R.string.service_data_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        js = response;
                        loadUrl();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.setVisibility(View.GONE);
        mWebView.removeAllViews();
        mWebView.destroy();
    }

    private void loadUrl() {
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                TitleBarUtils
                        .getInstance()
                        .setTitle(activity, title);
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    view.loadUrl(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadJs();
//                loadTestJs();
            }
        });
        webViewSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new WebviewJs(activity, 0), "android");
        mWebView.loadUrl(assemblyData());

        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()){
                    mWebView.goBack();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()){
            mWebView.goBack();
            return;
        }
        this.finish();
    }
    // 注入js函数监听
    public void loadJs() {
        mWebView.loadUrl("javascript:"+getJs());
    }
    private String js;
    private String getJs(){
        return js;
    }

    /**
     * 组装数据
     * @return
     * https://h5.51xianwan.com/try/try_list_plus_browser.aspx?ptype=2&deviceid=8883300242xw&appid=1010&appsign=1000&keycode=07688c3e9a783b245e59311
     */
    private String assemblyData(){
        String userId = DataUtil.getInstance().getUserId();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(xianWanEntity.getUrl()+"?");
        stringBuffer.append("ptype="+"2");
        stringBuffer.append("&deviceid="+ DeviceIDUtil.getimei(activity));
        stringBuffer.append("&appid="+ xianWanEntity.getAndroid().getAppid());
        stringBuffer.append("&appsign="+ userId);
        stringBuffer.append("&keycode="+CommonUtil.getInstance().encrypt2Md5(
                xianWanEntity.getAndroid().getAppid()+""+
                        DeviceIDUtil.getimei(activity) +
                        2 +
                        userId +
                        xianWanEntity.getAndroid().getAppsecret()
        ));
        return stringBuffer.toString();
    }
}
