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

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.content.pm.PackageManager;

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;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    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("scanBT")) {
            boolean isScan = scanBT();

            if (isScan) {
              result.success(isScan);
            } else {
              result.error("UNAVAILABLE", "蓝牙扫描出错", null);
            }
          } else if (call.method.equals("connectBT")) {
            boolean isConn = connnectBT((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("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);


          registerReceiver(scanBlueReceiver, filter1);
          registerReceiver(scanBlueReceiver, filter2);
          registerReceiver(scanBlueReceiver, filter3);

          registerReceiver(scanBlueReceiver, new IntentFilter(Intent.ACTION_DATE_CHANGED));

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


        }

        @Override
        public void onCancel(Object o) {

          unregisterReceiver(scanBlueReceiver);
          scanBlueReceiver = null;

        }
      }

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

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

    return flag;
  }

  /**
   * 判断师傅打开蓝牙
   *
   * @return
   */
  private boolean isEnableBluetooth() {
        System.out.println("**********************************BT*******************************");
       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();

        return mBluetoothAdapter.isEnabled();
    }


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

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

    try {
      if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
      }
      System.out.println("**********************************BT1111 SCAN*******************************");

      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);
        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) {
              eventSink.success(device.getName() + "||" + device.getAddress());
            }

            

            break;
        }
      }
    };
  }


  /**
   * 关闭蓝牙
   * @return
   */
  private boolean disConnnectBT() {
    boolean flag = false;

    try {
      flag = HPRTPrinterHelper.PortClose();
    } catch (Exception e) {

    }
    return flag;

  }

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


    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

    try {
      int sdk = Build.VERSION.SDK_INT;
      if (sdk >= 10) {
        socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
      } else {
        socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
      }

      int i = HPRTPrinterHelper.PortOpen("Bluetooth," + device.getAddress());
      System.out.println("连接状态" + i);
      flag = true;



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



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

    //        pum.put("[logisticsNo]", "1111232321321");
    //        pum.put("[createTime]", "2019");
    //        pum.put("[sendStationName]", "五方");
    //        pum.put("[dealerCode]", "WF1112");
    //        pum.put("[dealerName]", "五方配件商");
    //        pum.put("[dealerTel]", "13439395969");
    //        pum.put("[repairName]", "NB修理厂");
    //        pum.put("[repairTel]", "13826514987");
    //        pum.put("[endStationName]", "丰台");
    //        pum.put("[goodsLineCode]", "F12");
    //        pum.put("[goodsLine]", "马驹桥");
    //        pum.put("[repairAddress]", "NB修车厂地址）");
    //        pum.put("[goodsQuantity]", "1");
    //        pum.put("[goodsInsurance]", "12");
    //        pum.put("[goodsFlatCost]", "14");
    //        pum.put("[goodsPaymentMethod]", "200");
    //        pum.put("[goodsAgencyFund]", "18");
    //        pum.put("[dealerBankAccount]", "1234512312YH");
    //        pum.put("[goodsRemark]", "帽子");
    //        pum.put("[realName]", "xg");
    //        pum.put("[currentTime]", "21111yyymmm");


    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 {
    //        pum.put("[logisticsNo]", "1111232321321");
    //        pum.put("[createTime]", "2019");
    //        pum.put("[sendStationName]", "五方");
    //        pum.put("[dealerCode]", "WF1112");
    //        pum.put("[dealerName]", "五方配件商");
    //        pum.put("[dealerTel]", "13439395969");
    //        pum.put("[repairName]", "NB修理厂");
    //        pum.put("[repairTel]", "13826514987");
    //        pum.put("[endStationName]", "丰台");
    //        pum.put("[goodsLineCode]", "F12");
    //        pum.put("[goodsLine]", "马驹桥");
    //        pum.put("[repairAddress]", "NB修车厂地址）");
    //        pum.put("[goodsQuantity]", "1");
    //        pum.put("[goodsInsurance]", "12");
    //        pum.put("[goodsFlatCost]", "14");
    //        pum.put("[goodsPaymentMethod]", "200");
    //        pum.put("[goodsAgencyFund]", "18");
    //        pum.put("[dealerBankAccount]", "1234512312YH");
    //        pum.put("[goodsRemark]", "帽子");
    //        pum.put("[realName]", "xg");
    //        pum.put("[currentTime]", "21111yyymmm");


    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 {



    //        pum.put("[logisticsNo]", "1111232321321");
    //        pum.put("[createTime]", "2019");
    //        pum.put("[sendStationName]", "五方");
    //        pum.put("[dealerCode]", "WF1112");
    //        pum.put("[dealerName]", "五方配件商");
    //        pum.put("[dealerTel]", "13439395969");
    //        pum.put("[repairName]", "NB修理厂");
    //        pum.put("[repairTel]", "13826514987");
    //        pum.put("[endStationName]", "丰台");
    //        pum.put("[goodsLineCode]", "F12");
    //        pum.put("[goodsLine]", "马驹桥");
    //        pum.put("[repairAddress]", "NB修车厂地址）");
    //        pum.put("[goodsQuantity]", "1");
    //        pum.put("[goodsInsurance]", "12");
    //        pum.put("[goodsFlatCost]", "14");
    //        pum.put("[goodsPaymentMethod]", "200");
    //        pum.put("[goodsAgencyFund]", "18");
    //        pum.put("[dealerBankAccount]", "1234512312YH");
    //        pum.put("[goodsRemark]", "帽子");
    //        pum.put("[realName]", "xg");
    //        pum.put("[currentTime]", "21111yyymmm");


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

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


  }


  private void ZTexpress() {
    try {
      Map < String, String > pum = new HashMap < String, String > ();
      pum.put("[logisticsNo]", "1111232321321");
      pum.put("[createTime]", "2019");
      pum.put("[sendStationName]", "五方");
      pum.put("[dealerCode]", "WF1112");
      pum.put("[dealerName]", "五方配件商");
      pum.put("[dealerTel]", "13439395969");
      pum.put("[repairName]", "NB修理厂");
      pum.put("[repairTel]", "13826514987");
      pum.put("[endStationName]", "丰台");
      pum.put("[goodsLineCode]", "F12");
      pum.put("[goodsLine]", "马驹桥");
      pum.put("[repairAddress]", "NB修车厂地址）");
      pum.put("[goodsQuantity]", "1");
      pum.put("[goodsInsurance]", "12");
      pum.put("[goodsFlatCost]", "14");
      pum.put("[goodsPaymentMethod]", "200");
      pum.put("[goodsAgencyFund]", "18");
      pum.put("[dealerBankAccount]", "1234512312YH");
      pum.put("[goodsRemark]", "帽子");
      pum.put("[realName]", "xg");
      pum.put("[currentTime]", "21111yyymmm");
      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();

    } catch (Exception e) {
      Log.e("打印异常", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
    }
  }


}
