package com.dlc.exam.ui.learn;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.dlc.exam.common.CommonUtils;
import com.dlc.exam.databinding.ActivityLearnDetailWebBinding;
import com.dlc.exam.ui.common.BaseCountDownActivity;
import com.dlc.exam.ui.learn.test.ClassTestActivity;
import com.dlc.exam.ui.widget.JsInterface;
import com.dlc.exam.ui.widget.MessageEvent;
import com.rc.core.util.EscapeUnescape;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.vo.request.ExamLearnReq;

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

import io.reactivex.disposables.Disposable;
import okhttp3.HttpUrl;

public class LearnDetailLibOfficeActivity extends BaseCountDownActivity<ActivityLearnDetailWebBinding> implements View.OnClickListener {

    private ActivityLearnDetailWebBinding binding;
    private LearnChapterBean learnChapterBean;
    private WebView webView;
    private boolean learnCompleted = false;// 是否已完成学习
    private long learnTimeSecond = 0L;

    @NonNull
    @Override
    protected ActivityLearnDetailWebBinding createViewBinding() {
        return ActivityLearnDetailWebBinding.inflate(LayoutInflater.from(this));
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);

        binding = getViewBinding();
        Intent getIntent = getIntent();
        if (null != getIntent && getIntent.hasExtra("Chapter")) {
            learnChapterBean = getIntent.getParcelableExtra("Chapter");
            boolean relearn = getIntent.getBooleanExtra("relearn", false);
            if (null == learnChapterBean) {
                finish();
                return;
            }
            binding.back.setOnClickListener(this);
            binding.titleText.setText(learnChapterBean.title);
            // 是否完成学习
            binding.learnCompleted.setVisibility(relearn ? View.GONE : View.VISIBLE);
            binding.learnCompleted.setOnClickListener(this);
            // 初始化WebView
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            webView = new WebView(getApplicationContext());
            webView.setLayoutParams(params);
            binding.mainLL.addView(webView);
            WebView.setWebContentsDebuggingEnabled(true);
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setSupportZoom(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setDomStorageEnabled(true);//DOM Storage
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setAllowContentAccess(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDefaultTextEncodingName("utf-8");
            webSettings.setJavaScriptEnabled(true);//设置webview支持javascript脚本
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webView.addJavascriptInterface(new JsInterface(), "Android");
            webView.setWebChromeClient(webChromeClient);
            webView.setWebViewClient(webViewClient);
            webView.requestFocus();
            // 富文本
            if ("5".equals(learnChapterBean.type)) {
                webView.loadDataWithBaseURL(null, EscapeUnescape.unescape(learnChapterBean.chapterData), "text/html", "utf-8", null);
            } else {
                String baseUrl = HttpConfig.Companion.getAPI_BASE_URL();
                HttpUrl httpUrl = HttpUrl.get(baseUrl);
                String libOfficeUrl = httpUrl.scheme() + "://" + httpUrl.host() + ":19999/";
                String chapterData = learnChapterBean.chapterData;
                if (!"http".startsWith(chapterData)) {
                    chapterData = HttpConfig.Companion.getAPI_BASE_URL() + learnChapterBean.chapterData;
                }
                webView.loadUrl(libOfficeUrl + "file_to_images/" + chapterData);
            }

        } else {
            finish();
        }
    }

    private final WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LogUtils.d("Jayce", url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);

            LogUtils.e("Jayce", error.getErrorCode(), error.getDescription());
        }
    };

    private final WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (ConsoleMessage.MessageLevel.ERROR == consoleMessage.messageLevel()) {
                LogUtils.e("Jayce", consoleMessage.message(), consoleMessage.lineNumber(), consoleMessage.sourceId());
            } else {
                if (consoleMessage.message().startsWith("status")) {
                    String[] statusArray = consoleMessage.message().split(" ", -1);
                    if (statusArray.length > 1) {
                        String code = statusArray[1];
                        if ("200".equals(code)) {
                            startLearn();
                        } else if ("400".equals(code)) {
                            Toast.makeText(LearnDetailLibOfficeActivity.this, "无法预览", Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }
                }
                LogUtils.d("Jayce", consoleMessage.message(), consoleMessage.lineNumber(), consoleMessage.sourceId());
            }
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.d("Jayce", "加载进度:" + newProgress);
        }

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
            String js = "javascript:objPreviewerDestroy()";
            webView.evaluateJavascript(js, value -> {
                LogUtils.d("Jayce", value);
            });
        }
    };

    /**
     * 完成学习
     */
    private void finishLearn() {
        showLoading("保存中...", false);
        ExamLearnReq examLearnReq = new ExamLearnReq();
        examLearnReq.chapterId = learnChapterBean.chapterId;
        examLearnReq.courseId = learnChapterBean.courseId;
        Disposable disposable = ApiRepository.INSTANCE.examLearnFinish(examLearnReq).subscribe(learnBonusBean -> {
            dismissLoading();
            LogUtils.json("Jayce", learnBonusBean);
            learnCompleted = true;
            new LearnCompletedDialog(LearnDetailLibOfficeActivity.this, learnBonusBean, false, learnChapterBean.assessStatus, () -> {
                binding.learnCompleted.setEnabled(false);
                // 课后考核
                if (learnChapterBean.assessStatus) {
                    Intent intent = new Intent(LearnDetailLibOfficeActivity.this, ClassTestActivity.class);
                    intent.putExtra("chapterId", learnChapterBean.chapterId);
                    startActivity(intent);
                    setResult(RESULT_OK);
                }
                finish();
                return null;
            }).show();
        }, throwable -> {
            dismissLoading();
            throwable.printStackTrace();
            showNetError(throwable);
        });
        addDisposable(disposable);
    }

    private Handler cdHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            learnTimeSecond++;
            binding.learnDuration.setText("已学习时长:" + CommonUtils.INSTANCE.formatLearnTime(learnTimeSecond));
            sendEmptyMessageDelayed(1, 1000);
            if (learnTimeSecond >= learnChapterBean.duration) {
                binding.learnCompleted.setEnabled(true);
            }
        }
    };

    private volatile boolean isStartLearn = false;

    /**
     * 开始学习
     */
    private void startLearn() {
        if (!isStartLearn) {
            showLoading("加载中...", false);
            ExamLearnReq examLearnReq = new ExamLearnReq();
            examLearnReq.chapterId = learnChapterBean.chapterId;
            examLearnReq.courseId = learnChapterBean.courseId;
            Disposable disposable = ApiRepository.INSTANCE.examLearnStart(examLearnReq).subscribe(aBoolean -> {
                isStartLearn = true;
                dismissLoading();
                learnTimeSecond = 0L;
                cdHandler.sendEmptyMessage(1);

            }, throwable -> {
                dismissLoading();
                throwable.printStackTrace();
                showNetError(throwable);
            });
            addDisposable(disposable);
        }
    }

    @Override
    protected void onPause() {
        webView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        webView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();
            binding.mainLL.removeAllViewsInLayout();
            webView.destroy();
            webView = null;
        }
        cdHandler.removeMessages(1);
        cdHandler.removeCallbacksAndMessages(null);
        cdHandler = null;
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (learnCompleted) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == binding.back.getId()) {
            onBackPressed();
        }
        // 完成学习
        else if (v.getId() == binding.learnCompleted.getId()) {
            learnTimeSecond = 0L;
            cdHandler.removeMessages(1);
            finishLearn();
        }
    }


}