package com.kfzs.duanduan;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

import com.kfzs.android.view.RunThreadUtils;
import com.kfzs.android.view.widget.SafeWebView;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.kfzs.duanduan.data.graph.provider.current.Current;
import com.kfzs.duanduan.datashare.DDProviderHelper;
import com.kfzs.duanduan.db.DataSave;
import com.kfzs.duanduan.utils.net.OnURLParseByJS;
import com.kfzs.duanduan.utils.ShareUtils;
import com.orhanobut.logger.Logger;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

/**
 * all web view
 * Created by HooRang on 2017/2/17.
 */
public class ActWeb extends BaseCompatActivity {

    public static final String BEHAVIOR_GAME_BOOK = "behavior:act:webView:game_book";

    public
    @BindView(R.id.tv_nav_label)
    TextView tvLabel;

    @BindView(R.id.activity_webview)
    SafeWebView mWebView;

    @BindView(R.id.ibtn_act_webview)
    ImageButton btnBack;

    @BindView(R.id.btn_share)
    ImageButton btnShare;

    private String extraUrl;
    private String shareUrl;
    private String extraTitle;
    private String extraGameBookID;
    private String extraGameID;
    private String behavior;
    private String extraShareImgUrl;
    private WebSettings webViewSettings;
    private OnURLParseByJS urlParseByJS;
    private String packageName;
    private String gameVer;
    private String gameSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        ButterKnife.bind(this);
        webViewSettings = mWebView.getSettings();
        webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.autoSettingWebViewDefaultByWideViewPort(this, false);
        behavior = getIntent().getStringExtra(KFIntentKeys.EXTRA_BEHAIOR);
        extraUrl = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_URL);
        extraTitle = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_TITLE);
        extraShareImgUrl = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_SHARE_IMGURL);
        extraGameID = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_GAME_ID);
        extraGameBookID = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_GAME_BOOK_ID);
        packageName = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_PACKAGENAME);
        gameVer = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_GAME_VERSION);
        gameSize = getIntent().getStringExtra(KFIntentKeys.EXTRA_WEBVIEW_GAME_SIZE);
        if (getIntent().hasExtra(EXTRA_WEBVIEW_NO_TITLE)) {//不显示标题
            findViewById(R.id.appbar_act_webview).setVisibility(View.GONE);
        }


        mWebView.addJavascriptInterface(new PublicJavaScript(), "PublicJavaScript");
        urlParseByJS = new JSCallFilter();
        filterURLByBehavior();
        loadUrl();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webViewSettings.setJavaScriptEnabled(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        webViewSettings.setJavaScriptEnabled(false);
    }

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

    private void loadUrl() {
        tvLabel.setText(extraTitle);
        Logger.d("loadUrl: " + extraUrl);
        //        extraUrl = "http://app.haowan.yunduanzs.cn/static/index.html?type=android&dd_channel=family&gamebookid=21&gameid=132#/";
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            boolean once = true;

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    if (filterURLByJS(url, "openActivity"))
                        return true;

                    if (url.contains(".apk") && !url.contains("channel") && once) {
                        // 创建下载请求
                        once = false;
                        setUmengOnEvent(extraTitle);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.addCategory(Intent.CATEGORY_BROWSABLE);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);


//                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//                        request.setTitle(extraTitle);
//                        request.setDescription("文件下载中...");
//                        File saveFile = new File(Environment.getExternalStorageDirectory(), extraTitle + ".apk");
//                        request.setDestinationUri(Uri.fromFile(saveFile));
//                        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//                        long downloadId = manager.enqueue(request);
//
//                        FileDownloader.start(url);
//
//                        DownLoadInfo task = new DownLoadInfo();
//                        task.setMIconUrl(extraShareImgUrl);
//                        task.setMGameName(extraTitle);
//                        task.setMGameID(Integer.valueOf(extraGameID));
//                        task.setMDownloadUrl(url);
//                        task.setMPackageName(packageName);
//                        task.setMVersionCode(Integer.parseInt(TextUtils.isEmpty(gameVer) ? "1.0" : gameVer));
//                        task.setMTotalSize(Double.valueOf(gameSize));
//                        downloadTaskService.addDownloadTask(task);
//
//                        EventBus.getDefault().post(BigEvent.get()
//                                .setEventTypes(EventTypes.TIPS_DOWN_ICON));
//
//                        startActivity(new Intent(ActWeb.this, ActDownloadMgr.class));
//                        ActWeb.this.finish();
                        return true;
                    }
                    view.loadUrl(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        mWebView.loadUrl(extraUrl);
    }


    private void setUmengOnEvent(String extInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("gameUnique", extInfo);
        MobclickAgent.onEvent(ActWeb.this, UMConfigUtils.Event.GAME_DOWNLOAD.getKey(), map);
    }


    private void filterURLByBehavior() {
        Logger.d("extraGameID: " + extraGameID + " |extraGameBookID: " + extraGameBookID);
        String channelName = DataSave.getInstance().getChannelName();
        if (TextUtils.equals(behavior, BEHAVIOR_GAME_BOOK)) {
            shareUrl = extraUrl + "?type=share&dd_channel=" + channelName;
            extraUrl = extraUrl + "?type=android&dd_channel=" + channelName;
            if (!TextUtils.isEmpty(extraGameID) && !TextUtils.isEmpty(extraGameBookID)) {
                extraUrl = extraUrl + "&gamebookid=" + extraGameBookID + "&gameid=" + extraGameID;
                shareUrl = shareUrl + "&gamebookid=" + extraGameBookID + "&gameid=" + extraGameID;
            } else {
                showToast("订阅游戏参数错误\nbehavior: " + behavior + "\nGameID: " + extraGameID + "\nGameBookID: " + extraGameBookID);
                ActWeb.this.finish();
            }
        }
        filterShareBtn();
    }

    private void filterShareBtn() {
        if (TextUtils.equals(behavior, BEHAVIOR_GAME_BOOK)) {
            btnShare.setVisibility(View.VISIBLE);
        } else {
            btnShare.setVisibility(View.GONE);
        }
    }

    private boolean filterURLByJS(String url, String router) {
        Uri uri = Uri.parse(url);
        String scheme = uri.getScheme();
        if (scheme.equals("js")) {
            if (uri.getAuthority().equals(router)) {
                Set<String> collection = uri.getQueryParameterNames();
                if (urlParseByJS != null) {
                    String who = "";
                    String where = "";
                    String doJob = "";
                    for (String name : collection) {
                        if (name.equals("who")) {
                            who = uri.getQueryParameter(name);
                        }
                        if (name.equals("where")) {
                            where = uri.getQueryParameter(name);
                        }
                        if (name.equals("do")) {
                            doJob = uri.getQueryParameter(name);
                        }
                    }
                    urlParseByJS.whoWhereDo(who, where, doJob);
                }
            }
            return true;
        }
        return false;
    }

    @OnClick({R.id.ibtn_act_webview, R.id.btn_share})
    public void onClick(View v) {
        int resId = v.getId();
        switch (resId) {
            case R.id.ibtn_act_webview:
                onBackPressed();
                //                this.finish();
                break;
            case R.id.btn_share:
                popShare();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (KFZSApp.actMain == null) {
            Intent intent = new Intent(this, ActMain.class);
            startActivity(intent);
        }
        this.finish();
    }

    private void popShare() {
        Logger.d("now share url: " + shareUrl);
        if (!TextUtils.isEmpty(shareUrl) && shareUrl.toLowerCase().startsWith("http")) {
            new ShareUtils().showShareView(this, shareUrl, extraTitle, extraShareImgUrl, extraTitle);
        } else {
            String msg = "分享错误，请联系客服!\n错误链接为: " + shareUrl;
            Log.w("DD_ERROR", msg);
            showToast(msg);
        }
    }

    private class JSCallFilter implements OnURLParseByJS {

        private static final String WHO_WEB = "1";
        private static final String WHERE_CLOSE_SELF = "11";
        private static final String WHERE_BOOK_GAME = "22";

        @Override
        public void whoWhereDo(String who, String where, String doJob) {
            Logger.d("who:" + who + " |where:" + where + " |doJob:" + doJob);
            switch (who) {
                case WHO_WEB:
                    switch (where) {
                        case WHERE_BOOK_GAME:
                            skip2GameDetails(doJob, true);
                            break;
                        case WHERE_CLOSE_SELF:
                            showInfoAndCloseSelf("");
                            break;
                        default:
                            showInfoAndCloseSelf("异常Web行为,关闭Web");
                            break;
                    }
                    break;
                default:
                    showInfoAndCloseSelf("异常Web对象,关闭Web");
                    break;
            }
        }
    }


    public class PublicJavaScript {
        @JavascriptInterface
        public String getHeader() {
            return DDProviderHelper.getInstance().getLastUserToken(KFZSApp.context);
        }
        @JavascriptInterface
        public String getNick() {
            Current current= DDProviderHelper.getInstance().getLastUser(ActWeb.this);
            if(current==null || TextUtils.isEmpty(current.getMNickName())){
                return "";
            }

            return current.getMNickName();
        }

        @JavascriptInterface
        public void finish() {
            ActWeb.this.finish();
        }
    }

    private void showInfoAndCloseSelf(String msg) {
        Logger.d(msg);
        if (!TextUtils.isEmpty(msg)) {
            showToast(msg);
        }
        RunThreadUtils.delay(new Runnable() {
            @Override
            public void run() {
                ActWeb.this.finish();
            }
        }, 100, true);
    }

    private void skip2GameDetails(String doJob, boolean bRequestOrder) {
        Bundle bundle = new Bundle();
        bundle.putString(KFIntentKeys.EXTRA_GAME_ID, doJob);
        if (bRequestOrder) {
            bundle.putString(KFIntentKeys.EXTRA_GAME_REQUEST_ORDER, doJob);
        }
        skip2Activity(ActGameDetails.class, bundle);
        this.finish();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


}
