package com.fxy.fms.putIn;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.elvishew.xlog.XLog;
import com.google.gson.Gson;
import com.google.zxing.Result;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
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.JsonUtil;
import com.fxy.R;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.fms.logic.ViewLogic;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.view.FloatingImageView;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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 TallyVolumeMainActivity extends  BaseActivity implements StoJNI.ScanCallBack {
    /**
     * 列表适配器
     */
    Context mContext = this;
    //材积明细
    @BindView(R.id.ll_volume_content)
    LinearLayout llVolumeContent;

    @BindView(R.id.tv_add_pallet)
    TextView tvAddPallet;

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

    @BindView(R.id.ll_tally_info)
    LinearLayout llTallyInfo;

    private EditText edittext;

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

    //订单信息对象
    private JSONObject inboundObject;

    private JSONObject paramObject;

    private Unbinder unbinder;

    protected String action;

    //订单号
    private String orderNumber;

    //是否确认 Y 或 N 默认：N
    private String isConfirm = "N";

    //理货总件数
    private int total_pieces = 0;



    private ArrayList<Map<String, String>> volumeList = new ArrayList<Map<String, String>>();

    private JSONObject postParam = new JSONObject();

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

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

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

    @Override
    protected void getBundleExtras(Bundle bundle) {

        try {
            action = bundle.getString("action","receive");
            inboundObject = new JSONObject(bundle.getString("inbound_object"));
            paramObject = new JSONObject(bundle.getString("param"));
        } catch (JSONException e) {
            XLog.e("接收数据解析："+e.getMessage());
            e.printStackTrace();
        }



    }
    //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)//之前提到的两个标志，在这里显示出了作用
        {

            String  opt_status    = data.getStringExtra("opt_status").toString();
            if (opt_status.equals("success")){
                Intent intent = new Intent();
                intent.putExtra("opt_status", opt_status);
                setResult(200, intent);//返回值，200 是改返回的标志，也会返回
                finish();
            }


        }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("录入材积重");

        initEdit();


        //loadServiceData();
        initData();

        //监听浮动按钮
        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);
                }
            }
        });

        if (inboundObject!=null){
            //设置订单信息
            ViewLogic logic = new ViewLogic(llTallyInfo);
            logic.setTallyData(inboundObject);
            logic.setTallyMore(paramObject);
        }

        //默认添加一条
        addPallet();
    }


    private void initData(){


    }






    @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){
            //按确定键
            if(this.validate()){
                addReceive();
            }
        }
        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() {


    }


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

            switch (view.getId()) {
                case R.id.et_order_no:
                    break;
                default:
            }


        }
    }





    /*
     * 校验必录
     */
    private boolean validate(){
        int len = llVolumeContent.getChildCount();
        if (len==0){
            showWarningToast("请先添加材积信息");
            return false;
        }
        volumeList.clear();//清空材积信息

        total_pieces = 0;
        int num = 0;//第几个卡板
        for(int i=0;i<len ;i++) {
            View view_c = llVolumeContent.getChildAt(i);
            EditText etWeight = (EditText) view_c.findViewById(R.id.et_weight);
            EditText etPalletWeight = (EditText) view_c.findViewById(R.id.et_pallet_weight);
            if (etWeight==null){
                continue;
            }

            num++;
            //1、检查重量是否填写(一个卡板只有一个重量)
            if (!isNumber(getValStr(etWeight),3)){
                setEditTextFocused(etWeight,false);
                showWarningToast(getString(R.string.msg_gt_zero_3));
                return false;
            }
            etWeight.setBackgroundResource(R.drawable.edit_background);

            //1.1 检查卡板重量
            if (etPalletWeight.getText().toString().isEmpty()){
                setEditTextFocused(etPalletWeight,false);
                showWarningToast("必填项不能空");
                return false;
            }

            etPalletWeight.setBackgroundResource(R.drawable.edit_background);

            //总重量
            double weightTotal= Double.parseDouble(etWeight.getText().toString());
            //卡板重量
            double palletWeightTotal= Double.parseDouble(etPalletWeight.getText().toString());

            //1.2 检查卡板重量必需小于重量
            if (palletWeightTotal>=weightTotal){
                setEditTextFocused(etWeight,false);
                showWarningToast("卡板重量必需小于总重量");
                return false;
            }



            LinearLayout pallLayout = (LinearLayout) view_c.findViewById(R.id.ll_pall_center);




            //3、遍历卡板下的材积 ,由于removeAllViews 没有删除视图

            int volumeCopies = 0;
            int starIndex = volumeList.size();
            for(int j=2;j<pallLayout.getChildCount();j++) {
                View pallView = pallLayout.getChildAt(j);
                if (pallView.findViewById(R.id.et_copies)!=null){
                    EditText etCopies = (EditText) pallView.findViewById(R.id.et_copies);
                    EditText etLength = (EditText) pallView.findViewById(R.id.et_length);
                    EditText etWidth = (EditText) pallView.findViewById(R.id.et_width);
                    EditText etHeight = (EditText) pallView.findViewById(R.id.et_height);
                    if (!validateVolume(etCopies,etLength,etWidth,etHeight)){
                        return false;
                    }
                    String copies= etCopies.getText().toString().trim();
                    Map<String,String> hostMap = new HashMap<>();
                    hostMap.put("qty",copies);
                    hostMap.put("inbound_weight","0");
                    hostMap.put("inbound_length",etLength.getText().toString().trim());
                    hostMap.put("inbound_width",etWidth.getText().toString().trim());
                    hostMap.put("inbound_height",etHeight.getText().toString().trim());
                    hostMap.put("pallet_height",etPalletWeight.getText().toString().trim());
                    hostMap.put("total_width",etWeight.getText().toString().trim());
                    volumeList.add(hostMap);

                    volumeCopies = volumeCopies+Integer.parseInt(copies);
                }
            }

            if (volumeCopies==0){
                showWarningToast("卡板"+num+"材积不能为空");
                return false;
            }
            total_pieces = total_pieces+volumeCopies;


            //单件重量
            String inbound_weight = String .format("%.2f",(weightTotal-palletWeightTotal)/volumeCopies);;
            for (int n=starIndex ;n<volumeList.size();n++){
                Map<String,String> hostMap = volumeList.get(n);
                hostMap.put("inbound_weight",inbound_weight);
                volumeList.set(n,hostMap);
            }


        }
        return true;
    }

    private boolean validateVolume(EditText etCopies,EditText etLength,EditText etWidth,EditText etHeight){
        if (etCopies.getText().toString().isEmpty() ||   !isNumber(getValStr(etCopies),0)){
            setEditTextFocused(etCopies,false);
            showWarningToast(getString(R.string.error_please_int_num));
            return false;
        }
        //清除红色框框
        etCopies.setBackgroundResource(R.drawable.edit_background);


        if (!isNumber(getValStr(etLength),3)){
            setEditTextFocused(etLength,false);
            showWarningToast(getString(R.string.msg_gt_zero_3));
            return false;
        }
        //清除红色框框
        etLength.setBackgroundResource(R.drawable.edit_background);

        if (!isNumber(getValStr(etWidth),3)){
            setEditTextFocused(etWidth,false);
            showWarningToast(getString(R.string.msg_gt_zero_3));
            return false;
        }
        //清除红色框框
        etWidth.setBackgroundResource(R.drawable.edit_background);

        if (!isNumber(getValStr(etHeight),3)){
            setEditTextFocused(etHeight,false);
            showWarningToast(getString(R.string.msg_gt_zero_3));
            return false;
        }
        //清除红色框框
        etHeight.setBackgroundResource(R.drawable.edit_background);


        return true;
    }



    @OnClick({R.id.btn_confirm,R.id.tv_add_pallet})
    public void onViewClicked(final View view) {
        Bundle bundle = new Bundle();

        switch (view.getId()) {
            case R.id.btn_confirm:
                addReceive();
                break;
            case R.id.tv_add_pallet:
                addPallet();
                break;

            default:
                break;
        }
    }


    private void addPallet(){
        View newView = View.inflate(TallyVolumeMainActivity.this, R.layout.item_tally_pallet, null);



        //找到里面需要动态改变的控件
        TextView tvPalletTitle = (TextView) newView.findViewById(R.id.tv_pallet_num);
        //给控件赋值
        tvPalletTitle.setText("卡板"+(llVolumeContent.getChildCount()+1));

        TextView tvPalletDel = (TextView) newView.findViewById(R.id.tv_pallet_del);
        TextView tvVolumeDel = (TextView) newView.findViewById(R.id.tv_volume_del);
        TextView tvAddVolume = (TextView) newView.findViewById(R.id.tv_add_volume);

        if (llVolumeContent.getChildCount()==0){
            tvPalletDel.setVisibility(View.GONE);
        }
        tvVolumeDel.setVisibility(View.GONE);


        //监听删除按钮
        onClickVolumeDel(tvVolumeDel);
        onEditorAction((EditText) newView.findViewById(R.id.et_copies));
        onEditorAction((EditText) newView.findViewById(R.id.et_weight));
        onEditorAction((EditText) newView.findViewById(R.id.et_pallet_weight));
        onEditorAction((EditText) newView.findViewById(R.id.et_length));
        onEditorAction((EditText) newView.findViewById(R.id.et_width));
        onEditorAction((EditText) newView.findViewById(R.id.et_height));

        //监听删除卡托点击事件
        tvPalletDel.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                try {
                    final LinearLayout  linearLayout = (LinearLayout) v.getParent().getParent().getParent();
                    new AlertDialog.Builder(mContext)
                            .setTitle(R.string.dl_hint)
                            .setMessage("确定要删除卡板吗?")
                            .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) {
                            linearLayout.removeAllViews();
                            setPalletTitle();
                        }
                    }).show();




                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorToast("删除卡板失败");
                }

            }
        });


        //监听添加材积
        tvAddVolume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout pallLayout = (LinearLayout) v.getParent().getParent();
                addVolume(pallLayout);
            }
        });
        llVolumeContent.addView(newView); //添加一个View
        setPalletTitle();
    }
    //统计
    //添加材积
    private void addVolume(LinearLayout pallLayout){
        try {

            int childCount = pallLayout.getChildCount();
            //卡板的Layout
            View newView = View.inflate(TallyVolumeMainActivity.this, R.layout.item_tally_volume, null);
            TextView tvVolumeDel = (TextView) newView.findViewById(R.id.tv_volume_del);
            TextView tvTitleNum = (TextView) newView.findViewById(R.id.tv_title_num);

            onEditorAction((EditText) newView.findViewById(R.id.et_copies));
            onEditorAction((EditText) newView.findViewById(R.id.et_length));
            onEditorAction((EditText) newView.findViewById(R.id.et_width));
            onEditorAction((EditText) newView.findViewById(R.id.et_height));


            //监听删除按钮
            onClickVolumeDel(tvVolumeDel);

            //index 获取插入卡板的第几个子元素
            pallLayout.addView(newView,childCount-1);
            setVolumeTitle(pallLayout);
        } catch (Exception e) {
            e.printStackTrace();
            showErrorToast("添加失败");
        }
    }

    //监听删除事件
    private void onClickVolumeDel(View tvVolumeDel){
        //监听删除材积
        tvVolumeDel.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {

                try {

                   final LinearLayout linearLayout = (LinearLayout) v.getParent().getParent().getParent();

                    new AlertDialog.Builder(mContext)
                            .setTitle(R.string.dl_hint)
                            .setMessage("确定要删除材积信息吗?")
                            .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) {
                            LinearLayout pallLayout = (LinearLayout) linearLayout.getParent();
                            linearLayout.removeAllViews();
                            setVolumeTitle(pallLayout);
                        }
                    }).show();


                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorToast("删除材积信息失败");
                }

            }
        });
    }

    //设置卡板标题
    private void setPalletTitle(){
        int num = 1;
        for(int j=0;j<llVolumeContent.getChildCount();j++) {
            View view_c = llVolumeContent.getChildAt(j);
            TextView tvPalletTitle = (TextView) view_c.findViewById(R.id.tv_pallet_num);
            if (tvPalletTitle!=null){
                tvPalletTitle.setText("卡板"+(num));
                num++;
            }

        }
    }
    //设置材积标题
    private void setVolumeTitle(LinearLayout pallLayout){
        int num = 1;
        for(int j=0;j<pallLayout.getChildCount();j++) {
            View view_c = pallLayout.getChildAt(j);
            if (view_c.findViewById(R.id.ll_volume_container)!=null){
                TextView tvTitle = (TextView) view_c.findViewById(R.id.tv_title_num);
                tvTitle.setText("材积信息（"+num+"）");
                num++;
            }
        }
    }
    //监听所有输入框
    private void onEditorAction(EditText editText){
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    int len = llVolumeContent.getChildCount();
                    int num = 0;//第几个卡板
                    for(int i=0;i<len ;i++) {
                        View view_c = llVolumeContent.getChildAt(i);
                        EditText etWeight = (EditText) view_c.findViewById(R.id.et_weight);
                        EditText etPalletWeight = (EditText) view_c.findViewById(R.id.et_pallet_weight);
                        if (etWeight==null){
                            continue;
                        }
                        num++;
                        if (etWeight.getText().toString().isEmpty()){
                            etWeight.requestFocus();
                            return false;
                        }
                        if (etPalletWeight.getText().toString().isEmpty()){
                            etPalletWeight.requestFocus();
                            return false;
                        }

                        LinearLayout pallLayout = (LinearLayout) view_c.findViewById(R.id.ll_pall_center);
                        int a = pallLayout.getChildCount();
                        //2、查验卡板下是否有材积信息
                        if (pallLayout.getChildCount()<4){
                            showWarningToast("卡板"+(num)+"材积不能为空");
                            //return true;
                            continue; //不终止
                        }


                        //3、遍历卡板下的材积
                        for(int j=2;j<pallLayout.getChildCount();j++) {
                            View pallView = pallLayout.getChildAt(j);
                            if (pallView.findViewById(R.id.et_copies)!=null){
                                EditText etCopies = (EditText) pallView.findViewById(R.id.et_copies);
                                if (etCopies.getText().toString().isEmpty()){
                                    etCopies.requestFocus();
                                    return false;
                                }
                                EditText etLength = (EditText) pallView.findViewById(R.id.et_length);
                                if (etLength.getText().toString().isEmpty()){
                                    etLength.requestFocus();
                                    return false;
                                }
                                EditText etWidth = (EditText) pallView.findViewById(R.id.et_width);
                                if (etWidth.getText().toString().isEmpty()){
                                    etWidth.requestFocus();
                                    return false;
                                }
                                EditText etHeight = (EditText) pallView.findViewById(R.id.et_height);
                                if (etHeight.getText().toString().isEmpty()){
                                    etHeight.requestFocus();
                                    return false;
                                }
                            }
                        }

                    }

                    //软键盘
                    View view = getWindow().peekDecorView();
                    if (view != null) {
                        InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }

                }
                return false;
            }
        });
    }

    private void addReceive(){

        if (!validate()){
            return;
        }


        try {
            //理货数量
            int inbound_pieces  = inboundObject.getInt("inbound_pieces");
            //预报数量
            int forecast_pieces = inboundObject.getInt("forecast_pieces");
            if (forecast_pieces>inbound_pieces+total_pieces){
                new AlertDialog.Builder(TallyVolumeMainActivity.this)
                        .setTitle(R.string.dl_hint)
                        .setMessage("入库件数"+(inbound_pieces+total_pieces)+"与预报件数"+(forecast_pieces)+"不一致，确定是否入库")
                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                            @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) {
                        addReceiveDo();
                    }
                }).show();
            }else{
                addReceiveDo();
            }

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


        //数据检查不通过

    }

    private void addReceiveDo(){
        try {
            postParam = new JSONObject();
            Gson gson = new Gson();
            postParam.put("order_number",inboundObject.getString("order_number"));
            postParam.put("docker_id",paramObject.getInt("docker_id"));
            postParam.put("has_label",paramObject.getString("has_label"));
            postParam.put("is_confirm",isConfirm);
            postParam.put("receive_list",gson.toJson(volumeList));
            postParam.put("action",action);
            if (!checkRepeat(Urls.FMS_ADD_RECEIVE+(postParam.toString()))){return;}
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FMS_ADD_RECEIVE).upJson(postParam)
                    .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){
                                    showSuccessToast(getString(R.string.str_tally_success));
                                    Intent intent = new Intent();
                                    intent.putExtra("opt_status", "success");
                                    setResult(200, intent);//返回值，2 是改返回的标志，也会返回
                                    finish();
                                }else{
                                    JSONObject result = new JSONObject();
                                    if (bean.data!=null && !bean.data.isEmpty()){
                                        result = new JSONObject(bean.data);
                                    }
                                    if (result.has("is_warning") && result.getInt("is_warning")==1){
                                        new AlertDialog.Builder(TallyVolumeMainActivity.this)
                                                .setTitle(R.string.dl_hint)
                                                .setMessage(bean.msg)
                                                .setNegativeButton("录入准确，拍照", new DialogInterface.OnClickListener() {
                                                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString("inbound_object",inboundObject.toString());
                                                        bundle.putString("param",paramObject.toString());
                                                        bundle.putString("post_param",postParam.toString());
                                                        intentPageResult(TallyVolumeMainActivity.this,TallyPictureMainActivity.class, bundle,200);
                                                    }
                                                }).setPositiveButton("重新录入", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                //取消不做操作

                                            }
                                        }).show();
                                    }else {
                                        showWarningToast(bean.msg);
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("添加理货数据结果返回错误",e.getMessage());
                            }
                        }
                    });
        } catch (JSONException e) {
            XLog.e("sku数据解析出错",e);
            e.printStackTrace();
        }
    }

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


}
