package com.fxy.mine;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.elvishew.xlog.XLog;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lzy.okgo.OkGo;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.R;
import com.fxy.bean.ScanBean;
import com.fxy.helper.ScanHelper;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import sto.android.app.StoPdaKeyEvent;
import sto.android.app.StoTongJNI;

/**
 * 蓝牙设置
 *
 * @author James.Jiang
 * @date 2020-03-10
 */
public class ScanSettingActivity extends BaseActivity {
    private Context mContext = this;


    @BindView(R.id.mt_select_device)
    MaterialSpinner deviceSpinner;

    private Integer selectDeviceId=0;

    @BindView(R.id.btn_scan)
    Button btnScan;


    //设备设置信息
    @BindView(R.id.et_scan_test)
    EditText etScanTest;
    @BindView(R.id.ib_scan_test_clear)
    ImageButton ibScanTestClear;


    @BindView(R.id.et_device_name)
    EditText etDeviceName;
    @BindView(R.id.et_action)
    EditText etAction;
    @BindView(R.id.et_data_name)
    EditText etDataName;
    @BindView(R.id.et_action_start)
    EditText etActionStart;
    @BindView(R.id.et_action_stop)
    EditText etActionStop;
    @BindView(R.id.ms_mode_list)
    MaterialSpinner modeSpinner;
    //默认是
    private Integer selectId=0;
    //获取厂商code
    private String manufacturer = "";
    //设备型号
    private String device_model = "";


    private ScanHelper scanHelper;



    private ScanBean scanBean;


    private  JSONArray scanList;

    @Override
    public boolean isPlayMusic() {
        return true;
    }



    private Unbinder unbinder;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_scan_setting;
    }

    @Override
    public boolean showToolBar() {
        return true;
    }

    @Override
    public boolean openEventBus() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }
    //监听按钮按键
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        return super.dispatchKeyEvent(event);
    }

    //监听按键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //System.out.println("############映射前key:" + keyCode);
        if (scanBean.getIsBroadcast()==0 && StoTongJNI.getIns(mContext).getEventFuction(keyCode)  == StoPdaKeyEvent.KEYCODE_SCAN
                && event.getRepeatCount() == 0) {

            if (StoTongJNI.getIns(mContext).GetScannerIsScanning()) {

            } else {
                StoTongJNI.getIns(mContext).SetScannerStart();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName(getString(R.string.user_sweep_code));
        scanHelper =  new ScanHelper(mContext);
        manufacturer = scanHelper.getManufacturer();
        device_model = scanHelper.getDeviceModel();

        iniShow();
        initEdit();


    }
    private void initEdit() {

        etScanTest.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 ) {
                    ibScanTestClear.setVisibility(View.VISIBLE);
                } else {
                    ibScanTestClear.setVisibility(View.INVISIBLE);
                }
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {

            }
        });
        ibScanTestClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etScanTest.requestFocus();
                etScanTest.getText().clear();
            }
        });
    }

    private void iniShow(){
        scanBean = JsonUtil.getObject(scanHelper.getScanSetTing(), ScanBean.class);
        selectId = scanBean.getBroadcast()==1?0:1;

        List<String> spinnerList = new ArrayList<String>();
        spinnerList.add("广播模式");
        spinnerList.add("接口模式");
        modeSpinner.setItems(spinnerList);
        modeSpinner.setSelectedIndex(selectId);
        modeSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                selectId = position;

                if (selectId==1 && scanBean.getIsApi()!=1){
                    showWarningToast("巴枪不支持接口模式");
                    selectId = 0;
                    modeSpinner.setSelectedIndex(selectId);
                    return;
                }

                try {
                    scanHelper.scanStop(mReceiver);
                    String scanStr = scanList.getString(selectDeviceId);
                    scanHelper.setCurrentMode(selectId+1);
                    scanHelper.initReceiver(mReceiver,scanHandler,scanStr);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        getDeviceName();

    }
    /**
     *
     */
    private void getDeviceName(){
        try {
            OkGo.<String>get(Urls.getScanSetting(mContext) + "?v=" + UUID.randomUUID().toString())
                    .execute(new MyDialogCallback(mContext, false, false) {
                        @Override
                        public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                            try {

                                scanList = new JSONArray(response.body().toString());
                                List<String> spinnerDeviceList = new ArrayList<String>();
                                for (int i = 0;i < scanList.length(); i++){
                                    JSONObject jsonObject =scanList.getJSONObject(i);
                                    spinnerDeviceList.add(jsonObject.getString("device_name"));


                                    if (scanBean.getCanId()>0){
                                        if (scanBean.getCanId()==jsonObject.getInt("scan_id")){
                                            selectDeviceId = i;
                                        }
                                    }else{

                                        //为兼容旧的缓存
                                        String tmpManufacturer = jsonObject.has("manufacturer")?jsonObject.getString("manufacturer"):"";
                                        String tmpModel = jsonObject.has("device_model")?jsonObject.getString("device_model"):"";

                                        //没有选中设置时，默认选中统一厂商的配置
                                        if (scanBean==null && tmpManufacturer.equals(manufacturer)){
                                            selectDeviceId = i;
                                        }
                                        //匹配到厂商跟设备型号一致的 并且结束
                                        if (tmpManufacturer.equals(manufacturer) && tmpModel.contains(device_model)){
                                            selectDeviceId = i;
                                        }
                                    }
                                }


                                deviceSpinner.setItems(spinnerDeviceList);
                                deviceSpinner.setSelectedIndex(selectDeviceId);
                                deviceSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
                                    @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                                        // XLog.e(id);XLog.e(item);
                                        selectDeviceId = position;
                                        try {
                                            scanBean = JsonUtil.getObject(scanList.getString(selectDeviceId), ScanBean.class);
                                            selectId = 0;
                                            modeSpinner.setSelectedIndex(selectId);


                                            scanHelper.scanStop(mReceiver);
                                            scanHelper.initReceiver(mReceiver,scanHandler,scanList.getString(selectDeviceId));

                                        } catch (JSONException e) {
                                            e.printStackTrace();

                                            XLog.e("巴枪切换错误:",e);
                                        }


                                    }
                                });



                            } catch (JSONException e) {
                                Toasty.error(mContext, "获取扫码设置错误").show();
                                e.printStackTrace();
                            }
                        }
                    });



        }catch (Exception e){
            XLog.e("数据错误:",e);
        }
    }

    //把扫描结果赋值
    private void setScanResult(String scanResult){
        //获取焦点的view对象
        View view=getWindow().getDecorView().findFocus();
        //如果是EditText
        if(view instanceof EditText)
        {
            ((EditText) view).setText(scanResult);
        }
    }
    @SuppressLint("HandlerLeak")
    Handler scanHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.obj != null) {
                String scanResult = msg.obj.toString().trim();
                if (!scanResult.isEmpty()){
                    setScanResult(scanResult);
                }
            }
        }

    };

    /**
     * 定义广播接受
     */
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String scanResult = scanHelper.getScanResult(scanBean,intent);
            if (scanResult!=null && !scanResult.isEmpty()){
                setScanResult(scanResult);
            }else{
                showErrorToast(getString(R.string.scan_failed));
            }

        }
    };

    /**
     * 注册广播
     */
    private void initReceiver(){
        try {
            scanHelper.initReceiver(mReceiver,scanHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @OnClick({  R.id.btn_scan})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                saveData();
                break;
        }

    }
    private void saveData(){
        int is_broadcast = selectId==0?1:0;
        if (is_broadcast ==0 &&scanBean.getIsApi()!=1){
            showWarningToast("巴枪不支持接口模式");
            return;
        }

        //凯立JNI  模式必须是凯立巴枪
        if (scanBean.getManufacturer().equals("kaicom") && !manufacturer.equals("kaicom")){
            showWarningToast("设备不是凯立");
            return;
        }


        scanBean.setIsBroadcast(is_broadcast);

        if (scanHelper.saveData(scanBean)){
            showSuccessToast(getString(R.string.str_save_success));
            finish();
        }else{
            showWarningToast("保存失败");
        }

    }

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        //停止扫描
        scanHelper.scanStop(mReceiver);
    }



}
