package xn.xxp.main.rule;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.bumptech.glide.Glide;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;

import core.ui.activity.BaseCountDownActivity;
import core.util.FastClickDelegate;
import http.net.DownloadHelper;
import http.vo.response.SafeBook;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import xn.xxp.R;
import xn.xxp.databinding.ActivityRuleDetailBinding;
import xn.xxp.utils.QrTool;
import xn.xxp.utils.Tool;
import xn.xxp.widget.ITitleBar;
import xn.xxp.widget.NavViewCompat;

public class RuleDetailActivity extends BaseCountDownActivity<ActivityRuleDetailBinding> {

    private ActivityRuleDetailBinding binding;
    private SafeBook safeBook;
    private DownloadHelper downloadHelper;

    @Override
    public ITitleBar getMTitleBar() {
        return null;
    }

    @Override
    public NavViewCompat getMNavView() {
        return null;
    }

    @Override
    protected ActivityRuleDetailBinding createViewBinding() {
        return binding = ActivityRuleDetailBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        Intent getIntent = getIntent();
        if (null != getIntent) {
            safeBook = (SafeBook) getIntent.getSerializableExtra("data");
        }

        binding.homeLayout.setOnClickListener(new FastClickDelegate(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {
                logoutCountDownFinish();
                return null;
            }
        }));
        binding.backLayout.setOnClickListener(new FastClickDelegate(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {
                finish();
                return null;
            }
        }));

    }

    @Override
    protected void initData() {
        super.initData();
        if (null == safeBook || TextUtils.isEmpty(safeBook.content)) {
            showToast("无法预览,请重新上传文件!");
            finish();
            return;
        }
        binding.titleText.setText(TextUtils.isEmpty(safeBook.name) ? "" : safeBook.name);
        showLoading("加载中...");
        downloadHelper = new DownloadHelper(this);
        downloadHelper.startDownload(safeBook.content, "pdf.pdf", 3399, new DownloadHelper.DownloadCallback() {
            @Override
            public void onProgress(int progress, long downloadedBytes, long totalBytes) {

            }

            @Override
            public void onSuccess(Uri fileUri) {
                dismissLoading();
                try {
                    binding.pdfView.fromUri(fileUri)
                            .defaultPage(0) // 默认显示第一页
                            .enableSwipe(true) // 允许滑动翻页
                            .swipeHorizontal(false) // 垂直滑动
                            .enableDoubletap(true) // 双击缩放
                            .onLoad(nbPages -> {
                                // 加载完成回调
                                showToast("加载完成!");
                            })
                            .onPageScroll((page, positionOffset) -> {
                                // 页面滚动监听
                            })
                            .onError(error -> { // 加载错误处理
                                showToast("加载错误:" + error.getMessage());
                                LogUtils.e(Log.getStackTraceString(error));
                            })
                            .enableAnnotationRendering(true) // 渲染注释
                            .password(null) // PDF密码（如果有）
                            .scrollHandle(new DefaultScrollHandle(RuleDetailActivity.this)) // 滚动条
                            .load();
                } catch (Exception e) {
                    LogUtils.e(Log.getStackTraceString(e));
                    showNetError(e);
                }

            }

            @Override
            public void onFailure(int reason) {
                showToast("下载文件异常:" + reason + ",请重新上传文件!");
                dismissLoading();
            }

            @Override
            public void onPaused() {

            }

            @Override
            public void onCancelled() {

            }
        });

        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() {
            @Override
            public Bitmap doInBackground() throws Throwable {
                return QrTool.generateQRCode(safeBook.realContent, Tool.INSTANCE.dip2px(150f));
            }

            @Override
            public void onSuccess(Bitmap result) {
                if (!isDestroyed()) {
                    Glide.with(binding.qrCode).asBitmap().load(result).error(R.mipmap.img_error).into(binding.qrCode);
                }
            }
        });
    }

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

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

    @Override
    protected void onDestroy() {
        if (null != downloadHelper) {
            downloadHelper.cancelDownload(3399);
            downloadHelper.release();
        }
        super.onDestroy();
    }

    @Override
    protected boolean enabledBackCountDown() {
        return true;
    }
}