package com.hh.lib_face.view;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.utils.ImageLoaderUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_face.R;
import com.hh.lib_face.adapter.Gridadapter;
import com.hh.lib_base.ConfigData;
import com.hh.lib_face.event.RequestThreeElementsEvent;
import com.hh.lib_face.utils.IdCardUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xwh
 * time 2024/8/27
 * Description: 手动输入身份证验证
 **/
public class IDCardView extends LinearLayout  {

    BaseAmpeRequestBean requestBean;


    private WindowManager EnterWindowManager;//本地过度页加载

    private GridView EnterIDNumberActivity_GridView;
    private Gridadapter gridadapter;
    private List<String> list = new ArrayList<>();
    private EditText EnterIDNumberActivity_edit;
    private TextView tv_OperatingTime;
    private LinearLayout EnterIDNumberActivity_SureClick, EnterIDNumberActivity_CancelClick;
    private RelativeLayout EnterIDNumberActivity_RelativeLayout;
    private long lastClickTime; // 上次点击的时间
    private RelativeLayout enterIDCard_RelativeLayout;
    private LinearLayout enterIDCard_Loding;
    private TextView enterIDCard_LodingText;
    private ImageView enterIDCard_LodingImageView;
    private int OperatingTime = 30;
    private String OperatingTimeType = "EnterIDNumber";
    private ImageView ivBg;



    Handler OperatingTimeHandler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                if (OperatingTime > 0) {
                    OperatingTime--;
                    if (OperatingTimeType.equals("EnterIDNumber")) {
                        tv_OperatingTime.setText("操作时间 " + OperatingTime + " 秒");
                    } else if (OperatingTimeType.equals("Loding")) {
                        tv_OperatingTime.setText(OperatingTime + " 秒");
                    }
                    OperatingTimeHandler.sendEmptyMessageDelayed(1, 1000);
                } else {
                    if (OperatingTimeType.equals("Loding")) {
                        OperatingTimeType = "Results";
                        OperatingTime = 3;
                        OperatingTimeHandler.sendEmptyMessageAtTime(1, 1000);
                    } else {
                        IDCardView.this.sendMessage("手输证件号超时");
                        try {
                            if (EnterWindowManager != null) {
                                EnterWindowManager.removeView(IDCardView.this);
                                EnterWindowManager = null;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    };

    public IDCardView(Context context,    BaseAmpeRequestBean requestBean) {
        super(context);
        this.requestBean=requestBean;
        init(context);
    }



    private void init(Context context) {
        if (Constants.DeviceModel.D2.equals(DeviceUtils.getDeviceModel())) {
            LayoutInflater.from(context).inflate(R.layout.window_enter_idnumber_hp, this);
        } else {
            LayoutInflater.from(context).inflate(R.layout.window_enter_idnumber_sp, this);
        }
        EnterWindowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        WindowManagerInitView(context, this);
        int type;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;// 系统提示window
        }
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                type,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN//将window放置在整个屏幕之内,无视其他的装饰(比如状态栏)
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS//允许window扩展值屏幕之外
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN//当这个window显示的时候,隐藏所有的装饰物(比如状态栏)这个flag允许window使用整个屏幕区域
                        | WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER,//标记在其它窗口的LayoutParams.flags中的存在情况而不断地被调整
                PixelFormat.RGBA_8888
        );
        //展示悬浮view
        EnterWindowManager.addView(this, layoutParams);
    }




    private void WindowManagerInitView(Context context, View view) {
        EnterIDNumberActivity_GridView = view.findViewById(R.id.EnterIDNumberActivity_GridView);
        EnterIDNumberActivity_edit = view.findViewById(R.id.EnterIDNumberActivity_edit);
        tv_OperatingTime = view.findViewById(R.id.tv_OperatingTime);
        enterIDCard_RelativeLayout = view.findViewById(R.id.enterIDCard_RelativeLayout);
        //加载中
        enterIDCard_Loding = view.findViewById(R.id.enterIDCard_Loding);
        enterIDCard_LodingText = view.findViewById(R.id.enterIDCard_LodingText);
        enterIDCard_LodingImageView = view.findViewById(R.id.enterIDCard_LodingImageView);
        EnterIDNumberActivity_SureClick = view.findViewById(R.id.EnterIDNumberActivity_SureClick);
        EnterIDNumberActivity_CancelClick = view.findViewById(R.id.EnterIDNumberActivity_CancelClick);
        EnterIDNumberActivity_RelativeLayout = view.findViewById(R.id.EnterIDNumberActivity_RelativeLayout);
        ivBg=view.findViewById(R.id.iv_bg);
        EnterIDNumberActivity_SureClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String edit = EnterIDNumberActivity_edit.getText().toString();
                if (!IdCardUtils.isValidatedAllIdcard(edit)) {//不符合
                    //重置悬浮框时间
                    OperatingTime = 30;
                    //添加输入框文字变红
                    EnterIDNumberActivity_edit.setTextColor(getResources().getColor(R.color.fFF3141));
                    //添加输入框抖动效果
                    IdCardUtils.ditheringAnimation(EnterIDNumberActivity_edit, context);
                } else {
                    EnterIDNumberActivity_edit.setTextColor(getResources().getColor(R.color.black));
                    long now = System.currentTimeMillis();
                    if (now - lastClickTime > 1000) {
                        lastClickTime = now;
                        sendEnterIDNumber(edit);
                    }
                }
            }
        });
        EnterIDNumberActivity_CancelClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage("取消手输证件号");
            }
        });
        //关闭键盘弹出
        EnterIDNumberActivity_edit.setInputType(InputType.TYPE_NULL);
        EnterIDNumberActivity_edit.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                EnterIDNumberActivity_edit.setInputType(InputType.TYPE_NULL); //关闭软键盘
                return false;
            }
        });
        if (Constants.DeviceModel.D2.equals(DeviceUtils.getDeviceModel())) {
            ImageLoaderUtils.Companion.loadRes(ivBg.getContext(),R.mipmap.bg_enter_hp,ivBg);
        } else {
            ImageLoaderUtils.Companion.loadRes(ivBg.getContext(),R.mipmap.bg_enter_sp,ivBg);
        }
        OperatingTimeHandler.sendEmptyMessageDelayed(1, 1000);
        list.clear();
        for (int i = 1; i < 13; i++) {
            if (i == 10) {
                list.add("X");
            } else if (i == 11) {
                list.add("0");
            } else {
                list.add(i + "");
            }
        }
        gridadapter = new Gridadapter(list, context);
        EnterIDNumberActivity_GridView.setAdapter(gridadapter);
        gridadapter.setListener(new Gridadapter.OnItemClickListener() {
            @Override
            public void onItemClick(String position) {
                OperatingTime = 30;
                if (position.equals("12")) {//删除
                    Editable editable = EnterIDNumberActivity_edit.getText();
                    EnterIDNumberActivity_edit.setSelection(EnterIDNumberActivity_edit.length());
                    int start = EnterIDNumberActivity_edit.getSelectionStart();
                    if (editable != null && editable.length() > 0 && start > 0) {
                        editable.delete(start - 1, start);
                    }
                } else {
                    String edit = EnterIDNumberActivity_edit.getText().toString();
                    EnterIDNumberActivity_edit.setText("");
                    EnterIDNumberActivity_edit.setText(edit + position);
                }
            }
        });
        //   initNet();
    }

    //点击确定进下网络请求
    private void sendEnterIDNumber(String IDNumber) {

        OperatingTimeType = "Loding";
        OperatingTime = 15;
        enterIDCard_Loding.setVisibility(View.VISIBLE);
        enterIDCard_RelativeLayout.setVisibility(View.GONE);
        enterIDCard_LodingText.setText("联网查询中……");
        enterIDCard_LodingText.setTextColor(getResources().getColor(R.color.f3D73FF));

        ImageLoaderUtils.Companion.loadRes(enterIDCard_LodingImageView.getContext(),R.mipmap.enter_idnumber_loding,
                enterIDCard_LodingImageView);
        //常口换取三要素
        long timecurrentTimeMillis = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("sfzh", IDNumber);
        //公安网密钥
        DeviceConfigResultBean.ManualInIdCardAuthDTO manualInIdCardAuthDTO = new DeviceConfigResultBean.ManualInIdCardAuthDTO();
        DeviceConfigResultBean deviceConfigBean= ConfigData.getDeviceConfigResultBean();
      //  deviceConfigBean.setManualInIdCardAuth(manualInIdCardAuthDTO);
        if(deviceConfigBean.getManualInIdCardAuth()==null){
            deviceConfigBean.setManualInIdCardAuth(new DeviceConfigResultBean.ManualInIdCardAuthDTO());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("appId", deviceConfigBean.getManualInIdCardAuth().getAppId());
        map.put("bizContent", IdCardUtils.encrypt(
                deviceConfigBean.getManualInIdCardAuth().getPrivateKey(),
                JSON.toJSONString(params)
        ));
        map.put("reqTimestamp", timecurrentTimeMillis + "");
        map.put("sign", IdCardUtils.getSign(deviceConfigBean.getManualInIdCardAuth().getAppKey(),
                deviceConfigBean.getManualInIdCardAuth().getAppSecret(),
                timecurrentTimeMillis + ""));
        AppLogUtils.i("常口输入请求入参 " +GsonUtils.getGson().toJson(map));
        EventBus.getDefault().post(new RequestThreeElementsEvent(map,
                "https://tx.hz-hanghui.com:8088/hanghui-server-platform/api/v1/open/user/sync/query"));

    }


    private void sendMessage(String Message) {

        if (requestBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(Constants.Ampe.ACTION_ENTERIDNUMBER);
        bean.setEvent(requestBean.getEvent());
        bean.setTaskId(requestBean.getTaskId());
        bean.setSuccess(false);
        bean.setMessage(Message);
        AromeServiceInvoker.BridgeCallback bridgeCallback = requestBean.getBridgeCallback();
        release();
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("jsonObject = ").append(jsonObject);
            UploadLogUtils.sendLogs("ACTION_FACE--刷脸--用户三要素--回传处理结果给小程序--",
                    Constants.Ampe.ACTION_ENTERIDNUMBER,logLine,logContentSb.toString());
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    public void release(){
        try {
            if (EnterWindowManager != null) {
                EnterWindowManager.removeView(this);
                EnterWindowManager = null;
            }else {
                EnterWindowManager = (WindowManager) getContext().getApplicationContext()
                        .getSystemService(Context.WINDOW_SERVICE);
                if (EnterWindowManager != null) {
                    EnterWindowManager.removeView(this);
                    EnterWindowManager = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        OperatingTimeHandler.removeMessages(1);
        OperatingTimeHandler.removeCallbacksAndMessages(null);
    }

}
