package com.fxy.detection;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
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.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;

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.util.JsonUtil;
import com.fxy.baselibrary.views.MarqueeTextView;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.common.AsyncPictureSelector;
import com.fxy.common.CommonDialog;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.detection.bean.TakePictureBean;
import com.fxy.detection.bean.TrackingBoxBean;
import com.fxy.detection.bean.TrayMakeBean;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.UploadUtils;
import com.google.gson.Gson;
import com.google.zxing.Result;
import com.luck.picture.lib.config.PictureConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import sto.android.app.StoJNI;
import sto.android.app.StoPdaKeyEvent;
import sto.android.app.StoTongJNI;

public class BoxPutInMainActivity extends  BaseActivity implements StoJNI.ScanCallBack{

    /**
     * 列表适配器
     */
    Context mContext = this;

    @BindView(R.id.et_order_number)
    EditText etOrderNumber;

    @BindView(R.id.et_tracking_number)
    EditText etTrackingNumber;


    @BindView(R.id.ll_await_num)
    LinearLayout llAwaitNum;


    @BindView(R.id.ll_extend_info)
    LinearLayout llExtendInfo;

    @BindView(R.id.tv_await_num)
    TextView tvAwaitNum;

    @BindView(R.id.mt_customer_code)
    MarqueeTextView mtCustomerCode;

    @BindView(R.id.ll_label_picture)
    LinearLayout llLabelPicture;

    @BindView(R.id.ll_order_number)
    LinearLayout llOrderNumber;

    private HashMap<String, Object> postData  = new HashMap<>();

    private TrackingBoxBean trackingBoxBean;

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


    private boolean showWeightImg = false;

    private boolean isRequiredShow = false;

    private  ArrayList<String> baseImgList = new ArrayList<>();
    protected String action;


    private HashMap<String, AsyncPictureSelector> mapPictureSelector = new HashMap<>();



    private String currentPictureType= "label_img";

    private Unbinder unbinder;



    private CommonDialog commonDialog;

    //是否需要显示客户
    private boolean needCustomer;

    //客户名称
    private String customerCode="";


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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {
        //XLog.e("接收数据解析：",bundle);
    }



    //finish的返回监听
    //这里的requestCode参数，就是上面设置的 1 ，当跳转的页面返回的时候，通过这个加以判断
    //resultCode ,这个参数是在跳转的页面里面规定的，它也是一个int类型的标志
    //第三个参数包含了返回的值
    //如果不需要所跳转的页面返回值，也就不需要这个方法了
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 图片选择结果回调
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (mapPictureSelector.containsKey(currentPictureType)){
                    mapPictureSelector.get(currentPictureType).getSelectImg(data);
                }
                totalAwaitNum();

                if (mapPictureSelector.get("label_img").getOssPhotoList().size()>0){
                    //页面跳转
                    submitLabelImg();
                }

            }
        }
        if (requestCode == 200 && resultCode == 200)//之前提到的两个标志，在这里显示出了作用
        {
            initFinish();
        }


    }

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

        assert event != null;
        switch (event.getEventCode()){

            case EventCode.file_upload_lister:
                totalAwaitNum();
                break;
        }


    }

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


    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("单箱入库");

        initEdit();
        iniData();
        RecyclerView rvLabelShowImg = (RecyclerView)llLabelPicture.findViewById(R.id.rv_show_img);
        mapPictureSelector.put("label_img",setItemPicture("label_img",rvLabelShowImg,1));

        initDialog();
        totalAwaitNum();

    }


    /**
     * 设置多个上传文件
     * @param uploadType String
     * @param showImg RecyclerView
     */
    private AsyncPictureSelector setItemPicture(String uploadType,RecyclerView showImg,int num){

        String notifyUrl = Urls.getServiceAddress(this) + Urls.FXY_DETECTION_PUTIN;
        AsyncPictureSelector pictureUpload = new AsyncPictureSelector(BoxPutInMainActivity.this,showImg,"detection",uploadType,notifyUrl,false);
        pictureUpload.setUploadType(uploadType);
        pictureUpload.setCompress(true,100,100);
        pictureUpload.setOnlyCamera(true);
        pictureUpload.setMaxSelectNum(num);

        return  pictureUpload;
    }



    private void initDialog(){
        commonDialog = new CommonDialog(mContext, R.style.dialog, "need_customer", new CommonDialog.OnCloseListener() {
            @Override
            public void onClickCancel(Dialog dialog, boolean confirm) {
                customerCode = "" ;
                dialog.dismiss();
            }
            @Override
            public void onClickSubmit(Dialog dialog, boolean confirm) {
                String string = commonDialog.contentTxt.getText().toString().trim();
                if (commonDialog.getTypeCode().equals("need_customer")){
                    customerCode = string;
                }
                mtCustomerCode.setText(customerCode);
                getCustomer();


//                if (etOrderNumber.getText().toString().isEmpty()){
//                    etOrderNumber.requestFocus();
//                }else{
//                    getBoxNumber();
//                }

            }
        });
        commonDialog.setContentLabel("QC");


    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //XLog.e("event:"+event.getKeyCode());
        if ((event.getKeyCode()==KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode()==KeyEvent.KEYCODE_ENTER )  && event.getAction() == KeyEvent.ACTION_DOWN){
            //按确定键

        }
        return super.dispatchKeyEvent(event);
    }



    //监听按键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        XLog.e("监听按键："+keyCode);XLog.e(event);
        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"; //有值 默认是扫码成功;
            }

            //新大陆(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());
        }
    }

    private void initEdit() {
        List<EditText> list = new ArrayList<>();
        list.add(etTrackingNumber);
        list.add(etOrderNumber);
        unifyEdit(list);
    }


    private void iniData(){
        baseImgList.add("label_img");
        baseImgList.add("weight_img");
    }

    //getAwaitNum
    private void totalAwaitNum(){
        String[] uploadTypeList = {getClass().getSimpleName(),"BoxPutInDetailsMainActivity"};
        int awaitNum = UploadUtils.getAwaitNum(mRealm,uploadTypeList);
        tvAwaitNum.setText(String.valueOf(awaitNum));
    }

    //统一按钮回调
    @SuppressLint("NonConstantResourceId")
    public void callbackEditor(View v){

        switch (v.getId()) {
            case R.id.et_tracking_number:
                getTrackingNumber();
                break;
            case R.id.et_order_number:
                if (etTrackingNumber.getText().toString().isEmpty()){
                    etTrackingNumber.requestFocus();
                    return;
                }
                if (etOrderNumber.getText().toString().isEmpty()){
                    etOrderNumber.requestFocus();
                    return;
                }
                getBoxNumber();

                break;
            default:
        }

    }

    /**
     * 统一设置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 && isRequiredShow){
                            setEditTextFocused(currentEditText,true);
                        }
                    }
                }

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

                public void afterTextChanged(Editable s) {

                }
            });

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


    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);
            showSuccessToast("扫描成功");
            callbackEditor(view);
        }
    }


    //检查是否存在上传
    private void checkIsUpload(){

    }

    //获取跟踪单号
    private void getTrackingNumber(){

        checkIsUpload();
        if (etTrackingNumber.getText().toString().isEmpty()){
            showErrorToast(etTrackingNumber.getHint().toString());
            return;
        }

        Map<String,Object> math = new HashMap<>();
        math.put("tracking_number",etTrackingNumber.getText().toString().trim());

        String mathJson = (new Gson()).toJson(math);
        trackingBoxBean = null;
        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_PUTIN_TRACK).upJson(mathJson)
                .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.data!=null && !bean.data.isEmpty() && !bean.data.equals("[]")){
                                trackingBoxBean =  JsonUtil.jsonString2Bean(bean.data,TrackingBoxBean.class);
                            }

                            if (!trackingBoxBean.getTrackingNumber().isEmpty()){
                                etTrackingNumber.setText(trackingBoxBean.getTrackingNumber());
                            }

                            String voiceName = trackingBoxBean.getVoiceName();
                            final Bundle bundle = new Bundle();
                            bundle.putString("data",bean.data);
                            bundle.putString("customer_code",customerCode);

                            if (trackingBoxBean.getNeedConfirm().equals("Y")){
                                new AlertDialog.Builder(mContext).setTitle(R.string.dl_hint)
                                        .setMessage(trackingBoxBean.getConfirmMsg())
                                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                dialogInterface.dismiss();
                                            }
                                        }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

//                                        etOrderNumber.setEnabled(true);
//                                        etOrderNumber.requestFocus();
                                        intent2Page(BoxPutInMainActivity.this, BoxPutInDetailsMainActivity.class, false,bundle);
                                    }
                                }).show();
                                return;
                            }

                            needCustomer = trackingBoxBean.getNeedCustomer().equals("Y");
                            if (needCustomer && !commonDialog.isShowing()){
                                commonDialog.setTitle("客户编号","请输入客户编号").setContent(customerCode).show();
                            }else{
                                commonDialog.dismiss();
                            }
                            llExtendInfo.setVisibility(needCustomer ? View.VISIBLE:View.GONE);

                            llOrderNumber.setVisibility(trackingBoxBean.getBusinessType().equals("1")?View.GONE:View.VISIBLE);

                            if(bean.code == 1){
                                showSuccessToast(bean.msg,voiceName);
                                if (!needCustomer && trackingBoxBean.getBusinessType().equals("1")){
                                    mapPictureSelector.get(currentPictureType).authCamera();
                                }else{
                                    etOrderNumber.setEnabled(true);
                                    etOrderNumber.requestFocus();
                                }

                            }else{
                                showWarningToast(bean.msg,voiceName);
                            }


                        }catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("确认错误",e.getMessage());
                        }

                    }
                });
    }


    //获取跟踪单号
    private void getCustomer(){

        checkIsUpload();
        if (etTrackingNumber.getText().toString().isEmpty()){
            showErrorToast(etTrackingNumber.getHint().toString());
            return;
        }

        Map<String,Object> math = new HashMap<>();
        math.put("tracking_number",etTrackingNumber.getText().toString().trim());
        math.put("customer_code",customerCode);
        math.put("is_customer_code",1);

        String mathJson = (new Gson()).toJson(math);
        customerTrackingBoxBean = null;
        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_PUTIN_TRACK).upJson(mathJson)
                .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);
                            customerTrackingBoxBean = new TrackingBoxBean();
                            if (bean.data!=null && !bean.data.isEmpty() && !bean.data.equals("[]")){
                                customerTrackingBoxBean =  JsonUtil.jsonString2Bean(bean.data,TrackingBoxBean.class);
                            }



                            String voiceName = customerTrackingBoxBean.getVoiceName();
                            final Bundle bundle = new Bundle();
                            bundle.putString("data",(new Gson()).toJson(trackingBoxBean));
                            bundle.putString("customer_code",customerCode);

                            if (customerTrackingBoxBean.getNeedConfirm().equals("Y")){
                                new AlertDialog.Builder(mContext).setTitle(R.string.dl_hint)
                                        .setMessage(customerTrackingBoxBean.getConfirmMsg())
                                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                dialogInterface.dismiss();
                                            }
                                        }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

//                                        etOrderNumber.setEnabled(true);
//                                        etOrderNumber.requestFocus();
                                        intent2Page(BoxPutInMainActivity.this, BoxPutInDetailsMainActivity.class, false,bundle);
                                    }
                                }).show();
                                return;
                            }

                            llOrderNumber.setVisibility(customerTrackingBoxBean.getBusinessType().equals("1")?View.GONE:View.VISIBLE);


                            if(bean.code == 1){
                                commonDialog.dismiss();
                                showSuccessToast(bean.msg,voiceName);
                                if (customerTrackingBoxBean.getBusinessType().equals("1")){
                                    mapPictureSelector.get(currentPictureType).authCamera();
                                }else{
                                    etOrderNumber.setEnabled(true);
                                    etOrderNumber.requestFocus();
                                }

                            }else{
                                showWarningToast(bean.msg,voiceName);
                                commonDialog.authSoftKeyboard();
                            }


                        }catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("确认错误",e.getMessage());
                        }

                    }
                });
    }


    //获取跟踪单号
    private void getBoxNumber(){

        checkIsUpload();
        if (etTrackingNumber.getText().toString().isEmpty()){
            showErrorToast(etTrackingNumber.getHint().toString());
            return;
        }

        if (etOrderNumber.getText().toString().isEmpty()){
            showErrorToast(etOrderNumber.getHint().toString());
            return;
        }

        Map<String,Object> math = new HashMap<>();
        math.put("tracking_number",etTrackingNumber.getText().toString().trim());
        math.put("box_number",etOrderNumber.getText().toString().trim());
        if (needCustomer){

            if (customerCode.isEmpty()){
                showErrorToast("请输入客户代码");
                return;
            }
            math.put("is_customer_code","1");
            math.put("customer_code",customerCode);
        }

        String mathJson = (new Gson()).toJson(math);
        trackingBoxBean = null;
        customerTrackingBoxBean = null;
        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_PUTIN_TRACK).upJson(mathJson)
                .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.data!=null && !bean.data.isEmpty() && !bean.data.equals("[]")){
                                trackingBoxBean =  JsonUtil.jsonString2Bean(bean.data,TrackingBoxBean.class);
                            }

                            String voiceName = trackingBoxBean.getVoiceName();


                            if (trackingBoxBean.getNeedConfirm().equals("Y")){
                                new AlertDialog.Builder(mContext).setTitle(R.string.dl_hint)
                                        .setMessage(trackingBoxBean.getConfirmMsg())
                                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                dialogInterface.dismiss();
                                            }
                                        }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                        if (mapPictureSelector.get(currentPictureType).getOssPhotoList().size()>0){
                                            submitLabelImg();
                                        }else{
                                            mapPictureSelector.get(currentPictureType).authCamera();
                                        }

                                    }
                                }).show();
                            }else{

                                if(bean.code == 1){
                                    showSuccessToast(bean.msg,voiceName);

                                    if (mapPictureSelector.get(currentPictureType).getOssPhotoList().size()>0){
                                        submitLabelImg();
                                    }else{
                                        mapPictureSelector.get(currentPictureType).authCamera();
                                    }
                                }else{
                                    showWarningToast(bean.msg,voiceName);
                                }
                            }

                        }catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("确认错误",e.getMessage());
                        }

                    }
                });
    }


    //提交面单信息
    private void submitLabelImg(){
        checkIsUpload();
        if (etTrackingNumber.getText().toString().isEmpty()){
            showErrorToast(etTrackingNumber.getHint().toString());
            return;
        }
        if (customerTrackingBoxBean != null){
            if (!customerTrackingBoxBean.getBusinessType().equals("1") && etOrderNumber.getText().toString().isEmpty()){
                //showErrorToast(etOrderNumber.getHint().toString());
               // return;
            }
        }else{
            if (etOrderNumber.getText().toString().isEmpty()){
                //showErrorToast(etOrderNumber.getHint().toString());
                //return;
            }
        }



        Gson gson = new Gson();
        Map<String,Object> math = new HashMap<>();
        math.put("tracking_number",trackingBoxBean.getTrackingNumber().trim());


        math.put("box_number",etOrderNumber.getText().toString().trim());



        if (needCustomer){

            if (customerCode.isEmpty()){
                showErrorToast("请输入客户代码");
                return;
            }
            math.put("is_customer_code","1");
            math.put("customer_code",customerCode);
        }

        //面单
        List<String> stringList = mapPictureSelector.get("label_img").getOssPhotoList();
        if (stringList.size()==0){
            showWarningToast("面单照片不能为空");
            return;
        }
        math.put("label_img_tag",mapPictureSelector.get("label_img").getUniqueTag());
        math.put("label_img",gson.toJson(stringList));




        OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_DETECTION_PUTIN).upJson(gson.toJson(math))
                .execute(new MyDialogCallback(this, true, false) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        super.onSuccess(response);
                        try {

                            ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                            if (bean.data!=null && !bean.data.isEmpty() && !bean.data.equals("[]")){
                                trackingBoxBean =  JsonUtil.jsonString2Bean(bean.data,TrackingBoxBean.class);
                            }

                            String voiceName = trackingBoxBean.getVoiceName();
                            if(bean.code == 1){
                                showSuccessToast(bean.msg,voiceName);
                                Bundle bundle = new Bundle();
                                bundle.putString("data",bean.data);
                                bundle.putString("customer_code",customerCode);
                                intentPageResult(BoxPutInMainActivity.this, BoxPutInDetailsMainActivity.class, bundle,200);

                            }else{
                                showWarningToast(bean.msg,voiceName);
                            }

                        }catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("错误",e.getMessage());
                        }
                    }
                });

    }



    private void initFinish(){
        llExtendInfo.setVisibility(View.GONE);
        mtCustomerCode.setText("");
        customerCode = "";
        needCustomer = false;

        etOrderNumber.setText("");
        etOrderNumber.setEnabled(true);
        etTrackingNumber.setText("");
        etTrackingNumber.setEnabled(true);

        etTrackingNumber.requestFocus();

        for (int i=0;i<baseImgList.size();i++){
            if (mapPictureSelector.containsKey(baseImgList.get(i))){
                mapPictureSelector.get(baseImgList.get(i)).emptyRemake();
            }
        }


    }



    //sIsGoodinfoMatch,sIsBattery,sIsMagnetic,sIsWood,sIsExtra,sIsOther
    @OnClick({R.id.tv_edit_customer})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_edit_customer:
                if (needCustomer){
                    commonDialog.setTitle("客户编号","请输入客户编号").setContent(customerCode).show();
                }
                break;

            default:
                break;
        }
    }







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

}
