package com.fxy.tool;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.elvishew.xlog.XLog;
import com.fxy.R;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.interfaces.OnRxScanerListener;
import com.fxy.baselibrary.qrcode.ActivityScanerCode;
import com.fxy.baselibrary.util.DateUtil;
import com.fxy.baselibrary.util.HideUtil;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.realm.ToolScanRealm;
import com.fxy.tool.bean.ToolBean;
import com.fxy.tool.bean.ToolDetailBean;
import com.fxy.view.FloatingImageView;
import com.google.zxing.Result;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import sto.android.app.StoJNI;
import sto.android.app.StoPdaKeyEvent;
import sto.android.app.StoTongJNI;

public class OrderToolMainActivity extends  BaseActivity implements StoJNI.ScanCallBack {
    /**
     * 列表适配器
     */
    Context mContext = this;

    //单号清除
    @BindView(R.id.ib_order_no_clear)
    ImageButton ibOrderNoClear;

    //单号
    @BindView(R.id.et_order_no)
    EditText etOrderNo;




    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    //浮动按钮
    @BindView(R.id.iv_drag)
    FloatingImageView iv_drag;




    private View notDataView;   //没有数据显示页
    private View errorView;     //错误显示页
    private View emptyView;     //空显示页
    /**
     * 列表适配器
     */
    private FinishWorkAdapter mAdapter;

    //扫码扫码动作
    private ScanBean scanBean;



    private List<ToolBean> batchList = new ArrayList<>()   ;
    private JSONObject batchDetails ;
    //扫描数据
    private List<ToolDetailBean> scanShowList = new ArrayList<>()   ;

    //扫描记录
    //private JSONObject scanOrderList = new JSONObject()  ; citys = new String[jsonArray.length()][];

    private String scanBatch = "";

    private Map<Integer,List<ToolDetailBean>> cacheList = new HashMap<>();
    private Unbinder unbinder;



    @BindView(R.id.ms_batch)
    MaterialSpinner batchSpinner;
    //默认是
    private Integer batchIdx=0;

    // 默认校验
    private boolean isVerify = true;

    //是否开启声音
    private boolean isSound = true;


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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {

    }
    //finish的返回监听
    //这里的requestCode参数，就是上面设置的 1 ，当跳转的页面返回的时候，通过这个加以判断
    //resultCode ,这个参数是在跳转的页面里面规定的，它也是一个int类型的标志
    //第三个参数包含了返回的值
    //如果不需要所跳转的页面返回值，也就不需要这个方法了
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        XLog.e("requestCode："+requestCode);
//        XLog.e("resultCode："+resultCode);
        if (requestCode == 200 && resultCode == 200)//之前提到的两个标志，在这里显示出了作用
        {
        }else if (resultCode==0){
        }
    }


    /**
     * EventBus接收信息的方法，开启后才会调用(非粘性事件)
     *
     * @param event
     */
    @Override
    protected void EventBean(BaseEventBusBean event) {
//        XLog.e("----------接收返回--------------");
//        XLog.e("接收返回："+event.getEventCode());
        if (event != null && event.getEventCode() == EventCode.displacement_refresh){

        }
    }

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

    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("小工具");


        initAdapter();
        initData();
        initEdit();
        //监听浮动按钮
        iv_drag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!iv_drag.isDrag()){
                    ActivityScanerCode.setScanerListener(mScanerListener);
                    ActivityScanerCode.intent2Activity(mContext, BaseConfig.COMMON_SCANNER_ONLY);
                }
            }
        });

        //
        scanBatch = UUID.randomUUID().toString();

    }

    protected void showBack() {
        super.showBack();
        tb_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = cheatPush();
                if (num>0){
                    showErrorToast("还有"+num+"条数据未上传成功");

                }else{
                    HideUtil.hideSoftKeyboard(OrderToolMainActivity.this);
                    if (isShowBackDialog) {
                        onBackPressedSupport();
                    } else {
                        finish();
                    }
                }

            }
        });
    }


    protected void intSpinner(){
        List<String> spinnerList = new ArrayList<String>();
        for (int i = 0;i < batchList.size(); i++){
            spinnerList.add(batchList.get(i).getBatchName());
        }
        batchSpinner.setItems(spinnerList);
        batchSpinner.setSelectedIndex(batchIdx);
        batchSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                try {

                    batchIdx = position;
                    isVerify = batchList.get(position).getRules() == 1;


                    List<ToolDetailBean> tmpList = new ArrayList<>();

                    if (cacheList.get(position)!=null){
                        tmpList = cacheList.get(position);
                    }else{
                        tmpList.clear();
                        mAdapter.setEmptyView(emptyView);
                    }


                    scanShowList.clear();
                    scanShowList.addAll(tmpList);
                    Collections.reverse(scanShowList);
                    mAdapter.setNewData(scanShowList);
                    mAdapter.notifyDataSetChanged();


                }catch (Exception e){
                    XLog.e("切换包错误",e.getMessage());
                }

                getDetails();


            }
        });


    }



    private void initData(){
        try {
            final JSONObject jsonObject = new JSONObject();
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_GET_BATCH_LIST).upJson(jsonObject)
                    .execute(new MyDialogCallback(this, true, true) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            super.onSuccess(response);
                            try {
                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                if(bean.code == 1){
                                    batchList = JsonUtil.jsonString2Beans(bean.data, ToolBean.class);
                                    intSpinner();
                                    getDetails();
                                    isVerify = batchList.get(0).getRules() == 1;
                                    etOrderNo.setEnabled(true);
                                    etOrderNo.requestFocus();
                                }else{
                                    showWarningToast(bean.msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                showEmptyView("批次信息解析错误:"+e.getMessage());
                                XLog.e("获取批次信息解析错误",e.getMessage());
                            }
                        }
                    });


            //查询

//            RealmQuery query = mRealm.where(ToolScanRealm.class);
//            RealmResults list = query.findAll();
//            if(list==null || list.size()==0){
//                XLog.e( "query: no data!" );
//            }else{
//                XLog.e("query: size: "+list.size());
//                ToolScanRealm tmpRealm = (ToolScanRealm) list.get(0);
//                XLog.e("query: "+tmpRealm.getNumber() );
//            }

        }catch (Exception e){
            batchList.size();
            XLog.e("请求批次信息错误:"+e.getMessage(),e);
        }
    }


    /**
     * 获取批次详情
     */
    private void getDetails(){
        try {
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",batchList.get(batchIdx).getId());
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_GET_BATCH_DETAILS).upJson(jsonObject)
                    .execute(new MyDialogCallback(this, true, true) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            super.onSuccess(response);
                            try {
                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                batchDetails = new JSONObject();
                                if(bean.code == 1){
                                    if (StringUtils.isNotEmpty(bean.data)) {
                                        batchDetails = new JSONObject(bean.data);
                                    }
                                }else{
                                    showWarningToast(bean.msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                showEmptyView("批次详情解析错误:"+e.getMessage());
                                XLog.e("获取批次详情解析错误",e.getMessage());
                            }
                        }
                    });
        }catch (Exception e){
            batchList.size();
            XLog.e("请求批次详情错误:"+e.getMessage(),e);
        }
    }
    public void onRadioButtonClicked(View view) {
        RadioButton button = (RadioButton) view;
        boolean isChecked = button.isChecked();

        switch (view.getId()) {
            case R.id.rb_open_sound:
                isSound = true;
                break;
            case R.id.rb_turn_off_sound:
                isSound = false;
                break;
            default:
                break;
        }


    }

    protected void pushData(final int batch_inx,final int inx) {

        // 启动一个线程来做一些我们不应该在UI线程中直接做的工作
        Thread t = new Thread() {
            public void run() {
                try {

                    ToolDetailBean toolDetailBean = cacheList.get(batch_inx).get(inx);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("batch_inx",batch_inx);
                    jsonObject.put("inx",inx);
                    jsonObject.put("realm_id",toolDetailBean.getRealmId());
                    jsonObject.put("id",toolDetailBean.getId());
                    jsonObject.put("rules",toolDetailBean.getRules());
                    jsonObject.put("tool_data_id",toolDetailBean.getToolDataId());
                    jsonObject.put("number",toolDetailBean.getNumber());
                    jsonObject.put("scan_date",toolDetailBean.getScanDate());


                    OkGo.<String>post(Urls.getServiceAddress(getApplicationContext()) + Urls.FXY_ADD_SCAN_RESULT).upJson(jsonObject)
                            .execute(new MyDialogCallback(getApplicationContext(), true, false) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    super.onSuccess(response);
                                    try {
                                        ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                        JSONObject data = new JSONObject(bean.data);
                                        int position = data.getInt("inx");
                                        int batch_inx = data.getInt("batch_inx");

                                        int push_status = bean.code == 1 ? 1 : 2;


                                        List<ToolDetailBean> list = cacheList.get(batch_inx);
                                        ToolDetailBean tmpBean = list.get(position);;
                                        tmpBean.setPushStatus(push_status);

                                        cacheList.put(batch_inx,list);
                                        updateResult(batch_inx,position);


                                        // 保存一下数据
                                        mRealm.beginTransaction();
                                        RealmQuery query = mRealm.where(ToolScanRealm.class);
                                        RealmResults realList = query.equalTo("id",tmpBean.getRealmId()).findAll();
                                        if(realList.size() > 0){
                                            ToolScanRealm tmpRealm = (ToolScanRealm) realList.get(0);
                                            tmpRealm.setPushStatus(push_status);
                                        }
                                        mRealm.commitTransaction();



                                        if (bean.msg.equals("重复扫描")){
                                            showRepeatToast("重复扫描");
                                        }


                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        showEmptyView("上传失败:"+e.getMessage());


                                        XLog.e("获取批次详情解析错误",e.getMessage());
                                    }
                                }
                            });
                }catch (Exception e){

                    XLog.e("请求上传错误:"+e.getMessage(),e);
                }
            }
        };
        t.start();
    }


    @SuppressLint("HandlerLeak")
    Handler resultHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ToolDetailBean tmpBean ;

            switch (msg.what){
                //添加日志
                case 1:
                    List<ToolDetailBean> list = cacheList.get(batchIdx);
                    if (list==null){
                        list = new ArrayList<>();
                    }
                    int inx = list.size();


                    tmpBean = JsonUtil.getObject(msg.obj.toString(), ToolDetailBean.class); ;
                    list.add(tmpBean);
                    cacheList.put(batchIdx,list);
                    pushData(batchIdx,inx);

                    //倒序显示
                    scanShowList.clear();
                    scanShowList.addAll(cacheList.get(batchIdx));
                    Collections.reverse(scanShowList);
                    mAdapter.setNewData(scanShowList);
                    mAdapter.notifyDataSetChanged();

                    System.out.println("总条数:"+inx);
                    break;
                // 修改日志
                case 2:

                    int batch_inx = msg.arg1;

                    //倒序显示
                    List<ToolDetailBean> newList = cacheList.get(batch_inx);
                    //倒序显示
                    scanShowList.clear();
                    scanShowList.addAll(newList);
                    Collections.reverse(scanShowList);
                    mAdapter.setNewData(scanShowList);
                    mAdapter.notifyDataSetChanged();


                    break;
            }

        }
    };

    private void addResult(String str){
        Message msg = new Message();
        msg.what = 1;
        msg.obj = str;
        resultHandler.sendMessage(msg);
    }

    private void updateResult(int batch_inx,int inx){
        Message msg = new Message();
        msg.what = 2;
        msg.arg1 = batch_inx;
        msg.arg2 = inx;
        msg.obj = "";
        resultHandler.sendMessage(msg);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //XLog.e("Action："+event.getAction()+"---event:"+event.getKeyCode());
        if ((event.getKeyCode()==KeyEvent.KEYCODE_DPAD_CENTER )  && event.getAction() == KeyEvent.ACTION_DOWN){
            if(validate()){
                doVerify();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    //监听按键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //XLog.e("监听按键："+keyCode);XLog.e(event);
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            int num = cheatPush();
            if (num>0){
                showErrorToast("还有"+num+"条数据未上传成功");
                return false;
            }
        }
        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);
    }


    @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);
                }
            }

        }

    };
    @Override
    public void onScanResults(String str) {
        Message msg = new Message();
        msg.obj = str;
        scanHandler.sendMessage(msg);


    }


    @Override
    public void onScanResults(String str, int type) {

    }
    /**
     * 定义广播接受
     */
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String scanResult = intent.getStringExtra(scanBean.getDataName());
            if (scanResult==null){return; }
            String scanStatus = "";
            if (!scanBean.getStatusName().isEmpty()){
                scanStatus = intent.getStringExtra(scanBean.getStatusName());
            }else{
                scanStatus = scanResult.isEmpty()? "" : "ok"; //有值 默认是扫码成功;
            }


            String ruleStr = "[{\"number_start\":\"%\",\"number_length\":34,\"cut_type\":1,\"start_index\":23,\"cut_length\":12}," +
                    "{\"number_start\":\"420\",\"number_length\":30,\"cut_type\":1,\"start_index\":9,\"cut_length\":22}]";

            scanResult = StrInterception(scanResult,ruleStr);

            //新大陆(MT65,MT90) 需要手动关闭
            if (!scanBean.getActionStop().isEmpty()){
                Intent stopIntent = new Intent(scanBean.getActionStop());
                mContext.sendBroadcast(stopIntent);
            }


            if ("ok".equals(scanStatus)){
                setScanResult(scanResult);
            }else{
                showErrorToast(getString(R.string.scan_failed));
            }
        }
    };



    /**
     * 注册广播
     */
    private void initReceiver(){

        try {

            String scanStr = getScanSetting();
            scanBean = JsonUtil.getObject(scanStr, ScanBean.class);
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播

            if (is_broadcast ==1){
                IntentFilter mFilter = new IntentFilter(scanBean.getAction());
                this.registerReceiver(mReceiver, mFilter);
            }else{
                //不广播进行处理 jni模式
                String pdaBrand = StoTongJNI.getmPdaBrand();
                if (!pdaBrand.isEmpty()){
                    StoTongJNI.getIns(this).setmScanCB(this);
                    StoTongJNI.getIns(this).SetScannerOn();
                }
            }


        }catch (Exception e) {
            showErrorToast("获取扫码配置失败"+e.getMessage());
            XLog.e("获取扫码配置失败:" + e.getMessage());
        }
    }


    //统一按钮回调
    public void callbackEditor(View v){
        switch (v.getId()) {
            case R.id.et_order_no:
                doVerify();
                break;
            default:
        }
    }





    private void initEdit() {
        List<EditText> list = new ArrayList<>();
        list.add(etOrderNo);
        unifyEdit(list);
    }
    private OnRxScanerListener mScanerListener = new OnRxScanerListener() {
        @Override
        public void onSuccess(String type, Result result) {
            String scanResult = result.getText();
            switch (type){
                case BaseConfig.COMMON_SCANNER_ONLY:
                    setScanResult(scanResult);

                    break;
            }
        }
        @Override
        public void onFail(String type, String message) {

        }
    };

    //把扫描结果赋值
    private void setScanResult(String scanResult){

        //获取焦点的view对象
        View view=getWindow().getDecorView().findFocus();
        //如果是EditText
        if(view instanceof EditText)
        {
            ((EditText) view).setText(scanResult);
            //执行回调
            callbackEditor(view);
        }
    }



    public void doVerify() {

        //校验数据
        if (!validate()){
            return;
        }

        try {
            String number = etOrderNo.getText().toString().trim();
            JSONObject param = new JSONObject();


            String realmId = UUID.randomUUID().toString();


            int tool_data_id = 0;
            int id = 0;
            int rules = batchList.get(batchIdx).getRules();//默认不校验
            String scan_date = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
            if (batchDetails.has(number)){

                JSONObject tmpObject = batchDetails.getJSONObject(number.toUpperCase());
                if (tmpObject.has("scan_date") && !tmpObject.getString("scan_date").equals("")){
                    showRepeatToast("订单已扫描");
                    return ;
                };
                id = tmpObject.getInt("id");
            }

            tool_data_id = batchList.get(batchIdx).getId();

            param.put("realm_id",realmId);
            param.put("number",number);
            param.put("is_verify",isVerify);
            param.put("tool_data_id",tool_data_id);
            param.put("id",id);
            param.put("rules",rules);
            param.put("scan_date",scan_date);
            addResult(param.toString());

//            if (cacheList.get(batchIdx)!=null && cacheList.get(batchIdx).size()<50000){
//                for (int u=0;u<5000;u++){
//                    param.put("number",number+u);
//                    addResult(param.toString());
//                }
//            }



            //同步操作写法一：
            mRealm.beginTransaction();
            //会创建对象和user表
            ToolScanRealm toolScan = mRealm.createObject(ToolScanRealm.class,realmId);
            //会自动更新表
            toolScan.setScanBatch(scanBatch);
            toolScan.setNumber(number);
            toolScan.setToolDataId(tool_data_id);
            toolScan.setDetailsId(id);
            toolScan.setRules(rules);
            toolScan.setScanDate(scan_date);
            //提交事务，操作就被执行
            mRealm.commitTransaction();




            if (!isVerify){
                showSuccessToast("扫描成功");
                clearData();
            }else{
                if (id>0){
                    showSuccessToast("订单匹配成功");
                    clearData();
                }else{
                    showErrorToast("订单不存在");
                    clearData();
                }
            }

        } catch (JSONException e) {
            showEmptyView("请求入库失败:"+e.getMessage());
            e.printStackTrace();
        }
    }




    /*
     * 校验必录
     */
    private boolean validate(){
        if (batchDetails==null){
            showWarningToast("该批次无数据");
            return false;
        }

        if(!checkNull(etOrderNo)){
            setEditTextFocused(etOrderNo,true);
            showWarningToast(etOrderNo.getHint().toString());
            return false;
        }
        ToolBean toolBean = batchList.get(batchIdx);
        if (toolBean.getRules()==1 && cacheList.get(batchIdx) != null){
            String number = etOrderNo.getText().toString().trim();
            for (int i = 0; i <cacheList.get(batchIdx).size(); i++){
                if (cacheList.get(batchIdx).get(i).getNumber().toUpperCase().equals(number)){
                    showRepeatToast("订单已扫描");
                    return false;
                }
            }
        }



        return true;
    }

    private class FinishWorkAdapter extends BaseQuickAdapter<ToolDetailBean, BaseViewHolder>{
        public FinishWorkAdapter(List<ToolDetailBean> data){
            super(R.layout.item_card_intercept, data);
        }


        public void setNewData(List<ToolDetailBean> tmpList) {
        }

        @Override
        protected void convert(BaseViewHolder helper, ToolDetailBean item) {
            helper.addOnClickListener(R.id.ib_clear);//定义setOnItemChildClickListener 事件点击
            String status_str = "";
            switch (item.getPushStatus()){
                case 1:
                    status_str = "已上传";
                    break;
                case 2:
                    status_str = "上传失败";
                    break;
                default:
                    status_str = "未上传";
                    break;
            }
            helper.setText(R.id.tv_order_no,item.getNumber());
            helper.setText(R.id.tv_location,item.getScanDate());
            helper.setText(R.id.tv_status,status_str);
        }
    }
    private void initAdapter(){
        emptyView = this.getLayoutInflater().inflate(R.layout.pager_empty, (ViewGroup) recyclerView.getParent(), false);
        errorView = this.getLayoutInflater().inflate(R.layout.pager_error, (ViewGroup) recyclerView.getParent(), false);
        notDataView = emptyView;
        mAdapter  = new FinishWorkAdapter(scanShowList);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);




    }

    //清除订单信息
    private void clearData() {
        etOrderNo.setText("");
        etOrderNo.requestFocus();
        setEditTextNormal(etOrderNo,true);
    }

    @OnClick({R.id.btn_batch_upload})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            //批量上传
            case R.id.btn_batch_upload:

                int num = cheatPush();
                if (num>0){
                    showSuccessToast("已上传"+num+"条数据");
                }else{
                    showSuccessToast("数据已全部上传");
                }

                break;
            default:
                break;
        }
    }

    private int cheatPush(){

        int num = 0;

        for (int key : cacheList.keySet()) {

            if (cacheList.get(key)!=null){
                for (int j=0;j<cacheList.get(key).size();j++){
                    for (int i=0;i<cacheList.get(key).size();i++){
                        int push_status = cacheList.get(key).get(i).getPushStatus();
                        if (push_status!=1){
                            pushData(j,i);
                            num++;
                        }
                    }
                }
            }

        }



        return  num;
    }
    /**
     * 统一设置Edit监听
     * @param  list
     */
    public void unifyEdit(List<EditText> list){
        for (int i=0;i<list.size();i++){
            EditText editText = list.get(i);

            LinearLayout linearLayout = (LinearLayout)editText.getParent();
            ImageButton imageButton = getChildImageButton(linearLayout);


            //监听按确定
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    //XLog.e("actionId："+actionId);
                    if (actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE   ) {
                        if (v.getText().toString().trim().isEmpty()) {
                            setEditTextFocused(v,true);
                            showWarningToast(v.getHint().toString());
                            return false;
                        }else{
                            setEditTextNormal(v,true);
                        }

                        callbackEditor(v);

                        return false;
                    }
                    return false;
                }
            });
            editText.addTextChangedListener(new TextWatcher() {
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    EditText currentEditText = null;
                    ImageButton currentImage = null;
                    //获取焦点的view对象
                    View view=getWindow().getDecorView().findFocus();
                    //如果是EditText
                    if(view instanceof EditText){
                        currentEditText = (EditText) view;
                        currentImage = getChildImageButton((LinearLayout)currentEditText.getParent());
                    }

                    if (s.length() > 0  ) {

                        if (currentImage !=null ){
                            currentImage.setVisibility(View.VISIBLE);
                        }
                        if (currentEditText!=null){
                            setEditTextNormal(currentEditText,true);
                        }

                    } else {
                        if (currentImage !=null ){
                            currentImage.setVisibility(View.INVISIBLE);
                        }
                        if (currentEditText!=null){
                            setEditTextFocused(currentEditText,true);
                        }
                    }
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void afterTextChanged(Editable s) {

                }
            });

            if (imageButton !=null ){
                unifyClearEdit(imageButton);
            }
        }
    }


    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        initReceiver();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        try {


            //停止扫描
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播
            if (is_broadcast==0){
                StoTongJNI.getIns(mContext).SetScannerStop();
                StoTongJNI.getIns(mContext).SetScannerOff();
            }else{
                unregisterReceiver(mReceiver);
            }
        }catch (Exception e){
            XLog.e("销毁广播失败：",e.getMessage());
        }
    }


}
