package com.hh.arome.ui;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hh.arome.R;
import com.hh.arome.bean.DeviceConfigResultBean;
import com.hh.arome.bean.LogcatAddRequestBean;
import com.hh.arome.bean.SimpleResultBean;
import com.hh.arome.bean.ampe.AmpeAppletResultBean;
import com.hh.arome.common.ConfigData;
import com.hh.arome.common.Constants;
import com.hh.arome.common.scan.idcard.IDCardScan;
import com.hh.arome.common.scan.idcard.bean.IDCardInfoBean;
import com.hh.arome.common.scan.idcard.callback.IDCardInitResultCallback;
import com.hh.arome.common.scan.idcard.callback.IDCardScanResultCallback;
import com.hh.arome.mvp.contract.LogcatAddContract;
import com.hh.arome.mvp.presenter.LogcatAddPresenter;
import com.hh.arome.ui.base.BaseHHActivity;
import com.hh.arome.utlis.device.DeviceUtils;
import com.hh.arome.utlis.log.AppLogUtils;
import com.hh.arome.utlis.log.LogType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.hh.arome.common.Constants.Ampe.ACTION_IDCard;
import static com.hh.arome.common.Constants.Ampe.AMPE_EVENT;
import static com.hh.arome.common.Constants.LogcatValue.LINE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_IDCARD;
import static com.hh.arome.common.Constants.LogcatValue.NET_LOGCAT;
import static com.hh.arome.common.Constants.LogcatValue.NODE;
import static com.hh.arome.common.Constants.LogcatValue.WARP;
import static com.hh.arome.common.Constants.Value.TOKEN;

public class IDCardScanActivity extends BaseHHActivity implements LogcatAddContract.View {

    LogcatAddPresenter mLogcatAddPresenter;

    private View mBoottomView;


    String deviceModel = DeviceUtils.getDeviceModel();

    @Override
    public int setLayout() {
        super.setHideTopBar();

        AppLogUtils.e("IDCardScanActivity");

        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            return R.layout.activity_idcard_scan_hp;
        } else {
            return R.layout.activity_idcard_scan;
        }
    }


//    @Override
//    protected void initView() {
//        super.setHideTopBar();
//    }

    @Override
    public void setStatusBar() {
//        super.setStatusBar();

    }

    TextView tv_time;
    LinearLayout item_close;


    @Override
    protected void initView() {
        super.setHideTopBar();

        //
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);


        tv_time = findViewById(R.id.tv_time);
        item_close = findViewById(R.id.item_close);


        // 时间
        resh.mainHandler.postDelayed(resh.runnable, 1000);// 每兩秒執行一次runnable.


    }

    Integer idCardReaderBrand;

    @Override
    protected void initData() {

        mLogcatAddPresenter = new LogcatAddPresenter(this);

        EventBus.getDefault().register(this);


        // 日志开始保存----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = LOG_NODE_IDCARD + "身份证---开始调用识别---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP);

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean logBean = new LogcatAddRequestBean();
        logBean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        logBean.setLogTag(logLine + WARP + LOG_NODE_IDCARD);
        logBean.setLogContent(logContentSb.toString());
        requestLogcatAdd(logBean);
        // 日志开始保存----------------end


        DeviceConfigResultBean deviceConfigBean = ConfigData.getDeviceConfigResultBean();
        if(deviceConfigBean == null){
            getIdCardReaderBrandByModel();
        }else{
            idCardReaderBrand = deviceConfigBean.getIdCardReaderBrand();
        }


        AppLogUtils.e("初始值--idCardReaderBrand = " + idCardReaderBrand);
        if(idCardReaderBrand==null){
            getIdCardReaderBrandByModel();
        }
        AppLogUtils.e("最后的--idCardReaderBrand = " + idCardReaderBrand);


        IDCardScan.with(mActivity,idCardReaderBrand).initIDCard(new IDCardInitResultCallback() {
            @Override
            public void onIDCardInitSuccess() {
                AppLogUtils.e(mTag+"初始化成功");
            }

            @Override
            public void onIDCardInitError(String errorCode, String errorMsg) {
                AppLogUtils.e(mTag+"初始化失败");
            }
        });


        // 根据不同的设备取值
        IDCardScan.with(mActivity,idCardReaderBrand).startScanIDCard(new IDCardScanResultCallback() {
            @Override
            public void onIDCardScanSuccess(IDCardInfoBean idCardInfoBean) {

                AppLogUtils.e(idCardInfoBean.toString());


                AmpeAppletResultBean bean = new AmpeAppletResultBean();
                bean.setAction(ACTION_IDCard);
                bean.setEvent(AMPE_EVENT);
                bean.setTaskId("");
                bean.setSuccess(true);
                bean.setMessage("成功");

                AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
                dataBean.setName(idCardInfoBean.getIdcardName());
                dataBean.setIdNum(idCardInfoBean.getIdcardNumber());
                dataBean.setSex(idCardInfoBean.getSex());
                dataBean.setBeginTime(idCardInfoBean.getBeginTime());
                dataBean.setEndTime(idCardInfoBean.getEndTime());
                dataBean.setBirthDate(idCardInfoBean.getBirth());
                dataBean.setPhotoBase64(idCardInfoBean.getPhotoBase64());
                dataBean.setNation(idCardInfoBean.getNation());
                dataBean.setAddress(idCardInfoBean.getAddress());

                // 设置数据
                bean.setData(dataBean);

                // 在MainActivity中的receiveIDCardResult接收
                EventBus.getDefault().post(bean);


                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        // 跳转到
                        mActivity.finish();
                    }
                }, 1000);

            }

            @Override
            public void onIDCardError(String resCode, String resMsg) {
                AppLogUtils.e("resCode:"+resCode+"---resMsg:"+resMsg);
            }
        });



    }

    private void getIdCardReaderBrandByModel() {
        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            // D2
            idCardReaderBrand = 2;
        } else if (Constants.DeviceModel.K8.equals(deviceModel)) {
            // K8
            idCardReaderBrand = 1;
        } else {
            idCardReaderBrand = 1;
        }
    }

    @Override
    protected void initListener() {
        item_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }




    @Override
    protected void onPause() {
        super.onPause();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if(mLogcatAddPresenter!=null){
            mLogcatAddPresenter = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveIDCardResult(AmpeAppletResultBean resultBean) {

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (mBoottomView != null) {
            AppLogUtils.e("当前事件是" + this.getClass().getName() + "传递");
            mBoottomView.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();



    }


    @Override
    public void onBackPressed() {
        mActivity.finish();
//        overridePendingTransition(R.anim.bottom_no, R.anim.bottom_out);
    }

    private void requestLogcatAdd(LogcatAddRequestBean logBean) {

        if (mLogcatAddPresenter == null) {
            mLogcatAddPresenter = new LogcatAddPresenter(this);
        }

        logBean.setToken(TOKEN);
        logBean.setSn(DeviceUtils.getDeviceSN());

        mLogcatAddPresenter.requestLogcatAdd(logBean);
    }

    @Override
    public void showLogcatAddResult(SimpleResultBean resultBean) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void showError(String url, String msg) {

    }


    RefreshPage resh = new RefreshPage();
    int time = 20;

    class RefreshPage {
        Handler mainHandler = new Handler();
        // 倒计时任务
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                if (time == 0) {
                    finish();
                    return;
                }

                // 设置最新时间
                tv_time.setText(time-- + "s");
                // 接着发送刷新任务
                mainHandler.postDelayed(this, 1000);
            }
        };
    }


}
