package xn.xxp.home.auth.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Locale;

import core.ui.fragment.RcBaseFragment;
import http.client.HttpTool;
import http.vo.response.UserVo;
import okhttp3.Response;
import xn.xxp.databinding.FragmentAuthQrBinding;
import xn.xxp.home.auth.AuthType;
import xn.xxp.home.auth.ChoiceAuthActivity;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.utils.Tool;

/**
 * 览众人脸识别
 */
public class QrAuthFragment extends RcBaseFragment<FragmentAuthQrBinding> {
    private FragmentAuthQrBinding binding;
    private String qrScanTime;
    private DeviceConfig deviceConfig;
    private LabConfig labConfig;

    @NonNull
    @Override
    protected FragmentAuthQrBinding createViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return binding = FragmentAuthQrBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
    }

    @Override
    public void onResume() {
        super.onResume();
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() {
            @Override
            public Bitmap doInBackground() throws Throwable {
                createQrCodeInfo();
                return null;
            }

            @Override
            public void onSuccess(Bitmap bitmap) {
                startQrTimer();
            }
        });

    }

    private void createQrCodeInfo() {
        qrScanTime = TimeUtils.getNowString(new SimpleDateFormat("HHmmssSSS", Locale.getDefault()));
        String qrUrl;
        if (AppUtils.isAppDebug()) {
            qrUrl = deviceConfig.getBaseUrl() + "?macId=" + deviceConfig.getDevId() + "&subId=" + labConfig.getLabId() + "&type=13&code=" + qrScanTime;
        } else {
            qrUrl = "https://labcontrol.nwafu.edu.cn/api/?macId=" + deviceConfig.getDevId() + "&subId=" + labConfig.getLabId() + "&type=13&code=" + qrScanTime;
        }
        LogUtils.d("二维码", qrUrl);
        Bitmap bitmap = createQrCode(qrUrl);
        if (null != bitmap) {
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    binding.qrIV.setBackground(null);
                    binding.qrIV.setImageBitmap(bitmap);
                }
            });
        }
    }

    private CountDownTimer qrTimer;

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

            }

            @Override
            public void onFinish() {
                ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<UserVo>() {
                    @Override
                    public UserVo doInBackground() throws Throwable {
                        Response response = HttpTool.infoBordLogin(deviceConfig.getDevId(), qrScanTime);
                        String json = response.body().string();
                        JSONObject jsonObject = new JSONObject(json);
                        int code = jsonObject.getInt("code");
                        if (200 == code) {
                            LogUtils.d("扫码验证通过", json);
                            qrTimer.cancel();
                            UserVo userVo = GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), UserVo.class);
                            Response labStatusResponse = HttpTool.getLabStatusById(String.valueOf(labConfig.getLabId()), userVo.userId);
                            String labStatusJson = labStatusResponse.body().string();
                            JSONObject labStatusJO = new JSONObject(labStatusJson);
                            int labStatusCode = labStatusJO.getInt("code");
                            if (200 == labStatusCode) {
                                return GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), UserVo.class);
                            } else {
                                createQrCodeInfo();
                                qrTimer.start();
                            }
                            return null;
                        } else {
                            LogUtils.d("等待扫码");
                            qrTimer.start();
                        }
                        return null;
                    }

                    @Override
                    public void onSuccess(UserVo result) {
                        if (!isDetached()) {
                            if (null != result) {
                                ChoiceAuthActivity fourChoiceAuthActivity = (ChoiceAuthActivity) QrAuthFragment.this.requireActivity();
                                fourChoiceAuthActivity.authSuccess(AuthType.QR, result);
                            }
                        }
                    }
                });

            }
        };
        qrTimer.start();
    }

    @Override
    public void onDestroyView() {
        if (null != qrTimer) {
            qrTimer.cancel();
            qrTimer = null;
        }
        super.onDestroyView();

    }

    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;
    }
}
