package com.hw.nativeapp.ui.activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.sunmi.idcardservice.CardCallback;
import com.sunmi.idcardservice.IDCardInfo;
import com.sunmi.idcardservice.IDCardServiceAidl;
import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.R;
import com.hw.nativeapp.httpnet.ErrorConsumer;
import com.hw.nativeapp.httpnet.ResponseConsumer;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.MaskUtil;
import com.hw.nativeapp.utils.RxUtil;

import butterknife.OnClick;


public class InfoEnterActivity extends BaseActivity  {

    public static final Integer COUNTDOWN_TIME = 120000;
    private CountDownTimer timer;
    private TitleBar titleBar;

    private String performId = "";
    private String auditoriumId = "";
    private String date = "";
    private String goodsId = "";
    private String salePeice = "";
    private String performTimeId = "";
    private String seatTypeId = "";

    private String name = "";
    private String idcard = "";
    private JSONArray viewerList = new JSONArray();

    private IDCardServiceAidl mService;
    boolean hasPermission;
    private ProgressDialog progressDialog;

    @Override
    void initView() {
        titleBar = findViewById(R.id.tb_main_bar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                ActivityUtils.activityFinish(InfoEnterActivity.this, true );
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        getPageTransmitParams();
        startCountDownTimer();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_enter);
        bindIDCardService();
    }
    @Override
    protected void onStart() {
        super.onStart();
        hasPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (!hasPermission) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (mService != null) {
            try {
                mService.cancelAutoReading();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnection != null) {
            try {
                unbindService(mConnection);
//                Toast.makeText(InfoEnterActivity.this, "ID服务已断开", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mService = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101) {
            hasPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
        }
    }
    @OnClick({R.id.idCard_btn})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.idCard_btn:
                Bundle bundle = new Bundle();
                bundle.putString("performId", performId);
                bundle.putString("auditoriumId", auditoriumId);
                bundle.putString("performTimeId", performTimeId);
                bundle.putString("seatTypeId", seatTypeId);
                bundle.putString("goodsId", goodsId);
                bundle.putString("salePeice", salePeice);
                bundle.putString("type", "1");
                ActivityUtils.launchActivity(this,InfoInputActivity.class, bundle);
                break;
        }
    }
    //获取页面传递参数
    private void getPageTransmitParams(){
        Intent transmitIntent = getIntent();
        performId = transmitIntent.getStringExtra("performId");
        auditoriumId = transmitIntent.getStringExtra("auditoriumId");
        goodsId = transmitIntent.getStringExtra("goodsId");
        salePeice = transmitIntent.getStringExtra("salePeice");
        performTimeId = transmitIntent.getStringExtra("performTimeId");
        seatTypeId = transmitIntent.getStringExtra("seatTypeId");
    }
    private void jumpToLogin(){
        stopCountDownTimer();
        ActivityUtils.activityFinish(InfoEnterActivity.this, true);
    }
    private void stopCountDownTimer(){
        if (timer != null){
            timer.cancel();
        }
    }
    private void startCountDownTimer(){
        timer = new CountDownTimer(COUNTDOWN_TIME, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                titleBar.setRightTitle(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                jumpToLogin();
            }
        };
        timer.start();
    }

    // 身份证注册
    private void bindIDCardService() {
        Intent intent = new Intent();
        intent.setPackage("com.sunmi.idcardservice");
        intent.setAction("com.sunmi.idcard");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IDCardServiceAidl.Stub.asInterface(service);
            Log.e("id_card", " 服务已连接");
//            Toast.makeText(InfoEnterActivity.this, "服务已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            Log.e("id_card", "服务已断开");
            Toast.makeText(InfoEnterActivity.this, "服务已断开", Toast.LENGTH_SHORT).show();
        }
    };
    public void auto(View view) {
        try {
            mService.readCardAuto(new CardCallback.Stub() {
                @Override
                public void getCardData(final IDCardInfo info, int code) {
                    Log.i(TAG, "getCardData: code=" + code + ", id info:" + info);
                    if (code == 10) {
                        //读取成功
                        Log.i(TAG, "getCardData: " + info.toString());
                        name = info.getName(); // 姓名
                        idcard = info.getIdCard(); // 身份证号
                        factorAuth();
                    } else if (code == -10) {
                        //读取失败
                        Log.i(TAG, "auto read card did not get data");
                    } else {
                        Log.i(TAG, "what is wrong");
                    }
                }
            });
        } catch (Exception e) {
            Log.i(TAG, "auto read is error " + e.getMessage());
            e.printStackTrace();
        }
    }
    public void cancelAuto(View v) {
        try {
            mService.cancelAutoReading();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 二要数认证
    private void factorAuth(){
        if(name.isEmpty() || idcard.isEmpty()){
            ToastUtils.showShort("请输入姓名和身份证号");
            return;
        }
        if(name.length() < 2 || idcard.length() < 18){
            ToastUtils.showShort("姓名和身份证号格式错误");
            return;
        }
        JSONObject options = new  JSONObject();
        options.put("name", name);
        options.put("idcard", idcard);
        progressDialog = MaskUtil.showProgressDialog( "正在验证...", InfoEnterActivity.this);
        new Handler().postDelayed(() -> {
            if(progressDialog != null){
                progressDialog.dismiss();
            }
        }, 30000);
        MApplication.getApiService().factorAuth( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        if(data.getIntValue("status") == 1) {
                            if(progressDialog != null){
                                progressDialog.dismiss();
                            }
                            successFu();
                        } else {
                            if(progressDialog != null){
                                progressDialog.dismiss();
                            }
                            ToastUtils.showShort(data.getString("errReason"));
                        }
                    }

                    @Override
                    public void onFailed(int code, String msg) {
                        if(progressDialog != null){
                            progressDialog.dismiss();
                        }
                    }
                }, new ErrorConsumer());
    }

    private void successFu () {
        Bundle bundle = new Bundle();
        bundle.putString("performId", performId);
        bundle.putString("auditoriumId", auditoriumId);
        bundle.putString("performTimeId", performTimeId);
        bundle.putString("seatTypeId", seatTypeId);
        bundle.putString("goodsId", goodsId);
        bundle.putString("salePeice", salePeice);
        bundle.putString("type", "1");
        bundle.putString("name", name);
        bundle.putString("idcard", idcard);
        if(viewerList == null || viewerList.size() == 0){
            viewerList =  new JSONArray();
        }
        JSONObject obj = new JSONObject();
        obj.put("name", name);
        obj.put("idcard", idcard);
        viewerList.add(obj);
        bundle.putString("viewerList", JSONArray.toJSONString(viewerList));
        ActivityUtils.launchActivity(this,PurchaseInfoActivity.class, bundle);
    }
}