package xn.hxp.ui.login;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.CountDownTimer;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.mlkit.vision.face.Face;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.http.listener.OnUpdateListener;
import com.king.camera.scan.AnalyzeResult;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import xn.hxp.R;
import xn.hxp.databinding.ActivityLoginBinding;
import xn.hxp.http.HttpData;
import xn.hxp.http.api.GetCardLoginApi;
import xn.hxp.http.api.GetScanCodeApi;
import xn.hxp.http.api.PostFaceByPicApi;
import xn.hxp.room.bean.DeviceInfo;
import xn.hxp.room.bean.LabInfo;
import xn.hxp.room.bean.UserInfo;
import xn.hxp.room.tool.DeviceInfoTool;
import xn.hxp.room.tool.LabInfoTool;
import xn.hxp.room.tool.UserInfoTool;
import xn.hxp.ui.login.callback.OnFaceScanResultCallback;
import xn.hxp.util.AudioPlayerTool;
import xn.hxp.util.CardReaderHelper;
import xn.hxp.view.dialog.LoginVerifySuccessDialog;


public class LoginActivityHelper {
    private LoginActivity loginActivity;
    private ActivityLoginBinding binding;
    private DeviceInfo deviceInfo;
    private LabInfo labInfo;

    public LoginActivityHelper(LoginActivity loginActivity, ActivityLoginBinding binding, CardReaderHelper cardReaderHelper) {
        this.loginActivity = loginActivity;
        this.binding = binding;
        deviceInfo = DeviceInfoTool.INSTANCE.getDeviceInfo();
        labInfo = LabInfoTool.INSTANCE.getLabInfo();
        // 人脸登录
        loginActivity.onFaceScanResultCallback = new OnFaceScanResultCallback() {
            @Override
            public void onScanResultCallback(@NonNull AnalyzeResult<List<Face>> result) {
                faceResultHandle(result.getBitmap());
            }
        };

        // 刷卡登录
        loginActivity.cardReaderHelper = new CardReaderHelper(new CardReaderHelper.OnCardReadListener() {
            @Override
            public void onCardRead(String cardData) {
                cardResultHandle(cardData);
            }
        });

        // 扫码检查
        loginActivity.scanCodeCDT = new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (loginActivity.isScanning.get()) {
                    scanResultHandle();
                    return;
                }
                loginActivity.scanCodeCDT.start();
            }
        };
        loginActivity.scanCodeCDT.start();

    }

    private void scanResultHandle() {
        EasyHttp.get(loginActivity).api(new GetScanCodeApi(deviceInfo.getSn(), TimeUtils.getNowString(new SimpleDateFormat("HHmmssSSS", Locale.getDefault())), labInfo.getSubjectId())).request(new OnHttpListener<HttpData<UserInfo>>() {
            @Override
            public void onHttpSuccess(@NonNull HttpData<UserInfo> result) {
                if (result.isRequestSuccess()) {
                    UserInfo userInfo = result.getData();
                    if (null != userInfo && !loginActivity.isLogged.get()) {
                        loginActivity.isScanning.set(false);
                        UserInfoTool.INSTANCE.insert(userInfo);
                        LoginVerifySuccessDialog loginVerifySuccessDialog = new LoginVerifySuccessDialog(loginActivity, 3);
                        loginVerifySuccessDialog.setOnDismissListener(dialog -> loginActivity.finish());
                        loginVerifySuccessDialog.show();
                        loginActivity.isLogged.set(true);
                        return;
                    }
                }
                loginActivity.scanCodeCDT.start();
                loginActivity.showErr(result.getMessage());
            }

            @Override
            public void onHttpFail(@NonNull Throwable throwable) {
                loginActivity.scanCodeCDT.start();
                loginActivity.showErr(throwable.getMessage());
            }
        });
    }

    private void cardResultHandle(String cardData) {
        loginActivity.isCarding.set(true);
        EasyHttp.get(loginActivity).api(new GetCardLoginApi(cardData, labInfo.getSubjectId())).request(new OnHttpListener<HttpData<UserInfo>>() {
            @Override
            public void onHttpSuccess(@NonNull HttpData<UserInfo> result) {
                if (result.isRequestSuccess()) {
                    UserInfo userInfo = result.getData();
                    if (null != userInfo && !loginActivity.isLogged.get()) {

                        UserInfoTool.INSTANCE.insert(userInfo);
                        LoginVerifySuccessDialog loginVerifySuccessDialog = new LoginVerifySuccessDialog(loginActivity, 3);
                        loginVerifySuccessDialog.setOnDismissListener(dialog -> loginActivity.finish());
                        loginVerifySuccessDialog.show();
                        loginActivity.isLogged.set(true);
                        return;
                    }
                }
                loginActivity.showErr(result.getMessage());
                loginActivity.isCarding.set(false);
            }

            @Override
            public void onHttpFail(@NonNull Throwable throwable) {
                loginActivity.isCarding.set(false);
                loginActivity.showErr(throwable.getMessage());
            }
        });
    }

    private void faceResultHandle(Bitmap bitmap) {
        @SuppressLint("SdCardPath") String saveFile = "/sdcard/DCIM/face.jpg";
        ImageUtils.save(bitmap, saveFile, Bitmap.CompressFormat.JPEG);
        File faceFile = new File(saveFile);
        EasyHttp.post(loginActivity).api(new PostFaceByPicApi(faceFile, labInfo.getSubjectId())).request(new OnUpdateListener<HttpData<UserInfo>>() {
            @Override
            public void onUpdateProgressChange(int progress) {
                LogUtils.d(progress);
            }

            @Override
            public void onUpdateSuccess(@NonNull HttpData<UserInfo> result) {
                if (result.isRequestSuccess()) {
                    UserInfo userInfo = result.getData();
                    if (null != userInfo && !loginActivity.isLogged.get()) {
                        UserInfoTool.INSTANCE.insert(userInfo);
                        LoginVerifySuccessDialog loginVerifySuccessDialog = new LoginVerifySuccessDialog(loginActivity, 3, faceFile);
                        loginVerifySuccessDialog.setOnDismissListener(dialog -> loginActivity.finish());
                        loginVerifySuccessDialog.show();
                        loginActivity.isLogged.set(true);
                    }
                    return;
                }
                loginActivity.showErr(result.getMessage());
                ThreadUtils.runOnUiThreadDelayed(() -> loginActivity.loginFaceFragment.setAnalyzeImage(true), 1500);
            }

            @Override
            public void onUpdateFail(@NonNull Throwable throwable) {
                loginActivity.showErr(throwable.getMessage());
                ThreadUtils.runOnUiThreadDelayed(() -> loginActivity.loginFaceFragment.setAnalyzeImage(true), 1500);
            }
        });
    }

}
