package io.openim.android.ouigroup.ui;


import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.entity.LoginCertificate;
import io.openim.android.ouicore.utils.Common;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.Routes;
import io.openim.android.ouicore.vm.GroupVM;
import io.openim.android.ouigroup.databinding.ActivityGroupQrCodeBinding;
import io.openim.android.sdk.models.GroupInfo;

/**
 * 我的二维码
 */
@Route(path = Routes.Group.SHARE_QRCODE)
public class ShareQrcodeActivity extends BaseActivity<GroupVM, ActivityGroupQrCodeBinding> {

    public static final String IS_QRCODE = "is_qrcode";
    private Bitmap qrCodeBitmap;
    private String tips;
    private boolean isGroup = false;
    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/HiChat";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        bindVMByCache(GroupVM.class);
        super.onCreate(savedInstanceState);
        bindViewDataBinding(ActivityGroupQrCodeBinding.inflate(getLayoutInflater()));
        boolean isQrcode = getIntent().getBooleanExtra(IS_QRCODE, true);
        String shareContent;
        if (null == vm) {
            isGroup = false;
            //这里表示个人二维码分享 个人信息复制给群信息用于显示
            bindVM(GroupVM.class);
            LoginCertificate loginCertificate = LoginCertificate.getCache(this);
            shareContent = Constants.QR.QR_ADD_FRIEND + "/" + loginCertificate.userID;
            GroupInfo groupInfo = new GroupInfo();
            groupInfo.setGroupName(loginCertificate.nickname);
            groupInfo.setFaceURL(loginCertificate.faceURL);
            vm.groupsInfo.setValue(groupInfo);
            view.userId.setText("ID：" + loginCertificate.userID);
            tips = getString(io.openim.android.ouicore.R.string.qr_tips2);
            view.title.setText(io.openim.android.ouicore.R.string.qr_code);
            view.tips.setText(tips);
            isGroup(false);
        } else {
            isGroup = true;
            isGroup(true);
            shareContent = Constants.QR.QR_JOIN_GROUP + "/" + vm.groupId;
            if (isQrcode) {
                view.title.setText("");
                tips = getString(io.openim.android.ouicore.R.string.share_group_tips2);
            } else {
                view.title.setText(io.openim.android.ouicore.R.string.group_id);
                tips = getString(io.openim.android.ouicore.R.string.share_group_tips1);
            }
            view.tips2.setText(tips);
            view.name.setText(getString(io.openim.android.ouicore.R.string.group_chat) + vm.groupsInfo.getValue().getGroupName());
        }
        sink();
        view.setGroupVM(vm);

//        if (isQrcode) {
//            bindData(shareContent);
//        } else {
//            view.qrCodeRl.setVisibility(View.GONE);
//        }
        view.save.setOnClickListener(v -> {
            String filePath = PathUtils.getExternalPicturesPath() + "/" + TimeUtils.getNowMills() + ".png";
            boolean success = ImageUtils.save(qrCodeBitmap, filePath, Bitmap.CompressFormat.PNG);
            if (success) {
                MediaScannerConnection.scanFile(this,
                        new String[]{filePath}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                // 扫描完成的回调，可以在这里进行逻辑处理
                            }
                        });
                toast(getString(io.openim.android.ouicore.R.string.save_succ));
            }
        });
        vm.groupsInfo.observe(this, groupInfo -> {
            bindData(shareContent);
        });
    }

    private void isGroup(boolean isGroup) {
        view.layout.setBackgroundColor(isGroup ? Color.WHITE : Color.parseColor("#F8F9FB"));
        view.titleLayout.setCardBackgroundColor(isGroup ? Color.WHITE : Color.parseColor("#F8F9FB"));
        view.slPerson.setVisibility(isGroup ? View.GONE : View.VISIBLE);
        view.llGroup.setVisibility(isGroup ? View.VISIBLE : View.GONE);
    }

    private void bindData(String shareContent) {
        try {
            if (isGroup) {
                view.avatar2.load(vm.groupsInfo.getValue().getFaceURL(), true,vm.groupsInfo.getValue().getGroupName());
            } else {
                view.avatar.load(vm.groupsInfo.getValue().getFaceURL(),vm.groupsInfo.getValue().getGroupName());
            }
            Glide.with(BaseApp.inst())
                    .asBitmap() //必须
                    .load(vm.groupsInfo.getValue().getFaceURL())
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            qrCodeBitmap = createQRCode(shareContent, Common.dp2px(240), Common.dp2px(240), resource);
                            if (isGroup) {
                                view.qrCode2.setImageBitmap(qrCodeBitmap);
                            } else {
                                view.qrCode.setImageBitmap(qrCodeBitmap);
                            }
                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);
                            Drawable pic = ResourceUtils.getDrawable(isGroup ? io.openim.android.ouicore.R.mipmap.ic_my_group : io.openim.android.ouicore.R.mipmap.ic_user_avatar_default);
                            qrCodeBitmap = createQRCode(shareContent, Common.dp2px(240), Common.dp2px(240), ConvertUtils.drawable2Bitmap(pic));
                            if (isGroup) {
                                view.qrCode2.setImageBitmap(qrCodeBitmap);
                            } else {
                                view.qrCode.setImageBitmap(qrCodeBitmap);
                            }
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                        }
                    });

        } catch (Exception E) {
            E.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != qrCodeBitmap)
            qrCodeBitmap.recycle();
    }

    /*生成二维码*/
    public static Bitmap createQRCode(String content, int w, int h, Bitmap logo) {


        if (TextUtils.isEmpty(content)) {
            return null;
        }
        /*偏移量*/
        int offsetX = w / 2;
        int offsetY = h / 2;

        /*生成logo*/
        Bitmap logoBitmap = null;

        if (logo != null) {
            Matrix matrix = new Matrix();
            float scaleFactor = Math.min(w * 1.0f / 5 / logo.getWidth(), h * 1.0f / 5 / logo.getHeight());
            matrix.postScale(scaleFactor, scaleFactor);
            logoBitmap = Bitmap.createBitmap(logo, 0, 0, logo.getWidth(), logo.getHeight(), matrix, true);
        }


        /*如果log不为null,重新计算偏移量*/
        int logoW = 0;
        int logoH = 0;
        if (logoBitmap != null) {
            logoW = logoBitmap.getWidth();
            logoH = logoBitmap.getHeight();
            offsetX = (w - logoW) / 2;
            offsetY = (h - logoH) / 2;
        }

        /*指定为UTF-8*/
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //容错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置空白边距的宽度
        hints.put(EncodeHintType.MARGIN, 0);
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = null;
        try {
            matrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, w, h, hints);

            // 二维矩阵转为一维像素数组,也就是一直横着排了
            int[] pixels = new int[w * h];
            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    if (x >= offsetX && x < offsetX + logoW && y >= offsetY && y < offsetY + logoH) {
                        int pixel = logoBitmap.getPixel(x - offsetX, y - offsetY);
                        if (pixel == 0) {
                            if (matrix.get(x, y)) {
                                pixel = 0xff000000;
                            } else {
                                pixel = 0xffffffff;
                            }
                        }
                        pixels[y * w + x] = pixel;
                    } else {
                        if (matrix.get(x, y)) {
                            pixels[y * w + x] = 0xff000000;
                        } else {
                            pixels[y * w + x] = 0xffffffff;
                        }
                    }
                }
            }

            Bitmap bitmap = Bitmap.createBitmap(w, h,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
            return bitmap;


        } catch (WriterException e) {

            System.out.print(e);
            return null;
        }


    }
}
