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

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

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.R;
import com.hw.nativeapp.utils.ActivityUtils;


import butterknife.BindView;
import butterknife.OnClick;


public class TakeActivity extends BaseActivity  {

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

    boolean hasPermission;

    @BindView(R.id.et_modify_quantity)
    TextView et_modify_quantity;

    private IDCardServiceAidl mService;

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

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

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        startCountDownTimer();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take);
        registerReceiver();
    }
    @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 (receiver != null){
            unregisterReceiver(receiver);
        }
        if (mConnection != null) {
            try {
                unbindService(mConnection);
                Toast.makeText(TakeActivity.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.purchase_btn, R.id.num_01,R.id.num_02,R.id.num_03,R.id.num_04,R.id.num_05,R.id.num_06,R.id.num_07,R.id.num_08,R.id.num_09,R.id.num_0,R.id.num_empty,R.id.num_del})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.purchase_btn:
                Bundle bundle = new Bundle();
                bundle.putString("qrcodeNo", et_modify_quantity.getText().toString());
                ActivityUtils.launchActivity(this, TicketCollectionActivity.class, bundle);
                break;
            case R.id.num_01:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"1");
                break;
            case R.id.num_02:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"2");
                break;
            case R.id.num_03:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"3");
                break;
            case R.id.num_04:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"4");
                break;
            case R.id.num_05:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"5");
                break;
            case R.id.num_06:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"6");
                break;
            case R.id.num_07:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"7");
                break;
            case R.id.num_08:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"8");
                break;
            case R.id.num_09:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"9");
                break;
            case R.id.num_0:
                et_modify_quantity.setText(et_modify_quantity.getText().toString()+"0");
                break;
            case R.id.num_empty:
                et_modify_quantity.setText("");
                break;
            case R.id.num_del:
                String str = et_modify_quantity.getText().toString();
                et_modify_quantity.setText(str.substring(0, str.length() - 1));
                break;
        }
    }
    private void jumpToLogin(){
        stopCountDownTimer();
        ActivityUtils.activityFinish(TakeActivity.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 BroadcastReceiver receiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String code = intent.getStringExtra("data");
            if (code != null && !code.isEmpty())
            {
//                mCode.setText(code);
            }
        }
    };
    // 扫码注册
    private void registerReceiver()
    {
        IntentFilter fifilter = new IntentFilter();
        fifilter.addAction("com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED");
        registerReceiver(receiver, fifilter);
    }

    // 身份证注册
    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(TakeActivity.this, "服务已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            Log.e("id_card", "服务已断开");
            Toast.makeText(TakeActivity.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());
                        // info.getName(); // 姓名
                        // info.getIdCard(); // 身份证号
                        Bundle bundle = new Bundle();
                        bundle.putString("idcard", info.getIdCard());
                        ActivityUtils.launchActivity(TakeActivity.this, TicketCollectionActivity.class, bundle);
                    } 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();
        }
    }
}