package com.cooleshow.base.ui.activity.scan;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.R;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.ScanContract;
import com.cooleshow.base.databinding.ActivityScanLayoutBinding;
import com.cooleshow.base.presenter.ScanPresenter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.PermissionUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.helper.GlideEngine;
import com.cooleshow.base.widgets.DialogUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * Author by pq, Date on 2022/7/11.
 */
@Route(path = RouterPath.BaseCenter.SCAN_QR_CODE)
public class ScanActivity extends BaseMVPActivity<ActivityScanLayoutBinding, ScanPresenter> implements ScanContract.ScanView, CodeUtils.AnalyzeCallback, View.OnClickListener {
    public static final int SELECT_IMG_REQUEST_CODE = 1001;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "扫码登录");
        viewBinding.toolbarInclude.tvRight.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRight.setImageResource(R.drawable.icon_scan_by_photo_album);
        viewBinding.toolbarInclude.tvRight.setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
        checkCameraPermission();
    }

    private void initQrScan() {
        /**
         * 执行扫面Fragment的初始化操作
         */
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);

        captureFragment.setAnalyzeCallback(this);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    @Override
    protected ActivityScanLayoutBinding getLayoutView() {
        return ActivityScanLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected ScanPresenter createPresenter() {
        return new ScanPresenter();
    }

    @Override
    public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
        LogUtils.i("pq", "解析成功:" + result);
        LogUtils.i("pq", "解析成功mBitmap:" + mBitmap);
        parseResult(result);
    }

    private void parseResult(String result) {
        if (TextUtils.isEmpty(result)) {
            return;
        }
        if (!checkUrlIsEnable(result)) {
            ToastUtil.getInstance().showShort("请扫描酷乐秀二维码");
            return;
        }
        ARouter.getInstance()
                .build(RouterPath.WebCenter.ACTIVITY_HTML)
                .withString(WebConstants.WEB_URL, result)
                .navigation();
    }

    @Override
    public void onAnalyzeFailed() {
        ToastUtil.getInstance().showShort("解析失败");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_right) {
            //去图库选择图片
            addPermissions();
        }
    }

    private void checkCameraPermission() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission) {
                        initQrScan();
                    } else {
                        DialogUtil.showInCenter(getSupportFragmentManager(), com.cooleshow.base.R.layout.common_popu, (holder, dialog) -> {
                            TextView tvTitle = holder.getView(com.cooleshow.base.R.id.tv_title);
                            TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                            TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                            TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                            tvTitle.setText("提示");
                            tvContent.setText("扫描二维码需要相机权限，去设置？");
                            btncancel.setOnClickListener(view1 -> {
                                dialog.dismiss();
                            });
                            btnCommit.setOnClickListener(view1 -> {
                                PermissionUtils.toSelfSetting(this);
                                dialog.dismiss();
                            });
                        });
                    }
                });
    }

    private void addPermissions() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .imageEngine(GlideEngine.createGlideEngine())
                                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R .style.picture.white.style
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .enableCrop(false)// 是否裁剪 true or false
                                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                                .compress(true)// 是否压缩 true or false
                                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        DialogUtil.showInCenter(getSupportFragmentManager(), com.cooleshow.base.R.layout.common_popu, (holder, dialog) -> {
                            TextView tvTitle = holder.getView(com.cooleshow.base.R.id.tv_title);
                            TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                            TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                            TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                            tvTitle.setText("提示");
                            tvContent.setText("选择照片需要相机、储存权限，去设置？");
                            btncancel.setOnClickListener(view1 -> {
                                dialog.dismiss();
                            });
                            btnCommit.setOnClickListener(view1 -> {
                                PermissionUtils.toSelfSetting(this);
                                dialog.dismiss();
                            });
                        });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                String avatar = selectList.get(0).getCompressPath();
                try {
                    CodeUtils.analyzeBitmap(avatar, new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            ToastUtil.getInstance().showShort("解析成功");
                            parseResult(result);
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            ToastUtil.getInstance().showShort("解析二维码失败");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean checkUrlIsEnable(String url) {
        if (url.contains("colexiu")) {
            return true;
        }
        return false;
    }
}
