package com.hw.nativeapp.ui.activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.R;
import com.hw.nativeapp.httpnet.ErrorConsumer;
import com.hw.nativeapp.httpnet.ResponseConsumer;
import com.hw.nativeapp.httpnet.entity.handleBean;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.RxUtil;
import com.squareup.picasso.Picasso;
import com.sunmi.extprinterservice.ExtPrinterService;

import java.sql.Array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


public class IssueTicketsActivity extends BaseActivity  {

    public static final Integer COUNTDOWN_TIME = 120000;
    private CountDownTimer timer;
    private TitleBar titleBar;

    @BindView(R.id.print_num)
    TextView print_num;
    @BindView(R.id.tx_customerMobile)
    TextView tx_customerMobile;

    private ExtPrinterService ext;
    private int printNum = 1;

    private JSONArray viewerList = new JSONArray();
    private JSONArray dataList = new JSONArray();
    @Override
    void initView() {
        titleBar = findViewById(R.id.tb_main_bar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                ActivityUtils.activityFinish(IssueTicketsActivity.this, true );
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue_tickets);
        selfIndex();
        bindExtPrinterService();
        getPageTransmitParams();
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (serviceConnection != null) {
            try {
                unbindService(serviceConnection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceConnection != null) {
            try {
                unbindService(serviceConnection);
            } catch (Exception e) {
                e.printStackTrace();
            }
            serviceConnection = null;
        }
    }
    //获取页面传递参数
    private void getPageTransmitParams(){
        Intent transmitIntent = getIntent();
        viewerList = JSONArray.parseArray(transmitIntent.getStringExtra("viewerList"));
        print_num.setText(printNum +"/"+viewerList.size());
        Log.e("serviceConnection","---------------serviceConnection--------------"+ (serviceConnection));
    }

    private void initPageView() {
        print_num.setText(printNum +"/"+viewerList.size());
        getTicketOut(viewerList.getJSONObject(printNum - 1));
    }

    private void selfIndex(){
        MApplication.getApiService().selfIndex(  System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        tx_customerMobile.setText("客服电话：" + data.getString("customerMobile"));
                    }

                    @Override
                    public void onFailed(int code, String msg) {
                    }
                }, new ErrorConsumer());
    }

    private void getTicketOut(JSONObject obj){
        JSONObject options = new  JSONObject();
        options.put("orderId", obj.getString("orderId"));
        String [] list = new String[1];
        list[0] = obj.getString("id");
        options.put("viewerList", list);
        MApplication.getApiService().ticketout( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) throws RemoteException {
                        JSONArray rows = data.getJSONArray("rows");
                        dataList = rows;
                        startPrinting();
                    }

                    @Override
                    public void onFailed(int code, String msg) {

                    }
                }, new ErrorConsumer());
    }

    // 开始打印
    private void startPrinting() throws RemoteException {
        /*
        * 打印机状态
        * -1 打印机脱机或打印服务还未连接打印机
        * 0 打印机运⾏正常
        * 1 打印机开盖
        * 2 打印机缺纸
        * 3 打印机即将缺纸
        * 4 打印机过热
        * */
        int printerStatus = ext.getPrinterStatus(); //
        Log.e("printerStatus","---------------printerStatus--------------"+printerStatus);
        if(printerStatus != 0){
            String msg = printerStatus == -1 ? "打印机脱机或打印服务还未连接打印机" : printerStatus == 1 ? "打印机开盖" : printerStatus == 2 ? "打印机缺纸" : printerStatus == 3 ? "打印机即将缺纸" : "打印机过热";
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            return;
        }
        ext.startTransBuffer(); //启⽤事务模式
        ext.printText("测试");
        ext.printText("测试");
        ext.printText("测试");
        ext.endTransBuffer(); //结束事务模式
        //  打印完成，开始打印下一张
        printNum++;

        if(printNum < viewerList.size()){
            getTicketOut(viewerList.getJSONObject(printNum - 1));
        }
    }

    // 打印注册
    private void bindExtPrinterService() {
        Intent intent = new Intent();
        intent.setPackage("com.sunmi.extprinterservice");
        intent.setAction("com.sunmi.extprinterservice.PrinterService");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override public void onServiceConnected(ComponentName name, IBinder
                service) {
            ext = ExtPrinterService.Stub.asInterface(service);
            initPageView();
            Log.e("onServiceConnected","---------------onServiceConnected--------------");
        }
        @Override public void onServiceDisconnected(ComponentName name) {
            Log.e("onServiceDisconnected","---------------onServiceDisconnected--------------");
        }
        @Override public void onBindingDied(ComponentName name) {
            Log.e("onBindingDied","---------------onBindingDied--------------");
        }
        @Override public void onNullBinding(ComponentName name) {
            Log.e("onNullBinding","---------------onNullBinding--------------");
        }
    };

}