package com.alipay.face.verify.fintechfacedemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alipay.face.verify.fintechfacedemo.network.NetResponse;
import com.alipay.face.verify.fintechfacedemo.network.SimpleNetworkRequestUtil;
import com.alipay.face.verify.fintechfacedemo.utils.LogUtil;
import com.alipay.face.verify.fintechfacedemo.utils.RSAUtils;
import com.alipay.face.verify.fintechfacedemo.utils.TextUtil;
import com.antdigital.livenessverify.api.DTFFacade;
import com.antdigital.livenessverify.api.DTFFacadeBuilder;
import com.dtf.face.ui.widget.iOSLoadingView;

import java.util.HashMap;

public class MainActivity extends Activity {


    private final String TAG = "MultiActionDemo";


    // 最近一次验证ID
    private String lastCertifyID;
    private String lastQueryCertifyID;
    private String currentModel = "LIVENESS";//当前模式
    private VerifyFragment verifyFragment;
    private ResultFragment resultFragment;
    private int productType = APP;
    public static int APP = 0;

    public static int OCR = 1;
    public static int NFC = 2;

    public EditText etCertNo;
    public TextView txtCertNo;
    public RadioButton rbPassport;
    public EditText etBirthday;
    public EditText etValidate;
    public iOSLoadingView iOSLoading;
    public RadioButton rbIDCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DTFFacade.install(this);
        LogUtil.log(TAG, "metaInfos:  " + DTFFacade.getMetaInfos(this));

        FragmentManager fragmentManager = getFragmentManager();
        if (null == fragmentManager.findFragmentById(R.id.fl_container)) {
            verifyFragment = VerifyFragment.newInstance();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fl_container, verifyFragment);
            fragmentTransaction.commit();
        } else {
            verifyFragment = (VerifyFragment) fragmentManager.findFragmentById(R.id.fl_container);
        }

    }

    public void verifyClick(View view) {
        setLoadingVisibility(View.VISIBLE);
        if (verifyFragment.isDebug) {
            verifyCertifyID(view);
        } else {
            beginExpSDK(view);
        }
    }

    public void verifyCertifyID(View view) {
        setLoadingVisibility(View.GONE);
        String certifyID = ((EditText) findViewById(R.id.certifyID)).getText().toString();
        if (TextUtils.isEmpty(certifyID)) {
            showToastMsg("CertifyID不能为空");
            return;
        }

        verify(certifyID);
    }

    /**
     * 体验SDK
     */
    public void beginExpSDK(View view) {

        String expCode = ((EditText) findViewById(R.id.expCode)).getText().toString();
        String certName = ((EditText) findViewById(R.id.certName)).getText().toString();
        String certNo = etCertNo.getText().toString();
        String birthday = etBirthday.getText().toString();
        String validate = etValidate.getText().toString();


        if (productType == NFC) {
            String msg = "";
            if (null != rbIDCard && rbIDCard.isChecked()) {
                if (TextUtils.isEmpty(expCode) || TextUtils.isEmpty(certNo)) {
                    msg = "体验码&证件号码必填";
                }
            } else {
                if (TextUtils.isEmpty(expCode) || TextUtils.isEmpty(certNo) || TextUtils.isEmpty(birthday) || TextUtils.isEmpty(validate)) {
                    msg = "体验码&证件号码&出生日期&有效期必填";
                }
            }
            if (TextUtil.isNotEmpty(msg)) {
                showToastMsg(msg);
                return;
            }
        } else {
            if (TextUtils.isEmpty(expCode) || TextUtils.isEmpty(certName) || TextUtils.isEmpty(certNo)) {
                showToastMsg("体验码&姓名&身份证必填");
                return;
            }
        }

        final JSONObject requestBody = new JSONObject();
        requestBody.put("metaInfo", JSONObject.parseObject(DTFFacade.getMetaInfos(this)));

        try {
            if (!TextUtils.isEmpty(certName) && productType != NFC) {
                requestBody.put("certName", RSAUtils.encrypt(certName.getBytes("UTF-8")));
            }
            if (!TextUtils.isEmpty(certNo)) {
                if (productType == NFC) {
                    requestBody.put("certNo", certNo);
                } else {
                    requestBody.put("certNo", RSAUtils.encrypt(certNo.getBytes("UTF-8")));
                }
            }
        } catch (Exception e) {
            LogUtil.log(TAG, e.getMessage());
        }

        requestBody.put("caseCode", expCode);


        requestBody.put("interactionMode", currentModel);//默认眨眼

        if (productType == NFC) {
            //只支持透传
            requestBody.put("mode", "trans");
            requestBody.put("certType", null != rbPassport && rbPassport.isChecked() ? "PASSPORT" : "IDENTITY_CARD");
            requestBody.put("validateDate", etValidate.getText().toString().trim());
            requestBody.put("birthday", etBirthday.getText().toString().trim());
            JSONObject externParam = new JSONObject();
            externParam.put("syntheticEdoc", "Y");
            externParam.put("obtainDocPhoto", "Y");
            requestBody.put("externParam", externParam.toJSONString());
        }

        LogUtil.log(TAG, "request:    " + requestBody.toJSONString());
        setLoadingVisibility(View.VISIBLE);
        new Thread(() -> {
            try {
                NetResponse response = SimpleNetworkRequestUtil.doRequest(requestBody.toJSONString().getBytes(), SimpleNetworkRequestUtil.BASEURL +
                        (productType == NFC ? "v1/realdoc/nfc" : "v1/realface/app"));
                JSONObject result = JSONObject.parseObject(new String(response.responseBody));

                String certifyId = "";
                if (result != null && result.getBooleanValue("success")
                        && TextUtil.isNotEmpty(certifyId = TextUtil.getNotNullValue(result.getJSONObject("data"), "certifyId"))) {
                    lastCertifyID = certifyId;
                    verify(lastCertifyID);
                    setLoadingVisibility(View.GONE);
                    LogUtil.log(TAG, "数据请求正常:" + new String(response.responseBody));
                } else {
                    showToastMsg("数据请求异常" + new String(response.responseBody));
                    LogUtil.log(TAG, "数据请求异常:" + new String(response.responseBody));
                }

            } catch (Exception e) {
                LogUtil.log(TAG, "数据请求异常:" + Log.getStackTraceString(e));
                showToastMsg("数据请求异常" + e.getMessage());
            }
        }).start();
    }

    /**
     * 进入认证
     *
     * @param certifyID 认证唯一标识
     */
    private void verify(String certifyID) {
        lastCertifyID = certifyID;
        DTFFacade dtfFacade = DTFFacadeBuilder.create(this);
        HashMap<String, String> extParams = new HashMap<>();
        //如需指定活体检测UI界面方向(横屏+竖屏)，请指定这一项。
//        extParams.put(DTFFacade.ZIM_EXT_PARAMS_KEY_SCREEN_ORIENTATION, DTFFacade.ZIM_EXT_PARAMS_VAL_SCREEN_LAND);
        //如需支持活体视频返回，请指定这一项，并在response.videoFilePath中获取视频本地路径。
        extParams.put(DTFFacade.ZIM_EXT_PARAMS_KEY_USE_VIDEO, DTFFacade.ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE);

        //如需设置OCR的“下一步”按钮颜色（默认可不设置），请设置此项，如红色 #FF0000。
//        extParams.put(DTFFacade.ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR, "#FF0000");
        //如需自定义活体检测页面的进度条颜色（默认可不设置），请设置此项，如红色 #FF0000。
//        extParams.put(DTFFacade.ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR, "#FF0000");
        //如需设置自定义语言，请设置此项为以下值：zh-CN：中文简体 zh-HK：中文繁体 zh-TW：中文繁体，en：英文 in：印尼文 ja：日文 ko：韩文
        //设置为其他值，则显示系统当前语言
        extParams.put(dtfFacade.ZIM_EXT_PARAMS_KEY_LANGUAGE, "zh-CN");
        //如需打开刷脸页业务提示开关（默认可不设置），请设置此项,需要结合自定义UI的配置文件使用
        extParams.put(DTFFacade.ZIM_EXT_PARAMS_KEY_NEED_FACE_NOTICE, DTFFacade.ZIM_EXT_PARAMS_VAL_NEED_FACE_NOTICE_TRUE);
        dtfFacade.verify(certifyID, true, extParams, response -> {
            if (1000 == response.code) {
                Toast.makeText(this, "认证通过", Toast.LENGTH_LONG).show();
                LogUtil.log(TAG, "verify callback 认证通过  videoFilePath=" + response.videoFilePath);
            } else {
                Toast.makeText(this, "认证失败([" + response.code + "]" + response.reason + ")", Toast.LENGTH_LONG).show();
                LogUtil.log(TAG, "verify callback 认证失败  " + response.code + ":" + response.reason);
            }

            return true;
        });

    }

    public void setProductType(int productType) {
        this.productType = productType;
        if (productType == NFC) {
            etCertNo.setHint("必填，字母仅支持大写");
            txtCertNo.setText("证件号码");
        } else if (productType == APP) {
            etCertNo.setHint("请输入身份证");
            txtCertNo.setText("身份证号");
        }
    }

    public int getProductType() {
        return productType;
    }

    public void setCurrentModel(String currentModel) {
        this.currentModel = currentModel;
    }

    public void checkResult(View view) {
        if (null != lastCertifyID && !lastCertifyID.isEmpty()) {
            queryState(lastCertifyID);
        } else {
            showToastMsg("请先认证");
        }
    }

    public void showVerifyFragment() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        if (null != resultFragment && resultFragment.isAdded()) {
            fragmentTransaction.hide(resultFragment);
        }
        if (null != verifyFragment && verifyFragment.isAdded()) {
            fragmentTransaction.show(verifyFragment);
        }
        fragmentTransaction.commit();
    }


    /**
     * 复制CertifyID
     */
    public void copyCertifyID(View view) {
        lastCertifyID = ((EditText) findViewById(R.id.certifyID)).getText().toString().trim();
        if (!TextUtils.isEmpty(lastCertifyID)) {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("Label", lastCertifyID);
            cm.setPrimaryClip(clipData);
            showToastMsg("复制成功");
        } else {
            showToastMsg("无CertifyID需要复制");
        }
    }


    public void showToastMsg(final String msg) {
        setLoadingVisibility(View.GONE);
        if (Looper.getMainLooper() != Looper.myLooper()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToastMsg(msg);
                }
            });
        } else {
            if (TextUtils.isEmpty(msg)) {
                return;
            }
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 显示认证结果
     */
    public void showAlert(String title, String msg) {
        runOnUiThread(() -> {
            try {
                setLoadingVisibility(View.GONE);
                final AlertDialog.Builder alertDialogBuilder =
                        new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle(title);
                alertDialogBuilder.setMessage(msg);
                alertDialogBuilder.setPositiveButton(android.R.string.yes,
                        (dialog, which) -> dialog.dismiss());

                AlertDialog dialog = alertDialogBuilder.create();
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 查询认证结果
     */
    public void queryState(String zimId) {
        setLoadingVisibility(View.VISIBLE);
        new Thread(() -> {
            try {

                NetResponse response = SimpleNetworkRequestUtil.doRequest(SimpleNetworkRequestUtil.BASEURL +
                        (productType == NFC ? "v1/realdoc/nfc" : "v1/realface/app") + "?certifyId=" + zimId, null, null);
                setLoadingVisibility(View.GONE);
                String msg = "";
                if (null != response.responseBody) {
                    JSONObject result = JSONObject.parseObject(new String(response.responseBody));
                    if (null != result) {
                        if (result.getBoolean("success")) {
                            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                            if (null == resultFragment || !zimId.equals(lastQueryCertifyID)) {
                                resultFragment = ResultFragment.newInstance(result.toJSONString());
                                fragmentTransaction.add(R.id.fl_container, resultFragment);
                            }
                            if (resultFragment.isAdded()) {
                                fragmentTransaction.show(resultFragment);
                            }
                            fragmentTransaction.hide(verifyFragment);
                            fragmentTransaction.commit();
                            lastQueryCertifyID = zimId;
                            return;
                        }
                        msg = result.toJSONString();
                    }
                }

                showAlert("认证提示", null == msg ? "" : msg);
            } catch (Exception e) {
                e.printStackTrace();
                showAlert("错误提示", e.getMessage());
            }

        }).start();
    }

    public void setLoadingVisibility(int visibility) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            if (null != iOSLoading) {
                iOSLoading.setVisibility(visibility);
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setLoadingVisibility(visibility);
                }
            });
        }
    }

}
