com.gqp.duoduo.ui.activity.SearchHisSettlementActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.gqp.duoduo.ui.activity.SearchHisSettlementActivity.java

Source

package com.gqp.duoduo.ui.activity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.speech.VoiceRecognitionService;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.gqp.common.adapter.ViewHolderBind;
import com.gqp.common.cache.SpCache;
import com.gqp.common.exception.ErrorMessageException;
import com.gqp.common.http.HttpRequest;
import com.gqp.common.rx.android.schedulers.AndroidSchedulers;
import com.gqp.common.rx.bus.RxBus;
import com.gqp.duoduo.App;
import com.gqp.duoduo.R;
import com.gqp.duoduo.adapter.SearchGoodsResultAdapter;
import com.gqp.duoduo.base.BaseActivity;
import com.gqp.duoduo.base.Constants;
import com.gqp.duoduo.database.DeliverModel;
import com.gqp.duoduo.database.Goods;
import com.gqp.duoduo.database.dao.GoodsDao;
import com.gqp.duoduo.model.CommonItem;
import com.gqp.duoduo.model.GoodsList;
import com.gqp.duoduo.model.Settlement;
import com.gqp.duoduo.printer.BlueToothPrinter;
import com.gqp.duoduo.printer.ThreadPoolManager;
import com.gqp.duoduo.utils.HttpUrl;
import com.gqp.duoduo.utils.MapUtils;
import com.gqp.duoduo.utils.StringUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.view.ViewClickEvent;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Request;
import com.sunmi.controller.ICallback;
import com.sunmi.impl.V1Printer;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

import static com.gqp.common.util.ViewUtils.getView;
import static com.gqp.duoduo.utils.StringUtil.priceFormat;

/**
 * Created by admin on 2015/10/29.
 */
public class SearchHisSettlementActivity extends BaseActivity implements RecognitionListener {
    //?
    private static final int REQUEST_UI = 1;
    public static final int STATUS_None = 0;
    public static final int STATUS_WaitingReady = 2;
    public static final int STATUS_Ready = 3;
    public static final int STATUS_Speaking = 4;
    public static final int STATUS_Recognition = 5;
    private SpeechRecognizer speechRecognizer;
    private int status = STATUS_None;
    private long speechEndTime = -1;
    private static final int EVENT_ERROR = 11;

    private List<Settlement.MarketSettleEntity> mList;
    //    private SearchGoodsResultAdapter adapter;
    private TextView searchCommit;
    private EditText searchText;
    //    private LinearLayout listView;
    private ImageView search_voice;
    private TextView commit;

    private TextView moneyText;

    @Bind(R.id.settlement_view_container)
    LinearLayout container;
    @Bind(R.id.settlement_view_nodata_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.settlement_view_data_layout)
    LinearLayout dataLayout;

    private Settlement.SettleMessageEntity message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_settlement_view);
        ButterKnife.bind(this);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        sp.edit().remove(Constants.EXTRA_INFILE).commit(); // infile?PCM?????
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
                new ComponentName(this, VoiceRecognitionService.class));
        speechRecognizer.setRecognitionListener(this);
        mList = new ArrayList<>();

        searchText = (EditText) findViewById(R.id.search_edittext);
        searchCommit = (TextView) findViewById(R.id.search_commit);
        search_voice = (ImageView) findViewById(R.id.search_voice);
        commit = (TextView) findViewById(R.id.settlement_view_commit);

        moneyText = (TextView) findViewById(R.id.settlement_view_money);

        searchCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = searchText.getText().toString();
                if (App.getNetState()) {
                    getHisSettlementInfo(input);

                } else {
                    showToast("???");
                }
            }
        });

        search_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(SearchHisSettlementActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        //EditText ?100
                        searchText.setText(new StringBuilder().append(year).append("-")
                                .append((month + 1) < 10 ? "0" + (month + 1) : (month + 1)).append("-")
                                .append((day < 10) ? "0" + day : day));
                        String input = searchText.getText().toString();
                        if (App.getNetState()) {
                            getHisSettlementInfo(input);

                        } else {
                            showToast("???");
                        }
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
                        .show();
            }
        });
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCommitClick(message);
            }
        });

        compositeSubscription
                .add(RxView.clickEvents(findViewById(R.id.search_back)).subscribe(new Action1<ViewClickEvent>() {
                    @Override
                    public void call(ViewClickEvent viewClickEvent) {
                        finish();
                    }
                }));

        Observable<MainActivity.MainActivityEvent.DeliverEvent> deliverEventObservable = RxBus.getDefault()
                .register(MainActivity.MainActivityEvent.DeliverEvent.class);

        compositeSubscription
                .add(deliverEventObservable.subscribe(new Action1<MainActivity.MainActivityEvent.DeliverEvent>() {
                    @Override
                    public void call(MainActivity.MainActivityEvent.DeliverEvent deliverEvent) {

                        finish();
                    }
                }));

    }

    public void onCommitClick(Settlement.SettleMessageEntity settleMessageEntity) {
        String totalStr = StringUtil.priceFormat(getRealInCome(settleMessageEntity));
        //        boolean isInnerPrint = SpCache.getBoolean(Constants.IS_INNER_PRINTER, false);
        //        if (isInnerPrint) {
        //            innerPrint(settleMessageEntity, totalStr);
        //        }
        // else {
        boolean isWide = SpCache.getBoolean(Constants.IS_WIDE_PRINTER, false);
        if (isWide) {
            print(getMarketListStr(settleMessageEntity), getTotalPrintStr(settleMessageEntity), totalStr);
        } else {
            printNarrow(settleMessageEntity, totalStr);
        }
        //        }
        finish();
    }

    public double getRealInCome(Settlement.SettleMessageEntity settleMessageEntity) {
        Map tmpMap = settleMessageEntity.getSettelmentTotal();
        double ss = MapUtils.doubleMapGet(tmpMap, "realincome");
        moneyText.setText("" + StringUtil.priceFormat(ss));
        return ss;
    }

    private String getMarketListStr(Settlement.SettleMessageEntity settleMessageEntity) {
        StringBuffer sb = new StringBuffer();
        for (Settlement.MarketSettleEntity marketModel : settleMessageEntity.getSettelment()) {
            StringBuffer tmpStr = new StringBuffer();
            tmpStr.append(marketModel.getSeq() + ". ");
            tmpStr.append(marketModel.getCustomer());
            sb.append(StringUtil.getFormatString(tmpStr.toString(), 34, 1));
            sb.append(marketModel.getGoodstotalamount());
            sb.append("\n");
        }
        return sb.toString();
    }

    private String getTotalPrintStr(Settlement.SettleMessageEntity settleMessageEntity) {
        StringBuilder totalStr = new StringBuilder();

        Map settle = settleMessageEntity.getSettelmentTotal();
        totalStr.append("  ?:" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("realincome"))) + "", 12));
        totalStr.append("?:" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("returnamount"))) + "", 12));
        totalStr.append('\n');
        totalStr.append("  :" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("clearingdebt"))) + "", 12));
        totalStr.append("?:" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("cutdownprice"))) + "", 12));
        totalStr.append('\n');
        totalStr.append(":" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("advanceamount"))) + "", 12));
        totalStr.append(":" + StringUtil.getFormatString(
                StringUtil.priceFormat(StringUtil.doubleParse(settle.get("ticketamount"))) + "", 12));
        totalStr.append('\n');
        totalStr.append(StringUtil.getFormatString(" ", 23));
        totalStr.append("  :" + StringUtil
                .getFormatString(StringUtil.priceFormat(StringUtil.doubleParse(settle.get("debt"))) + "", 12));
        totalStr.append('\n');
        totalStr.append('\n');
        totalStr.append("?:" + StringUtil.getFormatString("0.00", 12));
        totalStr.append(":" + StringUtil.getFormatString("0.00", 12));
        totalStr.append('\n');
        return totalStr.toString();

    }

    private void getHisSettlementInfo(String input) {

        if (TextUtils.isEmpty(input)) {
            return;
        }
        Request request = new Request.Builder().url(HttpUrl.QUERY_SETTLEMENT)
                .post(new FormEncodingBuilder().add("irdate", input).build())
                .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
                .tag(System.currentTimeMillis()).build();

        compositeSubscription
                .add(HttpRequest.modelRequest(request, Settlement.class).subscribe(new Subscriber<Settlement>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof ErrorMessageException) {
                            if (App.getNetState()) {
                                reLogin();
                            } else {
                                showToast("??");
                            }
                        }
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onNext(Settlement inventoryList) {

                        if (inventoryList != null) {
                            message = inventoryList.getMessage();
                            mList = inventoryList.getMessage().getSettelment();
                            getRealInCome(inventoryList.getMessage());
                            dataLayout.setVisibility(View.VISIBLE);
                            noDataLayout.setVisibility(View.GONE);

                            container.removeAllViews();

                            LayoutInflater inflater = LayoutInflater.from(SearchHisSettlementActivity.this);

                            View headerView = inflater.inflate(R.layout.common_item_hearder_layout, null);
                            ((TextView) headerView.findViewById(R.id.common_item_01)).setText("??");
                            ((TextView) headerView.findViewById(R.id.common_item_02)).setText("?");
                            headerView.setBackgroundResource(R.color.gray_whiter);
                            container.addView(headerView);

                            int index = 0;
                            for (Settlement.MarketSettleEntity marketModel : mList) {

                                View view = inflater.inflate(R.layout.common_item_layout, null);
                                ViewMarketItemHolder holder = new ViewMarketItemHolder(view);
                                holder.bind(marketModel, index);
                                container.addView(view);

                                View divider = new View(SearchHisSettlementActivity.this);
                                divider.setLayoutParams(
                                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                                divider.setBackgroundColor(Color.parseColor("#DDDDDD"));
                                container.addView(divider);
                                index++;
                            }
                            View footerdivider = new View(SearchHisSettlementActivity.this);
                            footerdivider.setLayoutParams(
                                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 38));

                            footerdivider.setBackgroundColor(Color.parseColor("#ededed"));
                            container.addView(footerdivider);
                            int sIndex = 0;
                            List<CommonItem> tmpList = formatData(inventoryList.getMessage().getSettelmentTotal());
                            for (CommonItem commonItem : tmpList) {
                                View view = inflater.inflate(R.layout.common_item_hearder_layout, null);
                                ViewItemHolder holder = new ViewItemHolder(view);
                                holder.bind(commonItem, index);
                                container.addView(view);
                                View divider = new View(SearchHisSettlementActivity.this);
                                divider.setLayoutParams(
                                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                                divider.setBackgroundColor(Color.parseColor("#dddddd"));
                                container.addView(divider);
                                if (sIndex == 0) {
                                    View footerView01 = new View(SearchHisSettlementActivity.this);
                                    footerView01.setLayoutParams(
                                            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 38));
                                    footerView01.setBackgroundResource(R.color.gray_whiter);
                                    container.addView(footerView01);
                                }
                                if (sIndex <= 2) {
                                    if (sIndex == 2) {
                                        View footerView01 = new View(SearchHisSettlementActivity.this);
                                        footerView01.setLayoutParams(new LinearLayout.LayoutParams(
                                                ViewGroup.LayoutParams.MATCH_PARENT, 38));
                                        footerView01.setBackgroundResource(R.color.gray_whiter);
                                        container.addView(footerView01);
                                    }
                                }
                                if (sIndex > 2 && sIndex <= 6) {
                                    if (sIndex == 6) {
                                        View footerView01 = new View(SearchHisSettlementActivity.this);
                                        footerView01.setLayoutParams(new LinearLayout.LayoutParams(
                                                ViewGroup.LayoutParams.MATCH_PARENT, 38));
                                        footerView01.setBackgroundResource(R.color.gray_whiter);
                                        container.addView(footerView01);
                                    }
                                }
                                sIndex++;
                            }

                        }
                    }
                }));
    }

    public class ViewMarketItemHolder extends ViewHolderBind<Settlement.MarketSettleEntity> {
        private TextView commonItemId;
        private TextView commonItem01;
        private TextView commonItem02;
        private TextView commonItem03;
        private TextView commonItem04;
        private TextView commonItem05;

        private RelativeLayout bigLayout;

        public ViewMarketItemHolder(View view) {
            super(view);
            commonItemId = (TextView) view.findViewById(R.id.common_item_id);
            commonItem01 = (TextView) view.findViewById(R.id.common_item_01);
            commonItem02 = (TextView) view.findViewById(R.id.common_item_02);
            commonItem03 = (TextView) view.findViewById(R.id.common_item_03);
            commonItem04 = (TextView) view.findViewById(R.id.common_item_04);
            commonItem05 = (TextView) view.findViewById(R.id.common_item_05);
        }

        @Override
        public void bind(Settlement.MarketSettleEntity data, final int pos) {

            commonItemId.setVisibility(View.VISIBLE);
            commonItemId.setText(data.getSeq() + ".");
            commonItem01.setText(data.getCustomer());
            commonItem02.setText(" " + data.getGoodstotalamount());
            commonItem03.setText(": " + StringUtil.priceFormatTwo(StringUtil.doubleParse(data.getDebt())));
            commonItem04.setText(
                    ": " + StringUtil.priceFormatTwo(StringUtil.doubleParse(data.getRealincome())));
            commonItem05.setText(
                    ": " + StringUtil.priceFormatTwo(StringUtil.doubleParse(data.getClearingdebt())));

        }
    }

    private List<CommonItem> formatData(Map settle) {
        List<CommonItem> list = new ArrayList<CommonItem>();
        CommonItem itemTmp = new CommonItem();
        itemTmp.setItem01("?");
        itemTmp.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "saletotalamount")));
        list.add(itemTmp);

        CommonItem itemTmp1 = new CommonItem();
        itemTmp1.setItem01("");
        itemTmp1.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "clearingdebt")));
        list.add(itemTmp1);
        CommonItem itemTmp2 = new CommonItem();
        itemTmp2.setItem01("");
        itemTmp2.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "advanceamount")));
        list.add(itemTmp2);
        CommonItem itemTmp3 = new CommonItem();
        itemTmp3.setItem01("?");
        itemTmp3.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "returnamount")));
        list.add(itemTmp3);
        CommonItem itemTmp4 = new CommonItem();
        itemTmp4.setItem01("?");
        itemTmp4.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "cutdownprice")));
        list.add(itemTmp4);
        CommonItem itemTmp6 = new CommonItem();
        itemTmp6.setItem01("");
        itemTmp6.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "ticketamount")));
        list.add(itemTmp6);
        CommonItem itemTmp5 = new CommonItem();
        itemTmp5.setItem01("");
        itemTmp5.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "debt")));
        list.add(itemTmp5);

        CommonItem itemTmp8 = new CommonItem();
        itemTmp8.setItem01("?");
        itemTmp8.setItem02("0.00");
        list.add(itemTmp8);
        CommonItem itemTmp9 = new CommonItem();
        itemTmp9.setItem01("??");
        itemTmp9.setItem02("0.00");
        list.add(itemTmp9);
        CommonItem itemTmp10 = new CommonItem();
        itemTmp10.setItem01("?");
        itemTmp10.setItem02(StringUtil.priceFormat(MapUtils.doubleMapGet(settle, "useadvanceamount")));
        list.add(itemTmp10);
        return list;

    }

    public class ViewItemHolder extends ViewHolderBind<CommonItem> {
        private TextView commonItem01;
        private TextView commonItem02;

        public ViewItemHolder(View view) {
            super(view);
            commonItem01 = (TextView) view.findViewById(R.id.common_item_01);
            commonItem02 = (TextView) view.findViewById(R.id.common_item_02);
        }

        @Override
        public void bind(CommonItem data, final int pos) {
            commonItem01.setText(data.getItem01());
            commonItem02.setText(" " + data.getItem02());

        }
    }

    public void startSearch() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SearchHisSettlementActivity.this);
        boolean api = sp.getBoolean("api", false);
        if (api) {
            switch (status) {
            case STATUS_None:
                start();
                status = STATUS_WaitingReady;
                break;
            case STATUS_WaitingReady:
                cancel();
                status = STATUS_None;
                break;
            case STATUS_Ready:
                cancel();
                status = STATUS_None;
                break;
            case STATUS_Speaking:
                stop();
                status = STATUS_Recognition;
                break;
            case STATUS_Recognition:
                cancel();
                status = STATUS_None;
                break;
            }
        } else {
            start();
        }
    }

    public void bindParams(Intent intent) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("tips_sound", true)) {
            intent.putExtra(Constants.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
            intent.putExtra(Constants.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
            intent.putExtra(Constants.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
            intent.putExtra(Constants.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
            intent.putExtra(Constants.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
        }
        if (sp.contains(Constants.EXTRA_INFILE)) {
            String tmp = sp.getString(Constants.EXTRA_INFILE, "").replaceAll(",.*", "").trim();
            intent.putExtra(Constants.EXTRA_INFILE, tmp);
        }
        if (sp.getBoolean(Constants.EXTRA_OUTFILE, false)) {
            intent.putExtra(Constants.EXTRA_OUTFILE, "sdcard/outfile.pcm");
        }
        if (sp.contains(Constants.EXTRA_SAMPLE)) {
            String tmp = sp.getString(Constants.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_SAMPLE, Integer.parseInt(tmp));
            }
        }
        if (sp.contains(Constants.EXTRA_LANGUAGE)) {
            String tmp = sp.getString(Constants.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_LANGUAGE, tmp);
            }
        }
        if (sp.contains(Constants.EXTRA_NLU)) {
            String tmp = sp.getString(Constants.EXTRA_NLU, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_NLU, tmp);
            }
        }

        if (sp.contains(Constants.EXTRA_VAD)) {
            String tmp = sp.getString(Constants.EXTRA_VAD, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_VAD, tmp);
            }
        }
        String prop = null;
        if (sp.contains(Constants.EXTRA_PROP)) {
            String tmp = sp.getString(Constants.EXTRA_PROP, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_PROP, Integer.parseInt(tmp));
                prop = tmp;
            }
        }

        // offline asr
        {
            intent.putExtra(Constants.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1");
            intent.putExtra(Constants.EXTRA_LICENSE_FILE_PATH, "/sdcard/easr/license-tmp-20150530.txt");
            if (null != prop) {
                int propInt = Integer.parseInt(prop);
                if (propInt == 10060) {
                    intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_Navi");
                } else if (propInt == 20000) {
                    intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_InputMethod");
                }
            }
            intent.putExtra(Constants.EXTRA_OFFLINE_SLOT_DATA, buildTestSlotData());
        }
    }

    private String buildTestSlotData() {
        JSONObject slotData = new JSONObject();
        JSONArray name = new JSONArray().put("?").put("");
        JSONArray song = new JSONArray().put("").put("?");
        JSONArray artist = new JSONArray().put("?").put("?");
        JSONArray app = new JSONArray().put("").put("");
        JSONArray usercommand = new JSONArray().put("?").put("");
        try {
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_NAME, name);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_SONG, song);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_ARTIST, artist);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_APP, app);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_USERCOMMAND, usercommand);
        } catch (JSONException e) {

        }
        return slotData.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onResults(data.getExtras());
        }
    }

    private void start() {
        //        txtLog.setText("");
        //        print("?");
        Intent intent = new Intent();
        bindParams(intent);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        {

            String args = sp.getString("args", "");
            if (null != args) {
                //                print("?" + args);
                intent.putExtra("args", args);
            }
        }
        boolean api = sp.getBoolean("api", false);
        if (api) {
            speechEndTime = -1;
            speechRecognizer.startListening(intent);
        } else {
            intent.setAction("com.baidu.action.RECOGNIZE_SPEECH");
            startActivityForResult(intent, REQUEST_UI);
        }

        //        txtResult.setText("");
    }

    private void stop() {
        speechRecognizer.stopListening();
        //        print("?");
    }

    private void cancel() {
        speechRecognizer.cancel();
        status = STATUS_None;
        //        print("??");
    }

    @Override
    public void onReadyForSpeech(Bundle params) {
        status = STATUS_Ready;
        //        print("??");
    }

    @Override
    public void onBeginningOfSpeech() {
        status = STATUS_Speaking;
        //        searchVoice.setText("");
        //        print("??");
    }

    @Override
    public void onRmsChanged(float rmsdB) {

    }

    @Override
    public void onBufferReceived(byte[] buffer) {

    }

    @Override
    public void onEndOfSpeech() {
        speechEndTime = System.currentTimeMillis();
        status = STATUS_Recognition;
        //        print("???");
        //        searchVoice.setText("");
    }

    @Override
    public void onError(int error) {
        status = STATUS_None;
        StringBuilder sb = new StringBuilder();
        switch (error) {
        case SpeechRecognizer.ERROR_AUDIO:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_CLIENT:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
            sb.append("???");
            break;
        case SpeechRecognizer.ERROR_NETWORK:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_NO_MATCH:
            sb.append("?");
            break;
        case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_SERVER:
            sb.append("?");
            break;
        case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
            sb.append("");
            break;
        }
        sb.append(":" + error);
        //        print("" + sb.toString());
        //        searchVoice.setText("");
    }

    @Override
    public void onResults(Bundle results) {
        long end2finish = System.currentTimeMillis() - speechEndTime;
        status = STATUS_None;
        ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        //        print("?" + Arrays.toString(nbest.toArray(new_version String[nbest.size()])));
        System.out.println("" + nbest.get(0));
        //        String json_res = results.getString("origin_result");
        //        try {
        //            print("origin_result=\n" + new_version JSONObject(json_res).toString(4));
        //        } catch (Exception e) {
        //            print("origin_result=[warning: bad json]\n" + json_res);
        //        }
        if (nbest != null && nbest.size() > 0) {
            getHisSettlementInfo(nbest.get(0));
        } else {
            showToast("?");
        }
        //        searchVoice.setText("");
        String strEnd2Finish = "";
        if (end2finish < 60 * 1000) {
            strEnd2Finish = "(waited " + end2finish + "ms)";
        }
    }

    @Override
    public void onPartialResults(Bundle partialResults) {
        ArrayList<String> nbest = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        if (nbest.size() > 0) {
            //            print("~" + Arrays.toString(nbest.toArray(new_version String[0])));
        }
    }

    @Override
    public void onEvent(int eventType, Bundle params) {
        switch (eventType) {
        case EVENT_ERROR:
            String reason = params.get("reason") + "";
            //                print("EVENT_ERROR, " + reason);
            break;
        case VoiceRecognitionService.EVENT_ENGINE_SWITCH:
            int type = params.getInt("engine_type");
            //                print("*?" + (type == 0 ? "" : ""));
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compositeSubscription != null) {
            if (!compositeSubscription.isUnsubscribed()) {
                compositeSubscription.unsubscribe();
            }
            compositeSubscription = null;
        }
    }

    private void print(String marketListStr, String totalStr, String totalMoney) {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String tmpStr = "";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("              " + SpCache.getString(Constants.USER_DIS, "") + "           ");
        stringBuilder.append('\n');
        stringBuilder.append("                                      ");
        stringBuilder.append('\n');
        stringBuilder.append("??" + SpCache.getString(Constants.REAL_NAME, ""));
        stringBuilder.append("   " + SpCache.getString(Constants.USER_TYPE, "") + " "
                + SpCache.getString(Constants.USER_WAREHOUSENAME, ""));
        stringBuilder.append('\n');
        stringBuilder.append("" + sf.format(calendar.getTime()));
        stringBuilder.append('\n');
        stringBuilder.append("?");
        stringBuilder.append('\n');
        stringBuilder.append("??                          ?");
        if (!TextUtils.isEmpty(marketListStr)) {
            stringBuilder.append('\n');
            stringBuilder.append(marketListStr);
        }
        stringBuilder.append('\n');
        stringBuilder.append("");
        if (!TextUtils.isEmpty(totalStr)) {
            stringBuilder.append('\n');
            stringBuilder.append(totalStr);
        }
        stringBuilder.append('\n');
        tmpStr = "" + totalMoney + "";
        stringBuilder.append(StringUtil.getHeadFormatString(tmpStr, 48, "-"));
        stringBuilder.append('\n');
        stringBuilder.append("");
        stringBuilder.append('\n');
        stringBuilder.append("");
        stringBuilder.append('\n');
        stringBuilder.append('\n');
        stringBuilder.append('\n');
        stringBuilder.append('\n');
        stringBuilder.append('\n');
        if (BlueToothPrinter.getInstance().isConnect()) {
            BlueToothPrinter.getInstance().print(stringBuilder.toString());
        } else {
            showToast("??");
        }

    }

    //
    //    private static String TAG = "SunmiPrinterTest";
    //    private V1Printer printer;
    //    private ICallback callback;
    //
    //    private void initInnerPrinter() {
    //        printer = new V1Printer(this);
    //
    //        callback = new ICallback() {
    //
    //            @Override
    //            public void onRunResult(boolean isSuccess) {
    //                Log.i(TAG, "onRunResult:" + isSuccess);
    //            }
    //
    //            @Override
    //            public void onReturnString(String result) {
    //                Log.i(TAG, "onReturnString:" + result);
    //            }
    //
    //            @Override
    //            public void onRaiseException(int code, String msg) {
    //                Log.i(TAG, "onRaiseException:" + code + ":" + msg);
    //            }
    //
    //        };
    //
    //        printer.setCallback(callback);
    //    }
    //
    //    private void innerPrint(final Settlement.SettleMessageEntity settleMessageEntity, final String totalMoney) {
    //        initInnerPrinter();
    //        printer.beginTransaction();
    //        ThreadPoolManager.getInstance().executeTask(new Runnable() {
    //
    //            @Override
    //            public void run() {
    //                Calendar calendar = Calendar.getInstance();
    //                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //                String tmpStr = "";
    //                printer.setAlignment(1);
    //                printer.printText(SpCache.getString(Constants.USER_DIS, ""));
    //                printer.printText("\n");
    //
    //                printer.printText("");
    //                printer.printText("\n");
    //                printer.setAlignment(0);
    //                printer.printText("??" + SpCache.getString(Constants.REAL_NAME, ""));
    //                printer.printText("\n");
    //                printer.printText("" + SpCache.getString(Constants.USER_TYPE, "") + " " + SpCache.getString(Constants.USER_WAREHOUSENAME, ""));
    //                printer.printText("\n");
    //                printer.printText("" + sf.format(calendar.getTime()));
    //                printer.printText("\n");
    //                printer.setAlignment(1);
    //                printer.printText("?");
    //                printer.printText("\n");
    //                printer.setAlignment(0);
    //                printer.printText("??             ?");
    //                printer.printText("\n");
    //                for (Settlement.MarketSettleEntity marketModel : settleMessageEntity.getSettelment()) {
    //                    printer.printColumnsText(new String[]{marketModel.getSeq() + "." + marketModel.getCustomer(), marketModel.getGoodstotalamount()}, new int[]{22, 8}, new int[]{0, 2});
    //                }
    //                printer.printText("");
    //                printer.printText("\n");
    //                Map settle = settleMessageEntity.getSettelmentTotal();
    //                printer.printText("?:" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("realincome"))) + "");
    //                printer.printText("\n");
    //                printer.printText("?:" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("returnamount"))) + "");
    //                printer.printText("\n");
    //                printer.printText(":" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("clearingdebt"))) + "");
    //                printer.printText("\n");
    //                printer.printText("?:" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("cutdownprice"))) + "");
    //                printer.printText("\n");
    //                printer.printText(":" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("advanceamount"))) + "");
    //                printer.printText("\n");
    //                printer.printText(":" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("ticketamount"))) + "");
    //                printer.printText("\n");
    //                printer.printText(":" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("debt"))) + "");
    //                printer.printText("\n");
    //                printer.printText("?:" + "0.00");
    //                printer.printText("\n");
    //                printer.printText(":" + "0.00");
    //                printer.printText("\n");
    //                printer.setFontSize(32);
    //                printer.setAlignment(2);
    //                printer.setFontName(Typeface.DEFAULT_BOLD);
    //                tmpStr = "" + totalMoney + "";
    //                printer.printText(tmpStr);
    //                printer.printText("\n");
    //                printer.setFontSize(24);
    //                printer.setAlignment(0);
    //                printer.setFontName(Typeface.DEFAULT);
    //                printer.lineWrap(2);
    //                printer.printText("");
    //                printer.printText("\n");
    //                printer.printText("");
    //                printer.lineWrap(6);
    //                printer.commitTransaction();
    //            }
    //        });
    //
    //
    //    }
    //
    private void printNarrow(Settlement.SettleMessageEntity settleMessageEntity, String totalMoney) {
        BlueToothPrinter blueToothPrinter = BlueToothPrinter.getInstance();
        blueToothPrinter.initService();
        blueToothPrinter.setContext(this);
        if (!blueToothPrinter.isConnect()) {
            showToast("??");
            return;
        }
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String tmpStr = "";
        blueToothPrinter.setAlignment(1);
        blueToothPrinter.printText(SpCache.getString(Constants.USER_DIS, ""));
        blueToothPrinter.printText("\n");

        blueToothPrinter.printText("");
        blueToothPrinter.printText("\n");
        blueToothPrinter.setAlignment(0);
        blueToothPrinter.printText("??" + SpCache.getString(Constants.REAL_NAME, ""));
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("" + SpCache.getString(Constants.USER_TYPE, "") + " "
                + SpCache.getString(Constants.USER_WAREHOUSENAME, ""));
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("" + sf.format(calendar.getTime()));
        blueToothPrinter.printText("\n");
        blueToothPrinter.setAlignment(1);
        blueToothPrinter.printText("?");
        blueToothPrinter.printText("\n");
        blueToothPrinter.setAlignment(0);
        blueToothPrinter.printText("??             ?");
        blueToothPrinter.printText("\n");
        for (Settlement.MarketSettleEntity marketModel : settleMessageEntity.getSettelment()) {
            blueToothPrinter.printText(
                    StringUtil.getFormatString(marketModel.getSeq() + "." + marketModel.getCustomer(), 22, 1));
            blueToothPrinter.printText(StringUtil.getHeadFormatString(marketModel.getGoodstotalamount(), 8, 1));
            blueToothPrinter.printText("\n");
        }
        blueToothPrinter.printText("");
        blueToothPrinter.printText("\n");
        Map settle = settleMessageEntity.getSettelmentTotal();
        blueToothPrinter.printText(
                "?:" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("realincome"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("?:"
                + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("returnamount"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText(":"
                + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("clearingdebt"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("?:"
                + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("cutdownprice"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText(":"
                + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("advanceamount"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText(":"
                + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("ticketamount"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText(
                ":" + StringUtil.priceFormat(StringUtil.doubleParse(settle.get("debt"))) + "");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("?:" + "0.00");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText(":" + "0.00");
        blueToothPrinter.printText("\n");
        blueToothPrinter.setAlignment(2);
        blueToothPrinter.setFontName(Typeface.DEFAULT_BOLD);
        tmpStr = "" + totalMoney + "";
        blueToothPrinter.printText(tmpStr);
        blueToothPrinter.printText("\n");
        blueToothPrinter.setAlignment(0);
        blueToothPrinter.setFontName(Typeface.DEFAULT);
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("\n");
        blueToothPrinter.printText("\n");
    }
}