package com.example.logisticsclient;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;


import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;


import HPRTAndroidSDKA300.HPRTPrinterHelper;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;


import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;


import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;


public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "io.fivefire/method_channel";
    private static final String EVENT_CHANNEL = "io.fivefire/event_channel";


    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private Context thisCon=null;

    private Thread thread;
    private static HPRTPrinterHelper HPRTPrinter=new HPRTPrinterHelper();


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



        thisCon=this.getApplicationContext();


        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, Result result) {

                        if (call.method.equals("isBTDevice")) {
                            boolean isBTDevice = isBTDevice();

                            if (isBTDevice) {
                                result.success(isBTDevice);
                            } else {
                                result.error("UNAVAILABLE", "没有发现蓝牙模块", null);
                            }
                        } else if (call.method.equals("isEnableBluetooth")) {
                            boolean isEnableBluetooth = isEnableBluetooth();

                            if (isEnableBluetooth) {
                                result.success(isEnableBluetooth);
                            } else {
                                result.error("UNAVAILABLE", "蓝牙未打开", null);
                            }
                        }else if (call.method.equals("enableBluetooth")) {
                            boolean enableBluetooth = enableBluetooth();

                            if (enableBluetooth) {
                                result.success(enableBluetooth);
                            } else {
                                result.error("UNAVAILABLE", "蓝牙打开失败", null);
                            }
                        } else if (call.method.equals("scanBT")) {
                            boolean isScan = scanBT();

                            if (isScan) {
                                result.success(isScan);
                            } else {
                                result.error("UNAVAILABLE", "蓝牙扫描出错", null);
                            }
                        } else if (call.method.equals("connectBT")) {
                            boolean isConn = connectBT((String) call.argument("address"));

                            if (isConn) {
                                result.success(isConn);
                            } else {
                                result.error("UNAVAILABLE", "连接蓝牙出错", null);
                            }
                        } else if (call.method.equals("disConnectBT")) {
                            boolean isConn = disConnnectBT();

                            if (isConn) {
                                result.success(isConn);
                            } else {
                                result.error("UNAVAILABLE", "关闭蓝牙出错", null);
                            }
                        }  else if (call.method.equals("isConnect")) {
                            boolean isConn = isConnect((String) call.argument("address"));

                            if (isConn) {
                                result.success(isConn);
                            } else {
                                result.error("UNAVAILABLE", "关闭蓝牙出错", null);
                            }
                        }else if (call.method.equals("cancelDiscoveryBT")) {
                            boolean cancelDiscovery = cancelDiscoveryBT();

                            if (cancelDiscovery) {
                                result.success(cancelDiscovery);
                            } else {
                                result.error("UNAVAILABLE", "取消蓝牙扫描出错", null);
                            }
                        }else if (call.method.equals("printOrder")) {
                            boolean isPrint = printOrder((Map<String, String>) call.argument("pum"), (Integer) call.argument("type"));

                            if (isPrint) {
                                result.success(isPrint);
                            } else {
                                result.error("UNAVAILABLE", "打印出错", null);
                            }
                        } else {
                            result.notImplemented();
                        }


                    }
                });


        new EventChannel(getFlutterView(), EVENT_CHANNEL).setStreamHandler(


                new EventChannel.StreamHandler() {
                    private BroadcastReceiver scanBlueReceiver;


                    @Override
                    public void onListen(Object o, EventChannel.EventSink eventSink) {
                        scanBlueReceiver = createScanBlueReceiver(eventSink);


                        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
                        IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
                        IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                        IntentFilter filter4 = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
                        IntentFilter filter5 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                        IntentFilter filter6 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
                        IntentFilter filter7 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
                        IntentFilter filter8  = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);







                        registerReceiver(scanBlueReceiver, filter1);
                        registerReceiver(scanBlueReceiver, filter2);
                        registerReceiver(scanBlueReceiver, filter3);
                        registerReceiver(scanBlueReceiver, filter4);
                        registerReceiver(scanBlueReceiver, filter5);
                        registerReceiver(scanBlueReceiver, filter6);
                        registerReceiver(scanBlueReceiver, filter7);
                        registerReceiver(scanBlueReceiver, filter8);





                    }

                    @Override
                    public void onCancel(Object o) {

                        unregisterReceiver(scanBlueReceiver);
                        scanBlueReceiver = null;

                    }
                }

        );


    }


    private void init(){
        System.out.println("===================AD:"+mBluetoothAdapter+"BM:"+mBluetoothManager);

        if (mBluetoothAdapter == null ){
            mBluetoothManager = (BluetoothManager) getSystemService(ContextWrapper.BLUETOOTH_SERVICE);
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }

    }


    /**
     * 判断当前设备蓝牙模块是否可用
     *
     * @return
     */
    private boolean isBTDevice() {
        init();
        boolean flag = true;
        try {
            if (mBluetoothAdapter == null) {
                flag = false;
                System.out.println("设备未发现蓝牙设备！");
            }

        } catch (Exception e) {
            System.out.println("判断蓝牙模块异常" + e.getMessage());
        }

        return flag;
    }

    /**
     * 打开蓝牙
     *
     * @return
     */



   /* private boolean enableBluetooth() {
        init();
        System.out.println("SDK:"+Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        100);
            }
        }

        if (mBluetoothAdapter.isEnabled()) {
            return true;
        }

//        mBluetoothAdapter.enable();

        Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enabler, 1);

        return mBluetoothAdapter.isEnabled();
    }*/





    private boolean enableBluetooth()
    {

        init();



        System.out.println("SDK:"+Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        100);
            }
        }



        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter != null)
        {
            if(mBluetoothAdapter.isEnabled())
                return true;
            mBluetoothAdapter.enable();
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            if(!mBluetoothAdapter.isEnabled())
            {
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        }
        else
        {
            Log.d("HPRTSDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }


    /**
     * 判断是否打开蓝牙
     *
     * @return
     */
    private boolean isEnableBluetooth() {
        init();
        return mBluetoothAdapter.isEnabled();
    }


    /**
     * 扫描获取蓝牙设备列表
     *
     * @return
     */
    private boolean scanBT() {
        init();
        boolean flag = false;

        System.out.println("**********************************BT SCAN*******************************");


        try {
            if (mBluetoothAdapter.isDiscovering()) {
                System.out.println("====================================================================");
                mBluetoothAdapter.cancelDiscovery();
            }
            Thread.sleep(500);

            mBluetoothAdapter.startDiscovery();
            flag = true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return flag;

    }


    private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothSocket socket;


    /**
     * 扫描广播接收类
     * Created by zqf on 2018/7/6.
     */

    private BroadcastReceiver createScanBlueReceiver(final EventChannel.EventSink eventSink) {


        return new BroadcastReceiver() {
            final String TAG = "RCV";



            //广播接收器，当远程蓝牙设备被发现时，回调函数onReceiver()会被执行
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.d(TAG, "action:" + action);
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//                if(device.getBluetoothClass().getMajorDeviceClass()==1536){


                switch (action) {
                    case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                        eventSink.success("开始扫描...");
                        break;
                    case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                        eventSink.success("结束扫描..");
                        break;
                    case BluetoothDevice.ACTION_FOUND:

                        if (device.getName() != null) {
                            
                            if (1536 == device.getBluetoothClass().getMajorDeviceClass() ){
                                eventSink.success(device.getName() + "||" + device.getAddress());
                            }



                        }

                        break;
                    case BluetoothDevice.ACTION_ACL_CONNECTED:

                        if (device.getName() != null) {

                            eventSink.success(device.getName() + "||" + device.getAddress()+"||CONNECTED");

                        }

                        break;

                    case BluetoothDevice.ACTION_ACL_DISCONNECTED:

                        if (device.getName() != null) {
                            if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                                eventSink.success(device.getName() + "||" + device.getAddress()+"||DISCAONNECTED");
                            }else{
                                eventSink.success(device.getName() + "||" + device.getAddress());

                            }
                        }

                        break;
                    case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                        System.out.println("===========BT 连接 STATE  变化=================");

                        if (device.getName() != null) {
                            if (device.getBondState()==BluetoothDevice.BOND_BONDED){
                                eventSink.success(device.getName() + "||" + device.getAddress()+"||BOND_BONDED");
                            }else if (device.getBondState()==BluetoothDevice.BOND_BONDING){
                                eventSink.success(device.getName() + "||" + device.getAddress()+"||BOND_BONDING");
                            }else if (device.getBondState()==BluetoothDevice.BOND_NONE){
                                eventSink.success(device.getName() + "||" + device.getAddress()+"||BOND_NONE");
                            }
                        }

                        break;

                }
                }
//            }
        };
    }


    /**
     * 取消扫描
     * @return
     */
    private boolean cancelDiscoveryBT() {

        boolean flag = false;
        if (mBluetoothManager  == null){
            return  true;
        }

        try {
            if (mBluetoothAdapter.isDiscovering()){
                flag = mBluetoothAdapter.cancelDiscovery();
            }


        } catch (Exception e) {

        }
        return flag;

    }


    /**
     * 关闭蓝牙
     *
     * @return
     */
    private boolean disConnnectBT() {
        init();
        boolean flag = false;
        if (mBluetoothManager  == null){
            return  true;
        }



        try {
            if (mBluetoothAdapter.isDiscovering()){
                mBluetoothAdapter.cancelDiscovery();
            }
            flag = mBluetoothAdapter.disable();
        } catch (Exception e) {

        }
        return flag;

    }

    private boolean connectBT(final String address) {
        init();
        boolean flag = false;


        if(HPRTPrinter!=null)
        {
            try {
                HPRTPrinterHelper.PortClose();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }





        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

        System.out.println("ADRESS:"+address);

        try {
            int sdk = Build.VERSION.SDK_INT;
            if (sdk >= 10) {
                System.out.println("=============10 more====================");
                socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
            } else {
                System.out.println("=============10 less====================");
                socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
            }


            thread = new Thread(new Runnable() {

                @Override
                public void run() {

//                    new HPRTPrinterHelper(thisCon,HPRTPrinterHelper.PRINT_NAME_A300);
                    int i = 0;
                    try {
                        i = HPRTPrinterHelper.PortOpen("Bluetooth," + address);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    System.out.println("连接状态" + i);


                }
            });

            thread.start();


            flag = true;



        } catch (Exception e) {
            System.out.println("sss" + e.getMessage());
            e.printStackTrace();
        }





        return flag;

    }



    private boolean isConnect(String address){
        boolean flag = false;

        init();
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device != null && device.getBondState()==BluetoothDevice.BOND_BONDED){
            flag = true;

        }

        return flag;

    }


    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    /**
     * 打印
     *
     * @param pum  打印内容
     * @param type 打印类型 1：全部 2：配件商：3:修理厂 4：司机 5：货物 6：货物外
     */
    private boolean printOrder(Map<String, String> pum, int type) {
//        init();
        System.out.println("====================================================================");
        System.out.println(pum);
        System.out.println(type);
        System.out.println("====================================================================");
        if (pum == null) {
            pum = new HashMap<>();
        }
        boolean flag = true;

        try {


            switch (type) {
                case 1:
                    printSender(pum);
                    printGoods(pum);
                    printSender(pum);
                    printDriver(pum);
                    break;
                case 2:
                    printSender(pum);
                    break;
                case 3:
                    printSender(pum);
                    break;
                case 4:
                    printDriver(pum);
                    break;
                case 5:
                    printGoods(pum);
                    break;
                case 6:
                    printSender(pum);
                    printSender(pum);
                    printDriver(pum);
                    break;
                default:
                    System.out.println("不打印");
                    break;
            }


        } catch (Exception e) {
            Log.e("配件商或修理厂打印异常", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
            flag = false;

        }

        return flag;

    }


    private void printSender(Map<String, String> pum) throws Exception {
        Set<String> keySet = pum.keySet();
        Iterator<String> iterator = keySet.iterator();
        InputStream afis = this.getResources().getAssets().open("sender.txt");//打印模版放在assets文件夹里
        String path = new String(InputStreamToByte(afis), "utf-8");//打印模版以utf-8无bom格式保存
        while (iterator.hasNext()) {
            String string = (String) iterator.next();
            path = path.replace(string, pum.get(string));
        }



        HPRTPrinterHelper.printText(path);
        HPRTPrinterHelper.Form();
        HPRTPrinterHelper.Print();

    }

    private void printGoods(Map<String, String> pum) throws Exception {
        System.out.println(pum.get("[goodsQuantity]"));


         int num = Integer.parseInt(pum.get("[goodsQuantity]"));

         for(int i=0; i<num ;i++){

             String cno = i+1+"/"+num;

             pum.put("[currentGoodNumber]",cno);

             Set<String> keySet = pum.keySet();
             Iterator<String> iterator = keySet.iterator();
             InputStream afis = this.getResources().getAssets().open("goods.txt");//打印模版放在assets文件夹里
             String path = new String(InputStreamToByte(afis), "utf-8");//打印模版以utf-8无bom格式保存
             while (iterator.hasNext()) {
                 String string = (String) iterator.next();
                 path = path.replace(string, pum.get(string));
             }

             HPRTPrinterHelper.printText(path);
             HPRTPrinterHelper.Form();
             HPRTPrinterHelper.Print();
            
         } 




    }

    private void printDriver(Map<String, String> pum) throws Exception {


        Set<String> keySet = pum.keySet();
        Iterator<String> iterator = keySet.iterator();
        InputStream afis = this.getResources().getAssets().open("driver.txt");//打印模版放在assets文件夹里
        String path = new String(InputStreamToByte(afis), "utf-8");//打印模版以utf-8无bom格式保存
        while (iterator.hasNext()) {
            String string = (String) iterator.next();
            path = path.replace(string, pum.get(string));
        }

        init();
        // 得到当前的一个已经配对的蓝牙设备
//        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//        if (pairedDevices.size() > 0){
//
//            for (BluetoothDevice device : pairedDevices) //遍历
//            {
//                connectBT(device.getAddress());
//            }
//
//
//        }



        HPRTPrinterHelper.printText(path);
        HPRTPrinterHelper.Form();
        HPRTPrinterHelper.Print();


    }






}
