package com.example.chemical.ui.verify;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.example.chemical.ChemicalApp;
import com.example.chemical.R;
import com.example.chemical.databinding.ActivityDoubleVerifyBinding;
import com.example.chemical.receiver.OnSerialScanListener;
import com.example.chemical.receiver.PortScanHelper;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import com.example.chemical.ui.verify.include.DetectType;
import com.example.chemical.ui.verify.include.FaceDetectView;
import com.example.chemical.utils.AudioPlayer;
import com.example.chemical.utils.TimesUils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lztek.toolkit.Lztek;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.UserValidationBean;
import com.rc.httpcore.client.HttpTool;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kotlin.Triple;
import okhttp3.Response;

public class DoubleVerifyActivityHelp {
    private DoubleVerifyActivity activity;
    private ActivityDoubleVerifyBinding binding;
    private String qrScanTime;
    /**
     * 验证通过的人信息
     */
    private UserValidationBean userValidation1, userValidation2;

    public void onDestroy() {
        if (null != qrTimer) {
            qrTimer.cancel();
            qrTimer = null;
        }

    }

    public DoubleVerifyActivityHelp(DoubleVerifyActivity activity) {
        this.activity = activity;
        binding = activity.binding;

        activity.portScanHelper = new PortScanHelper(activity, new OnSerialScanListener() {
            @Override
            public void dispatchScanEvent(@NonNull ScanType type, @NonNull String content) {
                boolean isCard = RegexUtils.isMatch("^[-+]?\\d+$", content);
                if (isCard) {
                    List<HxpCabinetDoorVo> planAddDataDoorList = activity.planAddData.getDoorList();
                    List<String> doorIdList = new ArrayList<>();
                    if (null != planAddDataDoorList && !planAddDataDoorList.isEmpty()) {
                        for (int i = 0; i < planAddDataDoorList.size(); i++) {
                            doorIdList.add(String.valueOf(planAddDataDoorList.get(i).getDoorUniqueId()));
                        }
                    }
                    ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<UserValidationBean>() {
                        @Override
                        public UserValidationBean doInBackground() throws Throwable {
                            try {
                                Response response = HttpTool.useCardVerify1(content, ChemicalApp.subjectId, doorIdList);
                                if (response.isSuccessful()) {
                                    String json = response.body().string();
                                    JSONObject jsonObject = new JSONObject(json);
                                    int code = jsonObject.getInt("code");
                                    if (200 == code) {
                                        return GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), UserValidationBean.class);
                                    } else {
                                        PopTip.show(jsonObject.getString("message"));
                                    }
                                } else {
                                    PopTip.show(response.message());
                                }
                            } catch (IOException e) {
                                LogUtils.e(Log.getStackTraceString(e));
                            }

                            return null;
                        }

                        @Override
                        public void onSuccess(UserValidationBean result) {
                            if (null != result) {
                                verifyProcess(result);
                            }
                        }
                    });
                } else {
                    PopTip.show("非法的卡号");
                }
            }
        });
    }

    private void verifyProcess(UserValidationBean userValidation) {
        LogUtils.json(userValidation);
        // 是否是 全部柜门管理员、安全员、实验室负责人
        boolean isAdmin = Boolean.TRUE.equals(userValidation.getSafeUser()) || Boolean.TRUE.equals(userValidation.getAdminUser()) || Boolean.TRUE.equals(userValidation.getCabinetAdmin());
        Triple<Boolean, Boolean, Long> first = activity.doubleVerifyList.get(0);
        Triple<Boolean, Boolean, Long> second = activity.doubleVerifyList.get(1);
        // 第一个人必须是登录人
        if (!first.getFirst()) {
            if (!userValidation.getUserId().equals(ChemicalApp.userData.getUserId())) {
                PopTip.show("请登录人验证!");
                return;
            }
        }
        // 第一个人是否已认证通过 第二个人未通过
        if (!first.getFirst() && !second.getFirst()) {
            binding.hint1IV.setText("登录人验证已通过");
            PopTip.show("登录人验证已通过!");
            userValidation1 = userValidation;
            activity.doubleVerifyList.set(0, new Triple<>(true, isAdmin, Long.valueOf(userValidation.getUserId())));
            // 切换到第二位验证人 默认人脸方式
            switchShowDetect(DetectType.FACE_DETECT, false, true);
        }
        if (first.getFirst() && !second.getFirst()) {
            //  至少一个人是管理员
            if (!first.getSecond() && !isAdmin) {
                PopTip.show("请联系柜门管理员、安全员、实验室负责人进行验证");
                return;
            }

//                                    // 重复的人
//                                    if (first.getThird() == Long.parseLong(result.getUserId())) {
//                                        PopTip.show("验证人不能相同!");
//                                        return;
//                                    }
            activity.doubleVerifyList.set(1, new Triple<>(true, isAdmin, Long.valueOf(userValidation.getUserId())));
            binding.hint2IV.setText("第二位验证已通过");
            PopTip.show("第2位验证已通过!");
            userValidation2 = userValidation;
            doubleVerifySuccess();
        }

    }

    private void doubleVerifySuccess() {
        PopTip.show("双人认证成功");
        AudioPlayer.getInstance().play(R.raw.shuangren_tongguo);
        Intent intent = new Intent();
        intent.putExtra("userValidation1", GsonUtils.toJson(userValidation1));
        intent.putExtra("userValidation2", GsonUtils.toJson(userValidation2));
        activity.setResult(TwoPersonActivity.RESULT_OK, intent);
        activity.finish();
    }

    /**
     * 切换识别展示
     *
     * @param faceDetect 类型
     * @param isFirst    是否第一位
     * @param isShow     是否展示
     */
    public void switchShowDetect(DetectType faceDetect, boolean isFirst, boolean isShow) {
        Triple<Boolean, Boolean, Long> first = activity.doubleVerifyList.get(0);
        Triple<Boolean, Boolean, Long> second = activity.doubleVerifyList.get(1);
        if (first.getFirst() && second.getFirst()) {
            PopTip.show("双人认证已通过!");
            return;
        }
        // 是否第一位
        if (isFirst) {
            if (first.getFirst()) {
                PopTip.show("登录人验证已通过!");
                return;
            }
            binding.include1LL.removeAllViewsInLayout();
            switch (faceDetect) {
                case FACE_DETECT:
                    if (isShow) {
                        binding.include1LL.addView(new FaceDetectView(activity, activity, activity.doubleVerifyList, activity.planAddData, new DoubleVerifyActivity.DoubleVerifyListener() {
                            @Override
                            public void detect(DetectType type, Bitmap faceBitmap, UserValidationBean userValidationBean) {
                                binding.include1LL.removeAllViewsInLayout();
                                ImageView imageView = new ImageView(activity);
                                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                imageView.setImageBitmap(faceBitmap);
                                binding.include1LL.addView(imageView);
                                binding.hint1IV.setText("登录人验证已通过");
                                PopTip.show("登录人验证已通过!");
                                userValidation1 = userValidationBean;
                                switchShowDetect(DetectType.FACE_DETECT, false, true);
                            }
                        }));
                        AudioPlayer.getInstance().play(R.raw.diyiren_renlianshibie);
                    } else {
                        ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setBackgroundResource(R.mipmap.icon_face_two);
                        binding.include1LL.addView(imageView);
                    }
                    break;
                case CARD_DETECT:
                    ImageView imageView = new ImageView(activity);
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    imageView.setBackgroundResource(R.mipmap.img_sfrz_sksyt);
                    binding.include1LL.addView(imageView);
                    AudioPlayer.getInstance().play(R.raw.diyiwei_shua_ka_renzheng);
                    break;
                case SCAN_DETECT:
                    ImageView qrIv = new ImageView(activity);
                    qrIv.setImageBitmap(ConvertUtils.drawable2Bitmap(ResourceUtils.getDrawable(R.mipmap.qr)));
                    ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() {
                        @Override
                        public Bitmap doInBackground() throws Throwable {
                            Lztek mLztek = Lztek.create(activity);
                            String toUpperCase = mLztek.getEthMac().toUpperCase().replace(":", "");
                            qrScanTime = TimesUils.INSTANCE.getCurrentDateTime();
                            String url = HttpConfig.Companion.getAPI_BASE_QC_URL() + "?doorId=-1" + "&subId=0" + ChemicalApp.subjectId + "&type=12&macId=" + toUpperCase + "&code=" + qrScanTime;
                            LogUtils.d("qrUrl", url);
                            return createQrCode(url);
                        }

                        @Override
                        public void onSuccess(Bitmap result) {
                            if (null != result) {
                                qrIv.setBackground(null);
                                qrIv.setImageBitmap(result);
                                startQrTimer();
                            }
                        }
                    });
                    binding.include1LL.addView(qrIv);
                    AudioPlayer.getInstance().play(R.raw.diyiren_saoma);
                    break;
            }
        } else {
            if (!first.getFirst()) {
                PopTip.show("登录人验证未通过!");
                return;
            }
            binding.include2LL.removeAllViewsInLayout();
            switch (faceDetect) {
                case FACE_DETECT:
                    if (isShow) {
                        binding.include2LL.addView(new FaceDetectView(activity, activity, activity.doubleVerifyList, activity.planAddData, new DoubleVerifyActivity.DoubleVerifyListener() {
                            @Override
                            public void detect(DetectType type, Bitmap faceBitmap, UserValidationBean userValidationBean) {
                                binding.include2LL.removeAllViewsInLayout();
                                ImageView imageView = new ImageView(activity);
                                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                imageView.setImageBitmap(faceBitmap);
                                binding.include2LL.addView(imageView);
                                binding.hint2IV.setText("第二位验证已通过");
                                userValidation2 = userValidationBean;
                                doubleVerifySuccess();
                            }
                        }));
                        AudioPlayer.getInstance().play(R.raw.dierwei_renlianshibie);
                    } else {
                        ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setBackgroundResource(R.mipmap.icon_face_two);
                        binding.include2LL.addView(imageView);
                    }
                    break;
                case CARD_DETECT:
                    ImageView imageView = new ImageView(activity);
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    imageView.setBackgroundResource(R.mipmap.img_sfrz_sksyt);
                    binding.include2LL.addView(imageView);
                    AudioPlayer.getInstance().play(R.raw.dierweishuakarenzheng);
                    break;
                case SCAN_DETECT:
                    ImageView qrIv = new ImageView(activity);
                    qrIv.setImageBitmap(ConvertUtils.drawable2Bitmap(ResourceUtils.getDrawable(R.mipmap.qr)));
                    ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() {
                        @Override
                        public Bitmap doInBackground() throws Throwable {
                            Lztek mLztek = Lztek.create(activity);
                            String toUpperCase = mLztek.getEthMac().toUpperCase().replace(":", "");
                            qrScanTime = TimesUils.INSTANCE.getCurrentDateTime();
                            String url = HttpConfig.Companion.getAPI_BASE_QC_URL() + "?doorId=-1" + "&subId=0" + ChemicalApp.subjectId + "&type=12&macId=" + toUpperCase + "&code=" + qrScanTime;
                            LogUtils.d("qrUrl", url);
                            return createQrCode(url);
                        }

                        @Override
                        public void onSuccess(Bitmap result) {
                            if (null != result) {
                                qrIv.setBackground(null);
                                qrIv.setImageBitmap(result);
                                startQrTimer();
                            }
                        }
                    });
                    binding.include2LL.addView(qrIv);
                    AudioPlayer.getInstance().play(R.raw.dierren_saoma);
                    break;
            }
        }
        // 切换UI
        switchDetectUi(faceDetect, isFirst);
    }

    private CountDownTimer qrTimer;

    private void startQrTimer() {
        if (null != qrTimer) {
            qrTimer.cancel();
            qrTimer.start();
        } else {
            qrTimer = new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (activity.detectType != DetectType.SCAN_DETECT) {
                        qrTimer.cancel();
                        qrTimer = null;
                    } else {
                        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<UserValidationBean>() {
                            @Override
                            public UserValidationBean doInBackground() throws Throwable {
                                List<HxpCabinetDoorVo> planAddDataDoorList = activity.planAddData.getDoorList();
                                List<String> doorIdList = new ArrayList<>();
                                if (null != planAddDataDoorList && !planAddDataDoorList.isEmpty()) {
                                    for (int i = 0; i < planAddDataDoorList.size(); i++) {
                                        doorIdList.add(String.valueOf(planAddDataDoorList.get(i).getDoorId()));
                                    }
                                }
                                Response response = HttpTool.aioScanLogin1(qrScanTime, ChemicalApp.subjectId, doorIdList);
                                if (response.isSuccessful()) {
                                    String json = response.body().string();
                                    JSONObject jsonObject = new JSONObject(json);
                                    int code = jsonObject.getInt("code");
                                    if (200 == code) {
                                        return GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), UserValidationBean.class);
                                    } else {
                                        PopTip.show(jsonObject.getString("message"));
                                    }
                                } else {
                                    PopTip.show(response.message());
                                }
                                return null;
                            }

                            @Override
                            public void onSuccess(UserValidationBean result) {
                                if (null != result) {
                                    qrTimer.cancel();
                                    qrTimer = null;
                                    verifyProcess(result);
                                }
                            }
                        });
                        qrTimer.start();
                    }
                }
            };
            qrTimer.start();
        }
    }

    private void switchDetectUi(DetectType detectType, boolean isFirst) {
        if (isFirst) {
            switch (detectType) {
                case FACE_DETECT:
                    binding.face1IB.setVisibility(View.GONE);
                    binding.scan1IB.setVisibility(View.VISIBLE);
                    binding.card1IB.setVisibility(View.VISIBLE);
                    binding.hint1IV.setText("请登录人人脸验证");
                    binding.hintBottom1IV.setText("请正对屏幕并使脸位于取景框内");
                    break;
                case CARD_DETECT:
                    binding.face1IB.setVisibility(View.VISIBLE);
                    binding.scan1IB.setVisibility(View.VISIBLE);
                    binding.card1IB.setVisibility(View.GONE);
                    binding.hint1IV.setText("请登录人刷卡验证");
                    binding.hintBottom1IV.setText("请在刷卡区域进行刷卡验证");
                    break;
                case SCAN_DETECT:
                    binding.face1IB.setVisibility(View.VISIBLE);
                    binding.scan1IB.setVisibility(View.GONE);
                    binding.card1IB.setVisibility(View.VISIBLE);
                    binding.hint1IV.setText("请登录人扫码验证");
                    binding.hintBottom1IV.setText("请打开微信扫描屏幕二维码");
                    break;
            }
        } else {
            switch (detectType) {
                case FACE_DETECT:
                    binding.face2IB.setVisibility(View.GONE);
                    binding.scan2IB.setVisibility(View.VISIBLE);
                    binding.card2IB.setVisibility(View.VISIBLE);
                    binding.hint2IV.setText("请第二位人脸验证");
                    binding.hintBottom2IV.setText("请正对屏幕并使脸位于取景框内");
                    break;
                case CARD_DETECT:
                    binding.face2IB.setVisibility(View.VISIBLE);
                    binding.scan2IB.setVisibility(View.VISIBLE);
                    binding.card2IB.setVisibility(View.GONE);
                    binding.hint2IV.setText("请第二位刷卡验证");
                    binding.hintBottom2IV.setText("请在刷卡区域进行刷卡验证");
                    break;
                case SCAN_DETECT:
                    binding.face2IB.setVisibility(View.VISIBLE);
                    binding.scan2IB.setVisibility(View.GONE);
                    binding.card2IB.setVisibility(View.VISIBLE);
                    binding.hint2IV.setText("请第二位扫码验证");
                    binding.hintBottom2IV.setText("请打开微信扫描屏幕二维码");
                    break;
            }
        }
    }

    private Bitmap createQrCode(String url) {
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400);
        } catch (WriterException e) {
            LogUtils.e(Log.getStackTraceString(e));
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(bitMatrix.getWidth(), bitMatrix.getHeight(), Bitmap.Config.ARGB_8888);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                bitmap.setPixel(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return bitmap;
    }
}
