package com.quenice.idcard;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.quenice.idcard.utils.ManageIDCardRecogResult;
import com.quenice.idcard.utils.CardScreenUtil;
import com.quenice.idcard.utils.ReturnMessage;
import com.quenice.idcard.utils.Id2Data;
import com.quenice.idcard.view.ScanCardsView;
import com.quenice.idcard.view.ViewfinderView;

import kernal.idcard.android.ResultMessage;
import kernal.idcard.camera.IScanReturnMessage;
import kernal.idcard.camera.UritoPathUtil;

import android.Manifest;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import kernal.sun.misc.BASE64Encoder;

import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;


/**
 * @author A@H
 * @describle 相机界面，主要识别结果的获取以及识别完成之后的跳转
 */
public class CardsCameraActivity extends ReactActivity implements IScanReturnMessage, View.OnClickListener {
    public static ReactContext MyContext;
    RelativeLayout relativeLayout;
    RelativeLayout.LayoutParams imageButton_flash_params, imageButton_camera_params, imageButton_back_params, imageButton_spot_dection_params, imageButton_ejct_params;
    ImageButton imageButton_flash, imageButton_camera, imageButton_back, imageButton_spot_dection, imageButton_ejct;
    ScanCardsView scanICamera;
    private boolean isOpenFlash = false;
    private int width, height;
    private boolean isOpendetectLightspot = false;
    private static final int PERMISSION_REQUESTCODE = 1;
    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};
    String re = null;

    int scanType = 2;
    Id2Data id2Data;

    /**
     * 扫描识别成功，界面的跳转(回调接口)
     *
     * @param resultMessage 识别结果
     * @param picPath       图片路径数组，picPath[0]: 全图路径；picPath[1]: 裁切图；picPath[2]: 证件头像
     */
    @Override
    public void scanOCRIdCardSuccess(ResultMessage resultMessage, String[] picPath) {
        Vibrator mVibrator = (Vibrator) getApplication().getSystemService(
                Service.VIBRATOR_SERVICE);
        mVibrator.vibrate(200);
        Toast.makeText(this, "扫描成功", Toast.LENGTH_LONG).show();
        String result=ManageIDCardRecogResult.managerSucessRecogResult(resultMessage);
        String[] GetFieldName = resultMessage.GetFieldName;
        String[] GetRecogResult = resultMessage.GetRecogResult;

        if (GetFieldName == null || GetFieldName.length <= 0 || GetRecogResult == null || GetRecogResult.length <= 0) {
            nativeCallRn("result is null");
            //Toast.makeText(this, "扫描成功 is null", Toast.LENGTH_LONG).show();
        } else {
            ReturnMessage resultMsg = new ReturnMessage();
            String[] values = id2Data.getIndex(scanType);
            int name = indexOfArr(GetFieldName, values[0]);
            int addr = indexOfArr(GetFieldName, values[1]);
            int num = indexOfArr(GetFieldName, values[2]);
            resultMsg.setIdName(name >= 0 ? GetRecogResult[name] : "");
            resultMsg.setAddress(addr >= 0 ? GetRecogResult[addr] : "");
            resultMsg.setIdNum(num >= 0 ? GetRecogResult[num] : "");
            String path = picPath[2];
            String pathFull = picPath[1];
            resultMsg.setPicPath(path);
            resultMsg.setPicSrc(GetImageStr(path));
            resultMsg.setPicSrcFull(GetImageStr(pathFull));
            String resultJson = new Gson().toJson(resultMsg);
            nativeCallRn(resultJson);
            Log.e("resultAll", result);
            Log.e("result", resultJson);
        }
        this.finish();
    }

    public static int indexOfArr(String[] arr,String value2){
        for(int i=0;i<arr.length;i++){
            if(arr[i].equals(value2)){
                return i;
            }
        }
        return -1;
    }

    // 图片转化成base64字符串
    public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        ByteArrayOutputStream out = null;
        int len = 0;
        byte buf[] = new byte[1024];
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            out = new ByteArrayOutputStream();
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);  //把数据写入内存
            }
            out.close();  //关闭内存输出流
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (out == null) {
            Log.e("output", "output is null " + imgFile);
            return "";
        }
        byte[] data = out.toByteArray();
        if (data == null) {
            Log.e("data", "data is null " + imgFile);
            return "";
        }
        Log.e("result", "has file:" + imgFile);
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    public void nativeCallRn(String msg) {
        MyContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("RESULT", msg);
    }

    /**
     * 扫描识别失败，界面的跳转(回调接口)
     *
     * @param error   -10601 开发码错误,把该文件中的{@link com.quenice.idcard.utils.Devcode}中的devcode替换
     *                -10602 applicationId错误，把build.gradle文件中的 applicationId修改为授权文件中绑定的信息
     *                -10603 授权到期，请从新申请授权
     *                -10605  string.xml中的app_name字段属性和授权文件中绑定的不一致
     *                -10606  string.xml中company_name字段属性和授权文件中绑定的不一致 武汉讯检科技有限公司
     *                -10608  string.xml中缺少company_name字段，请添加该字段
     * @param picPath 该数组存储的是拍照识别失败时的全图路径
     */
    @Override
    public void scanOCRIdCardError(String error) {
        Intent intent = new Intent();
        intent.putExtra("error", error);
        this.setResult(Activity.RESULT_OK, intent);
        Toast.makeText(this, "扫描失败 " + error, Toast.LENGTH_LONG).show();
        this.finish();
    }


    @Override
    public void authOCRIdCardSuccess(String result) {

    }

    /**
     * 授权失败
     *
     * @param error
     * @see
     */
    @Override
    public void authOCRIdCardError(String error) {
        Intent intent = new Intent();
        intent.putExtra("error", error);
        this.setResult(Activity.RESULT_OK, intent);
        this.finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 9 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            scanICamera.importPicRecog(UritoPathUtil.getImageAbsolutePath(getApplicationContext(), uri));
        }
    }

    @Override
    public void onClick(View v) {
        //返回事件
        if (v == imageButton_back) {
            this.finish();
            //拍照事件
        } else if (v == imageButton_camera) {
            scanICamera.takePicRecog();
            //闪光灯
        } else if (v == imageButton_flash) {
            if (isOpenFlash) {
                isOpenFlash = false;
                scanICamera.managerFlashLight(isOpenFlash);
                imageButton_flash.setBackgroundResource(R.mipmap.flash_off);
            } else {
                isOpenFlash = true;
                scanICamera.managerFlashLight(isOpenFlash);
                imageButton_flash.setBackgroundResource(R.mipmap.flash_on);
            }
            //隐藏、显示拍照事件
        } else if (v == imageButton_ejct) {
            imageButton_ejct.setVisibility(View.GONE);
            imageButton_camera.setVisibility(View.VISIBLE);
            // 光斑检测事件
        } else if (v == imageButton_spot_dection) {
            if (isOpendetectLightspot) {
                Toast.makeText(this, getString(R.string.closeddetectLightspot),
                        Toast.LENGTH_SHORT).show();
                isOpendetectLightspot = false;
                imageButton_spot_dection.setBackgroundResource(R.mipmap.spot_dection_off);
                scanICamera.managerSpotDection(isOpendetectLightspot);
            } else {
                Toast.makeText(this, getString(R.string.opendetectLightspot),
                        Toast.LENGTH_SHORT).show();
                isOpendetectLightspot = true;
                imageButton_spot_dection.setBackgroundResource(R.mipmap.spot_dection_on);
                scanICamera.managerSpotDection(isOpendetectLightspot);
            }
        }
    }

    @Override
    @TargetApi(16)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permission();

    }

    /**
     * 动态授权
     */
    private void permission() {
        boolean isPermission = true;
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                isPermission = false;
            }
        }
        if (!isPermission) {
            // 没有授权
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUESTCODE);
        } else {
            // 已经授权
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUESTCODE:
                boolean isPermission = true;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isPermission = false;
                    }
                }
                if (!isPermission) {
                    Toast.makeText(this, "权限获取失败", Toast.LENGTH_LONG).show();
                    this.finish();
                }
                init();
                break;
            default:
                break;
        }
    }

    private void init() {
        scanType = getIntent().getIntExtra("type", 2);
        id2Data = new Id2Data();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        hideBottomUIMenu();
        setContentView(R.layout.activity_idcardscan);
        width = CardScreenUtil.getScreenResolution(this).x;
        height = CardScreenUtil.getScreenResolution(this).y;
        // WriteUtil.writeLog("该设备的屏幕分辨率为:"+width+"X"+height);
        relativeLayout = findViewById(R.id.camera_layout);
        scanICamera = new ScanCardsView(this);
        if (CardScreenUtil.getScreenOrientation(this) == CardScreenUtil.ORIENTATION_LANDSCAPE) {
            //闪光灯
            imageButton_flash = new ImageButton(this);
            imageButton_flash.setBackground(getResources().getDrawable(R.mipmap.flash_off));
            imageButton_flash_params = new RelativeLayout.LayoutParams((int) (width * 0.05), (int) (width * 0.05));
            imageButton_flash_params.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.camera_layout);
            imageButton_flash_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.camera_layout);
            imageButton_flash_params.leftMargin = (int) (width * 0.02);
            imageButton_flash_params.topMargin = (int) (width * 0.02);

            //拍照按钮
            imageButton_camera = new ImageButton(this);
            imageButton_camera.setBackground(getResources().getDrawable(R.mipmap.tack_pic_btn));
            imageButton_camera_params = new RelativeLayout.LayoutParams((int) (width * 0.1),
                    (int) (width * 0.1));
            imageButton_camera_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, R.id.camera_layout);
            imageButton_camera_params.addRule(RelativeLayout.CENTER_VERTICAL);
            imageButton_camera_params.rightMargin = (int) (width * 0.02);
            imageButton_camera.setVisibility(View.GONE);

            //返回按钮
            imageButton_back = new ImageButton(this);
            imageButton_back.setBackground(getResources().getDrawable(R.mipmap.camera_back_nomal));
            imageButton_back_params = new RelativeLayout.LayoutParams((int) (width * 0.05), (int) (width * 0.05));
            imageButton_back_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, R.id.camera_layout);
            imageButton_back_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.camera_layout);
            imageButton_back_params.leftMargin = (int) (width * 0.02);
            imageButton_back_params.bottomMargin = (int) (width * 0.02);
            //光斑检测按钮
            imageButton_spot_dection = new ImageButton(this);
            imageButton_spot_dection.setBackgroundResource(R.mipmap.spot_dection_off);
            imageButton_spot_dection_params = new RelativeLayout.LayoutParams((int) (width * 0.08), (int) (width * 0.08));
            imageButton_spot_dection_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.camera_layout);
            imageButton_spot_dection_params.addRule(RelativeLayout.CENTER_VERTICAL);
            imageButton_spot_dection_params.leftMargin = (int) (width * 0.02);

            //隐藏拍照按钮
            imageButton_ejct = new ImageButton(this);
            imageButton_ejct.setBackground(getResources().getDrawable(R.mipmap.locker_btn_def));
            imageButton_ejct_params = new RelativeLayout.LayoutParams((int) (height * 0.05), (int) (height * 0.5));
            imageButton_ejct_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, R.id.camera_layout);
            imageButton_ejct_params.addRule(RelativeLayout.CENTER_VERTICAL);

        } else {
            //竖屏状态下框的方向 true:width>height; false:height>width
            //ViewfinderView.isSameScreen = false;
            //闪光灯
            imageButton_flash = new ImageButton(this);
            imageButton_flash.setBackground(getResources().getDrawable(R.mipmap.flash_off));
            imageButton_flash_params = new RelativeLayout.LayoutParams((int) (height * 0.05), (int) (height * 0.05));
            imageButton_flash_params.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.camera_layout);
            imageButton_flash_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, R.id.camera_layout);
            imageButton_flash_params.rightMargin = (int) (height * 0.02);
            imageButton_flash_params.topMargin = (int) (height * 0.02);

            //拍照按钮
            imageButton_camera = new ImageButton(this);
            imageButton_camera.setBackground(getResources().getDrawable(R.mipmap.tack_pic_btn));
            imageButton_camera_params = new RelativeLayout.LayoutParams((int) (height * 0.1),
                    (int) (height * 0.1));
            imageButton_camera_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, R.id.camera_layout);
            imageButton_camera_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
            imageButton_camera_params.bottomMargin = (int) (height * 0.02);
            imageButton_camera.setVisibility(View.GONE);

            //返回按钮
            imageButton_back = new ImageButton(this);
            imageButton_back.setBackground(getResources().getDrawable(R.mipmap.camera_back_nomal));
            imageButton_back_params = new RelativeLayout.LayoutParams((int) (height * 0.05), (int) (height * 0.05));
            imageButton_back_params.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.camera_layout);
            imageButton_back_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, R.id.camera_layout);
            imageButton_back_params.leftMargin = (int) (height * 0.02);
            imageButton_back_params.topMargin = (int) (height * 0.02);
            //光斑检测按钮
            imageButton_spot_dection = new ImageButton(this);
            imageButton_spot_dection.setBackgroundResource(R.mipmap.spot_dection_off);
            imageButton_spot_dection_params = new RelativeLayout.LayoutParams((int) (height * 0.08), (int) (height * 0.08));
            imageButton_spot_dection_params.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.camera_layout);
            imageButton_spot_dection_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
            imageButton_spot_dection_params.topMargin = (int) (height * 0.02);

            //隐藏拍照按钮
            imageButton_ejct = new ImageButton(this);
            imageButton_ejct.setBackground(getResources().getDrawable(R.mipmap.locker_btn_def_p));
            imageButton_ejct_params = new RelativeLayout.LayoutParams((int) (width * 0.5), (int) (width * 0.05));
            imageButton_ejct_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, R.id.camera_layout);
            imageButton_ejct_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        }
        relativeLayout.addView(scanICamera, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        relativeLayout.addView(imageButton_flash, imageButton_flash_params);
        relativeLayout.addView(imageButton_camera, imageButton_camera_params);
        relativeLayout.addView(imageButton_back, imageButton_back_params);
        relativeLayout.addView(imageButton_spot_dection, imageButton_spot_dection_params);
        relativeLayout.addView(imageButton_ejct, imageButton_ejct_params);
        imageButton_camera.setOnClickListener(this);
        imageButton_back.setOnClickListener(this);
        imageButton_flash.setOnClickListener(this);
        imageButton_ejct.setOnClickListener(this);
        imageButton_spot_dection.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (scanICamera != null) {
            scanICamera.setIScan(this);
            scanICamera.startCamera();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (scanICamera != null) {
            scanICamera.stopCamera();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scanICamera != null) {
            scanICamera.destroyService();
        }
    }

    @Override
    public void openCameraError(String error) {
        Log.i("string", "失败的信息" + error);

    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

}
