package com.baoshi.swms.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.Html;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baoshi.swms.R;
import com.baoshi.swms.bean.Picking;
import com.baoshi.swms.bean.PickingItem;
import com.baoshi.swms.bean.PickingNumber;
import com.baoshi.swms.bean.User;
import com.baoshi.swms.bean.dto.PickingDto;
import com.baoshi.swms.net.callback.SwmsHandlerCallback;
import com.baoshi.swms.net.subscribe.SwmsSubscribe;
import com.baoshi.swms.sqlite.DBManager;
import com.baoshi.swms.sqlite.SQLiteDataProxy;
import com.baoshi.swms.sqlite.TaskTable;
import com.baoshi.swms.util.Barcode;
import com.baoshi.swms.util.DateUtil;
import com.baoshi.swms.util.GlobalStorage;
import com.google.gson.Gson;
import com.kongzue.dialogx.DialogX;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialogx.style.MaterialStyle;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class PickingActivity extends AppCompatActivity implements View.OnKeyListener, View.OnClickListener {
    private Picking picking;
    private PickingItem pickingItem;
    private PickingNumber pickingNumber;
    private final String prefix = "picking";
    private final String BTN_TEXT_BEFORE = "提前完成拣货";
    private final String BTN_TEXT = "完成当前拣货";
    private TextView taskCount;
    private TextView offStockCount;
    private TextView group;
    private TextView gather;
    private TextView taskId;
    private TextView taskRatio;
    private TextView startTime;
    private TextView whenTime;
    private TextView way;
    private TextView currentLoc;
    private TextView number;
    private EditText barcode;
    private EditText verifyNumber;
    private long currentMillers;
    private Button btn;
    private RadioGroup ratio;
    private TaskTable taskDb;
    private MediaPlayer mediaPlayer;
    private MediaPlayer mediaPlayerErr;
    private Vibrator vibrator;
    private boolean lockStatus;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picking);

        //初始化DialogX组件
        DialogX.init(this);

        //注册一些局部变量与赋值
        registerLocalVar();
        //注册事件
        registerEvent();
        //判断是否有本地任务未结束
        if (!checkLocalTask()){
            inquiryTaskStart();//询问是否获取新任务
        }else{
            loadLocalTask();//加载本地任务
        }
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        DBManager.close(this);
    }

    /**
     * 注册事件
     * */
    private void registerEvent() {
        barcode.setOnKeyListener(this);
        verifyNumber.setOnKeyListener(this);
        btn.setOnKeyListener(this);
        btn.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.lock).setOnClickListener(this);
        findViewById(R.id.give_up).setOnClickListener(this);
    }

    /**
     * 注册局部变量
     * */
    private void registerLocalVar() {
        taskCount = findViewById(R.id.task_count);
        offStockCount = findViewById(R.id.off_stock_count);
        group = findViewById(R.id.group);
        gather = findViewById(R.id.gather);
        taskId = findViewById(R.id.task_id);
        taskRatio = findViewById(R.id.task_ratio);
        startTime = findViewById(R.id.start_time);
        whenTime = findViewById(R.id.when_time);
        way = findViewById(R.id.way);
        currentLoc = findViewById(R.id.current_loc);
        number = findViewById(R.id.number);
        barcode = findViewById(R.id.barcode);
        verifyNumber = findViewById(R.id.verify_number);
        btn = findViewById(R.id.btn);

        lockStatus = true;
        barcode.setInputType(InputType.TYPE_NULL);

        if (mediaPlayer==null){
            mediaPlayer = MediaPlayer.create(this,R.raw.tip);
        }
        if (mediaPlayerErr==null){
            mediaPlayerErr = MediaPlayer.create(this,R.raw.error);
        }
        if (vibrator==null){
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        }
        pickingNumber = new PickingNumber();
    }
    /**
     * 用作错误时的 语音与震动
     * */
    private void setVibrator(){
        mediaPlayerErr.start();
        vibrator.vibrate(VibrationEffect.createOneShot(1000, -1));
    }

    /**
     * 检查是否有本地任务
     * */
    private boolean checkLocalTask() {
        taskDb = new TaskTable(this);
        Cursor cursor = DBManager.query(this, "select 1 from task LIMIT 2");
        int count = cursor.getCount();
        cursor.close();
        return count>0;
    }
    /**
     * 询问是否获取新任务
     * */
    private void inquiryTaskStart() {
        picking = null;
        pickingItem = null;
        MessageDialog.show("宝时好拣单", "是否获取单据任务", "获取","返回").setOkButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog baseDialog, View v) {
                getTask();
                return false;
            }
        }).setCancelButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog baseDialog, View v) {
                finish();
                return false;
            }
        }).setCustomView(new OnBindView<MessageDialog>(R.layout.dialog_picking_selected) {
            @Override
            public void onBind(MessageDialog dialog, View v) {
                ratio = v.findViewById(R.id.ratio);
            }
        }).setCancelable(false);
    }

    /**
     * 加载本地任务 设置pickingNumber的一些数值 用以initData
     * */
    private void loadLocalTask(){
        WaitDialog.show("加载任务信息中~");
        Cursor cursor = DBManager.query(this,"SELECT * FROM "+TaskTable.TABLE_NAME);
        if (cursor!=null){
            pickingNumber.setUnfinishedTaskCount(0);
            pickingNumber.setTotal(0);
            pickingNumber.setBeenQty(0);
            while(cursor.moveToNext()){
                int aqIndex = cursor.getColumnIndex("anticipatedQuantity");
                int rqIndex = cursor.getColumnIndex("realQuantity");
                int piIndex = cursor.getColumnIndex("pickingTime");

                if (cursor.getString(piIndex)==null){
                    pickingNumber.setUnfinishedTaskCount(pickingNumber.getUnfinishedTaskCount()+1);
                }
                pickingNumber.setTotal(pickingNumber.getTotal()+cursor.getInt(aqIndex));
                pickingNumber.setBeenQty(pickingNumber.getBeenQty()+cursor.getInt(rqIndex));
            }
            cursor.close();
        }
        Gson gson = new Gson();
        GlobalStorage storage = GlobalStorage.getGlobalStorage();
        picking = gson.fromJson(storage.get("PICKING_TASK"),Picking.class);
        SwmsSubscribe.getUserTodayWorkNum(new SwmsHandlerCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                pickingNumber.setUserBeenWorkCount(result);
                super.onSuccess(result);
            }
            @Override
            public void onFinally() {
                initData();
                WaitDialog.dismiss();
            }
        });
    }

    /**
     * 发起请求，获取任务信息
     * */
    private void getTask() {
        WaitDialog.show("任务获取中~");
        if (type==null){
            type = ((RadioButton)findViewById(ratio.getCheckedRadioButtonId())).getText().toString();
        }
        SwmsSubscribe.getPickingTask(type, new SwmsHandlerCallback<PickingDto>() {
            @Override
            public void onSuccess(PickingDto result) {
                super.onSuccess(result);
                handlerTask(result);
            }
            @Override
            public void onFinally() {
                WaitDialog.dismiss();
            }
        });
    }

    /**
     * 清除当前本地任务
     * */
    private void clearTask(){
        GlobalStorage storage = GlobalStorage.getGlobalStorage();
        storage.remove("PICKING_TASK");
        DBManager.execSQL(this,"DELETE FROM "+TaskTable.TABLE_NAME);
        inquiryTaskStart();
    }
    /**
     * 放弃任务
     * */
    private void giveUpTask(){
        if(picking==null || picking.getCode()==null){
            TipDialog.show("任务取消成功！",WaitDialog.TYPE.SUCCESS,2500);
            return;
        }
        WaitDialog.show("任务取消中...");
        SwmsSubscribe.giveUpTask(picking.getCode(), new SwmsHandlerCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                TipDialog.show("任务取消成功！",WaitDialog.TYPE.SUCCESS,2500);
                clearTask();
            }
            @Override
            public void onFinally() {
                WaitDialog.dismiss();
            }
        });
    }

    /**
     * 处理获取任务
     * */
    private void handlerTask(PickingDto pickingDto){
        picking = pickingDto.getTask();
        if (picking==null){
            MessageDialog.build().setTitle("暂无拣货任务").setMessage("是否尝试重新获取？").setOkButton("重新获取").setCancelButton("退出")
            .setOkButtonClickListener(new OnDialogButtonClickListener<MessageDialog>() {
                @Override
                public boolean onClick(MessageDialog baseDialog, View v) {
                    getTask();
                    return false;
                }
            }).setCancelButtonClickListener(new OnDialogButtonClickListener<MessageDialog>() {
                @Override
                public boolean onClick(MessageDialog baseDialog, View v) {
                    finish();
                    return false;
                }
            }).setStyle(MaterialStyle.style()).show();
            return;
        }
        pickingNumber.setUserBeenWorkCount(pickingDto.getTodayWorkNumber());
        if (pickingDto.getUnfinished()){ //存在未完成任务
            handlerUnfinished(pickingDto.getItems());//处理未完任务
        }else{
            loadTask(pickingDto.getItems());//处理新任务
        }
    }

    /**
     * 加载任务信息
     * */
    private void loadTask(ArrayList<PickingItem> items){
        //将当前picking序列化存储
        Gson gson = new Gson();
        GlobalStorage storage = GlobalStorage.getGlobalStorage();
        storage.put("PICKING_TASK",gson.toJson(picking));
        SQLiteDatabase db = SQLiteDataProxy.getSQLiteProxy(this).getSQLiteDataBase();
        db.beginTransaction();
        try{
            DBManager.execSQL(this,"DELETE FROM "+TaskTable.TABLE_NAME);
            AtomicInteger index = new AtomicInteger(1);
            pickingItem = null;
            AtomicInteger atTotal = new AtomicInteger(0);
            AtomicInteger atBeenQty = new AtomicInteger(0);
            AtomicInteger unfinishedTaskCount = new AtomicInteger(0);
            items.forEach(item->{
                atTotal.set(atTotal.get()+item.getAnticipatedQuantity());
                if (item.getRealQuantity()!=null){
                    atBeenQty.set(atBeenQty.get()+item.getRealQuantity());
                }
                ContentValues values = new ContentValues();
                values.put("id",index.get());
                values.put("detailId",item.getDetailId());
                values.put("location",item.getLocation());
                values.put("way",item.getWay());
                values.put("barcode",item.getBarcode());
                values.put("barcodeAs",item.getBarcodeAs());
                values.put("anticipatedQuantity",item.getAnticipatedQuantity());
                values.put("realQuantity",item.getRealQuantity());
                values.put("pickingTime",item.getPickingTime());
                db.insert(TaskTable.TABLE_NAME,null,values);
                index.getAndIncrement();
                if (item.getPickingTime()==null){
                    unfinishedTaskCount.getAndIncrement();
                }
            });
            pickingNumber.setUnfinishedTaskCount(unfinishedTaskCount.get());
            pickingNumber.setTotal(atTotal.get());
            pickingNumber.setBeenQty(atBeenQty.get());
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        initData();
    }

    /**
     * 询问是否放弃
     * */
    private void handlerUnfinished(ArrayList<PickingItem> items){
        MessageDialog.show("存在未完任务", "是否要放弃历史未完任务", "加载任务","放弃任务").setOkButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog baseDialog, View v) {
                loadTask(items);
                return false;
            }
        }).setCancelButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog baseDialog, View v) {
                giveUpTask();
                return false;
            }
        }).setCancelable(false);
    }


    /**
     * 视图数据的初始化渲染,需要等一切数据加载完毕后才可调用
     * */
    private void initData(){
        //设置一些label的颜色标签
        String[] labels = new String[]{
                "way","current_loc","number","barcode"
        };
        //通过反射设置label资源,默认规则：资源加stocking前缀  id加label后缀
        for (String val: labels) {
            ((TextView) findViewById(getResources().getIdentifier(val+"_label","id",this.getPackageName()))).setText(
                    Html.fromHtml(getString(getResources().getIdentifier(prefix+"_"+val,"string",this.getPackageName())),Html.FROM_HTML_MODE_COMPACT)
            );
        }

        //一些需要组合赋值的显示数据
        ((TextView)findViewById(R.id.user_name)).setText(
                Html.fromHtml(
                        getString(R.string.stocktaking_user_name, User.getLocalUser().getName()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        group.setText(
                Html.fromHtml(
                        getString(R.string.picking_group, picking.getGroup()==null ? "" : picking.getGroup()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        gather.setText(
                Html.fromHtml(
                        getString(R.string.picking_gather, picking.getVenue()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        taskId.setText(
                Html.fromHtml(
                        getString(R.string.picking_task_id, picking.getCode()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        startTime.setText(
                Html.fromHtml(
                        getString(R.string.picking_start_time, picking.getOperationTime()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        ((TextView)findViewById(R.id.owner_code)).setText(picking.getOwnerCode());
        //渲染条码
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        ((ImageView)findViewById(R.id.barcode_img)).setImageBitmap(Barcode.createBarcode(picking.getWaveCode(),outMetrics.widthPixels,60,false));
        //渲染计时器
        workTimer();
        //聚焦
        barcode.requestFocus();
        //渲染局部视图
        changeNumberUi();
        //渲染初始按钮与初始库位
        btn.setText(BTN_TEXT);
        pickingItem = new PickingItem();
        pickingItem.setId(0);
        completeLoad();
    }

    /**
     * 更新数值部分UI
     * */
    void changeNumberUi(){
        taskCount.setText(
                Html.fromHtml(
                        getString(R.string.picking_task_count, pickingNumber.getUnfinishedTaskCount()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        offStockCount.setText(
                Html.fromHtml(
                        getString(R.string.picking_off_stock_count, pickingNumber.getUserBeenWorkCount()),
                        Html.FROM_HTML_MODE_COMPACT)
        );
        taskRatio.setText(String.valueOf(pickingNumber.getBeenQty())+"/"+String.valueOf(pickingNumber.getTotal()));
    }

    /**
     * 计时器开始
     * */
    private void workTimer() {
        currentMillers = (new Date().getTime() - DateUtil.strToDate(picking.getOperationTime()).getTime())/1000;
        Observable.interval(0,1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                               @Override
                               public void onSubscribe(@NonNull Disposable disposable) {
                               }
                               @Override
                               public void onNext(@NonNull Long number) {
                                   whenTime.setText(
                                           Html.fromHtml(
                                                   getString(R.string.picking_when_time, (int)(Math.floor((double)currentMillers/60.0)),(int)((double)currentMillers%60.0)),
                                                   Html.FROM_HTML_MODE_COMPACT)
                                   );
                                   currentMillers += 1;
                               }
                               @Override
                               public void onError(@NonNull Throwable e) {
                               }
                               @Override
                               public void onComplete() {
                               }
                           });
    }

    /**
     * 回车时的事件
     * */
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_DOWN){
            if (v.getId()==R.id.barcode || v.getId()==R.id.verify_number){
                if (number.getText().toString().isEmpty()){//无拣货数 拿当前条码去加载当条信息
                    loadCurrentBarcode();
                }else{
                    updateCurrent();
                }
            }
        }
        return false;
    }

    /**
     * 点击时的事件
     * */
    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.btn){
            picking();
        }
        if (v.getId()==R.id.back){
            finish();
        }
        if (v.getId()==R.id.lock){
            ImageView lock = (ImageView)findViewById(R.id.lock);
            if (lockStatus){
                lock.setImageResource(R.drawable.ic__4gf_unlock);
                barcode.setInputType(InputType.TYPE_CLASS_TEXT);
            }else{
                lock.setImageResource(R.drawable.ic__4gf_lock);
                barcode.setInputType(InputType.TYPE_NULL);
            }
            lockStatus = !lockStatus;
        }
        if (v.getId()==R.id.give_up){
            MessageDialog.show("任务取消", "确定要放弃该任务吗？", "确定").setOkButtonClickListener(new OnDialogButtonClickListener<MessageDialog>() {
                @Override
                public boolean onClick(MessageDialog baseDialog, View v) {
                    giveUpTask();
                    return false;
                }
            }).setCancelable(true);
        }
    }
    private void loadCurrentBarcode(){
        String barcodeStr = barcode.getText().toString();
        SQLiteDatabase db = taskDb.getReadableDatabase();
        Cursor cursor=db.rawQuery("SELECT * FROM "+TaskTable.TABLE_NAME+" WHERE `location` = ? AND (barcode = ? OR barcodeAs = ?) AND pickingTime IS NULL LIMIT 1",
                new String[]{pickingItem.getLocation(),barcodeStr,barcodeStr});
        if (!cursor.moveToFirst()){
            TipDialog.show("无此条码信息",WaitDialog.TYPE.ERROR);
            setVibrator();//报警
        }else{
            int numIndex = cursor.getColumnIndex("anticipatedQuantity");
            int idIndex = cursor.getColumnIndex("id");
            pickingItem.setAnticipatedQuantity(cursor.getInt(numIndex));
            pickingItem.setId(cursor.getInt(idIndex));
            number.setText(String.valueOf(pickingItem.getAnticipatedQuantity()));
            verifyNumber.setText(String.valueOf(pickingItem.getAnticipatedQuantity()));
            mediaPlayer.start();//成功
        }
        cursor.close();
    }
    /**
     * 点击完成当前库位拣货时 进行的加载事件
     * */
    private void completeLoad(){
        Cursor cursor = null;
        try {
            cursor=DBManager.query(this,"SELECT * FROM "+TaskTable.TABLE_NAME+" WHERE `id` > ? AND pickingTime IS NULL LIMIT 2",
                    new String[]{String.valueOf(pickingItem.getId())});
            if (cursor.getCount()==0){
                cursor.close();
                TipDialog.show("任务拣货完毕！",WaitDialog.TYPE.SUCCESS);
                inquiryTaskStart();
                return;
            }
            //按钮仍为 完成当前拣货 加载当前第一条数据
            cursor.moveToFirst();
            int locationIndex = cursor.getColumnIndex("location");
            int wayIndex = cursor.getColumnIndex("way");
            PickingItem item = new PickingItem();
            item.setLocation(cursor.getString(locationIndex));
            item.setWay(cursor.getString(wayIndex));
            pickingItem = item;
            if (cursor.getCount()==2){
                //如果有两条结果 对比两条库位是否一致 一致则修改按钮为 BTN_TEXT_BEFORE
                cursor.moveToNext();
                locationIndex = cursor.getColumnIndex("location");
                if (pickingItem.getLocation().equals(cursor.getString(locationIndex))){
                    btn.setText(BTN_TEXT_BEFORE);
                }else{
                    btn.setText(BTN_TEXT);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor!=null){
                cursor.close();
            }
        }
        //渲染子视图
        way.setText(pickingItem.getWay());
        currentLoc.setText(pickingItem.getLocation());
        number.setText("");
        barcode.setText("");
        verifyNumber.setText("");

        barcode.requestFocus();
    }
    /**
     * 渲染局部视图
     * */
    private void renderingPartView(Integer realQty){
        pickingNumber.setUnfinishedTaskCount(pickingNumber.getUnfinishedTaskCount()-1);
        pickingNumber.setUserBeenWorkCount(pickingNumber.getUserBeenWorkCount()+realQty);
        pickingNumber.setBeenQty(pickingNumber.getBeenQty()+realQty);
        changeNumberUi();
        //成功 声音播报
        mediaPlayer.start();
        number.setText("");
        verifyNumber.setText("");
        barcode.setText("");

        if (btn.getText().toString().equals(BTN_TEXT_BEFORE)){
            //btn 为 提前完成拣货时
            Cursor cursor = null;
            try {
                cursor = DBManager.query(this,"SELECT 1 FROM "+TaskTable.TABLE_NAME+" WHERE `location` = ? AND pickingTime IS NULL LIMIT 2",
                        new String[]{String.valueOf(pickingItem.getLocation())});
                if (cursor.getCount()==0){
                    TipDialog.show("指针错误，联系主管关闭当前任务重开",WaitDialog.TYPE.ERROR);
                    setVibrator();
                    return;
                }
                if (cursor.getCount()==1){
                    btn.setText(BTN_TEXT);//库位待拣任务小于两条 变更按钮
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (cursor!=null){
                    cursor.close();
                }
            }
            barcode.requestFocus();
        }else{
            btn.requestFocus();
            btn.requestFocusFromTouch();
        }
    }
    /**
     * 更新当前ITEM信息
     * */
    private void updateCurrent(){
        if (pickingItem.getPickingTime()!=null){
            return;
        }
        if (verifyNumber.getText().toString().isEmpty()){
            TipDialog.show("真实拣货数量未填写！",WaitDialog.TYPE.ERROR,2000);
            return;
        }
        //更新当前数据
        int realQty = Integer.parseInt(verifyNumber.getText().toString());
        pickingItem.setPickingTime(DateUtil.getCurrentFormat(DateUtil.DATE_DATE_TIME));
        pickingItem.setRealQuantity(realQty);
        ContentValues values = new ContentValues();
        values.put("realQuantity", pickingItem.getRealQuantity());
        values.put("pickingTime",pickingItem.getPickingTime());

        SQLiteDatabase db = SQLiteDataProxy.getSQLiteProxy(this).getSQLiteDataBase();
        try {
            db.beginTransaction();
            db.update(TaskTable.TABLE_NAME,values,"id = ?",new String[]{String.valueOf(pickingItem.getId())});
            db.setTransactionSuccessful();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            db.endTransaction();
        }
        renderingPartView(realQty);
    }
    /**
     * 按库位批量提交
     * */
    private void picking(){
        if (pickingItem.getPickingTime()==null){
            updateCurrent();
        }
        ArrayList<HashMap<String,Object>> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = DBManager.query(this,"SELECT * FROM "+TaskTable.TABLE_NAME+" WHERE `location` = ? ",
                    new String[]{String.valueOf(pickingItem.getLocation())});
            if (cursor!=null){
                while (cursor.moveToNext()){
                    int idIndex = cursor.getColumnIndex("detailId");
                    int rqIndex = cursor.getColumnIndex("realQuantity");
                    int ptIndex = cursor.getColumnIndex("pickingTime");
                    String pickingTime = cursor.getString(ptIndex);
                    if (pickingTime == null || pickingTime.isEmpty()){
                        int barcodeIndex = cursor.getColumnIndex("barcode");
                        TipDialog.show(cursor.getString(barcodeIndex)+"未拣完",WaitDialog.TYPE.WARNING);
                        setVibrator();
                        cursor.close();
                        return;
                    }
                    HashMap<String, Object> item = new HashMap<>();
                    item.put("id", cursor.getInt(idIndex));
                    item.put("qty", cursor.getInt(rqIndex));
                    item.put("pickingTime",pickingTime);
                    list.add(item);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor!=null){
                cursor.close();
            }
        }
        WaitDialog.show("提交拣货记录中,请稍等...");
        SwmsSubscribe.picking(list, picking.getCode(), btn.getText().toString().equals(BTN_TEXT_BEFORE), new SwmsHandlerCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                if (btn.getText().toString().equals(BTN_TEXT)){
                    WaitDialog.dismiss();
                    //向下加载库位信息
                    completeLoad();
                }else{
                    //后续
                    TipDialog.show("任务拣货完毕！",WaitDialog.TYPE.SUCCESS);
                    clearTask();
                }
            }
            @Override
            public void onFinally() {
                WaitDialog.dismiss();
            }
        });
    }
}