package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.sheep.gamegroup.absBase.BaseActivity;
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.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Locale;

import butterknife.BindView;
import okhttp3.Call;


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

public class ActXianWanWeb extends BaseActivity {
    @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 int getLayoutId() {
        return R.layout.activity_guide_on_hook;
    }

    @Override
    public void initView() {
        activity = this;

        xianWanEntity = (XianWanEntity) getIntent().getSerializableExtra("xianwan_enty");
        TitleBarUtils
                .getInstance()
                .setShowOrHide(this, true)
                .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);
        }
        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();
        if(mWebView != null) {
            mWebView.setVisibility(View.GONE);
            mWebView.removeAllViews();
            mWebView.destroy();
        }
    }

    private void loadUrl() {
        if(mWebView == null){
            return;
        }
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                TitleBarUtils
                        .getInstance()
                        .setTitle(activity, title.replaceAll("任务", "奖励"));
            }
        });
        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(), "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 != null && mWebView.canGoBack()){
            mWebView.goBack();
            return;
        }
        this.finish();
    }
    // 注入js函数监听
    public void loadJs() {
        ViewUtil.loadJs(mWebView, 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 baseUrl = xianWanEntity.getUrl();
        int pType = 2;
        String deviceId = DeviceIDUtil.getimei(activity);
        String appId =  xianWanEntity.getAndroid().getAppid();
        String userId = DataUtil.getInstance().getUserId();
        String appSecret = xianWanEntity.getAndroid().getAppsecret();
        String keyCodeBefore = String.format(Locale.CHINA, "%s%s%d%s%s", appId, deviceId, pType, userId, appSecret);
        String keyCode = CommonUtil.getInstance().encrypt2Md5(keyCodeBefore);
        return String.format(Locale.CHINA, "%s?ptype=%d&deviceid=%s&appid=%s&appsign=%s&keycode=%s", baseUrl, pType, deviceId, appId, userId, keyCode);
    }
}
