package com.xg.idcard;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import com.cn.qsign.jsgzlibrary.utils.QsignNotaryApi;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;

public class IdCardIdentifyPlugin extends CordovaPlugin {
    private static final String ID_CARD_IDENTIFY = "IdCardIdentify";//实名认证
    private static final String FACE_CONTRAST = "faceContrast";//人脸对比
    private String idNum;
    private String idName;
    private String phoneNum;
    private CallbackContext mCallbackContext;
    private String licenseName;

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        String packageName = cordova.getActivity().getPackageName();
        if ("com.xcmg.app.demo".equals(packageName)) {
            licenseName = "com.xcmg.app.dev-license.qsign-android";
        } else {
            licenseName = "com.xcmg.app-license.qsign-android";
        }
        boolean initok = QsignNotaryApi.getInstance().init(cordova.getActivity().getApplication(), "", licenseName, "xugong", false);
        Log.d("IdCardIdentifyPlugin", "initok = " + initok);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        this.mCallbackContext = callbackContext;
        if (args == null) {
            mCallbackContext.error(getResult(0, "参数错误"));
            return false;
        }
        JSONObject idInfo = args.optJSONObject(0);
        if (idInfo == null) {
            mCallbackContext.error(getResult(0, "参数错误"));
            return false;
        }
        idNum = idInfo.optString("idNum");
        idName = idInfo.optString("idName");
        if (idNum == null || idNum.isEmpty() || idName == null || idName.isEmpty()) {
            mCallbackContext.error(getResult(0, "参数错误"));
            return false;
        }
        if (ID_CARD_IDENTIFY.equals(action)) {
            phoneNum = idInfo.optString("phoneNum");
            if (phoneNum == null || phoneNum.isEmpty()) {
                mCallbackContext.error(getResult(0, "参数错误"));
                return false;
            }
            startIdCardCheck();
        } else if (FACE_CONTRAST.equals(action)) {
            checkCameraPermission();
        } else {
            mCallbackContext.error(getResult(0, "参数错误"));
            return false;
        }
        return true;
    }

    private void startIdCardCheck() {
        QsignNotaryApi.getInstance().identifyNotary(cordova.getActivity(),
                idName, idNum, phoneNum,
                new QsignNotaryApi.registerCallbackListener() {
                    @Override
                    public void onSuccess(QsignNotaryApi.QSIGNREGISTERCODE qsignregistercode, String s, String s1, String s2) {
                        if (qsignregistercode == QsignNotaryApi.QSIGNREGISTERCODE.NORMALREGISTER) {
                            mCallbackContext.success(getResult(1, "检测成功"));
                        } else {
                            mCallbackContext.error(getResult(0, "信息提交成功，等待人工审核"));
                        }
                    }

                    @Override
                    public void onError(QsignNotaryApi.QSIGNERRORCODE qsignerrorcode, String s) {
                        mCallbackContext.error(getResult(0, s));
                    }
                });
    }

    private void startFaceContrast() {
        QsignNotaryApi.getInstance().qsignLivenessNotary(cordova.getActivity(), idName, idNum, new QsignNotaryApi.faceCallbackListener() {
            @Override
            public void onSuccess(String s) {
                String filePath = saveImage(s);
                mCallbackContext.success(getResult(1, filePath));
            }

            @Override
            public void onError(QsignNotaryApi.QSIGNERRORCODE qsignerrorcode, String s) {
                mCallbackContext.error(getResult(0, s));
            }
        });
    }


    private String getResult(int code, String message) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", code);
            jsonObject.put("message", message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    private void checkCameraPermission() {
        if (cordova.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && cordova.hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            startFaceContrast();
        } else {
            requestCameraPermission();
        }
    }

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static final int REQUEST_CAMERA_PERMISSION_CODE = 0x01;

    private void requestCameraPermission() {
        cordova.requestPermissions(this, REQUEST_CAMERA_PERMISSION_CODE, PERMISSIONS_STORAGE);
    }

    @Override
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
        if (REQUEST_CAMERA_PERMISSION_CODE == requestCode) {
            boolean checkPermission = true;
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        checkPermission = false;
                    }
                }
            } else {
                checkPermission = false;
            }
            if (checkPermission) {
                startFaceContrast();
            } else {
                mCallbackContext.success(getResult(0, "未授予文件读写"));
            }
        }
        super.onRequestPermissionResult(requestCode, permissions, grantResults);
    }

    private String saveImage(String base64String) {
        byte[] decode = Base64.decode(base64String, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        File appDir = new File(cordova.getActivity().getApplicationContext().getExternalFilesDir(null), "image");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getPath();
    }
}
