package com.siwei.recyclebox.deviceUtils;

import android.hardware.usb.UsbManager;
import android.util.Log;

import com.aliyuncs.exceptions.ClientException;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.siwei.recyclebox.ui.main.MainViewModel;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.SPUtils;

public class WeightDevice extends BaseDeviceEntity {

    private static final String TAG = "WeightDevice";

    public WeightDevice(UsbManager usbManager, UsbSerialDriver driver) {
        super(usbManager , driver);
    }

    /**
     * 读取称重器的读数
     * return weight 单位：g
     */
    public synchronized Integer readIsWeight(){
        try {
//            SPUtils.getInstance().put("RunningState",0);//1F 03 00 2A 00 01 A6 7C
            port.write(new byte[]{0x1F, 0x03, 0x00, 0x2A,0x00, 0x01, (byte) 0xA6, 0x7C},150);//称重器读取数值的请求
            byte[] response = new byte[7];
            port.read(response,200);
            Log.i(TAG,"返回称重"+ByteUtil.bytesToString(response));
            if(response[1]==3) {
                byte[] weightBytes = new byte[4];
                weightBytes[2] = response[3];
                weightBytes[3] = response[4];
                int weightInt = ByteUtil.bytes2Int(weightBytes);
                weightInt=weightInt*5*2;
                System.out.println("称重读数："+weightInt);
                if(weightInt>=327670){
                    weightInt=0;
                }
                return (int) weightInt;
            }else {
                return 1;
            }
        }catch ( Exception e ){
            e.printStackTrace();
            return 1;
        }

    }
    public synchronized Integer readWeight(){
        try {
//            SPUtils.getInstance().put("RunningState","0");//1F 03 00 2A 00 01 A6 7C
            port.write(new byte[]{0x1F, 0x03, 0x00, 0x2A,0x00, 0x01, (byte) 0xA6, 0x7C},150);//称重器读取数值的请求
//            port.write(new byte[]{(byte) 0xAA, (byte) 0xBB,0x0C ,0x01 ,0x55 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD},150);//称重器读取数值的请求
//            port.write(new byte[]{(byte) 0xAA, (byte) 0xBB,0x0C ,0x02 ,0x55 , (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xCC, (byte) 0xDD},150);//超声波读取数值的请求
//            Thread.sleep(100);
            byte[] response = new byte[7];
            port.read(response,200);
            Log.i(TAG,"返回称重"+ByteUtil.bytesToString(response));
//            byte[] responseCache = new byte[7];
//            long curTimeMiles = System.currentTimeMillis();
//            int readLengthCache = 0;
//            while (System.currentTimeMillis()-curTimeMiles<200){
//                int len = port.read(response,10);
//                System.out.println("读取到："+ByteUtil.bytesToString(response)+"  len:"+len);
//                if(len>0){
//                    if(readLengthCache == 0 && response[0] != 0x1f){//一个包的起始为0x22
//                        continue;
//                    }
//                    for(int i = 0 ;i<len;i++){
//                        if(readLengthCache>=7)
//                            break;
//                        responseCache[readLengthCache] = response[i];
//                        readLengthCache++;
//                    }
//                }
//            }
//            if(readLengthCache == 0) {
//                return 1;
//            }
//            if(readLengthCache >= 7 && responseCache[0] == 0x1f && responseCache[1] == 0x03){
//                byte[] weightBytes = new byte[4];
//                weightBytes[2] = responseCache[3];
//                weightBytes[3] = responseCache[4];
//                int weightInt = ByteUtil.bytes2Int(weightBytes);
//                weightInt=weightInt*5*2;
//                System.out.println("称重读数："+weightInt);
//                if(weightInt>=327670){
//                    weightInt=0;
//                }
//                return (int) weightInt;
//            }else{
//                SPUtils.getInstance().put("RunningState","4");
//                try {
//                    WarnActivity.SendSmsResponse("readWeight称重故障");
//                } catch (ClientException ex) {
//                    ex.printStackTrace();
//                }
//            }

            if(response[1]==3) {
                long curTimeMiles = System.currentTimeMillis();
                int num=0,a=0;
                while (System.currentTimeMillis()-curTimeMiles<200){
                    port.read(response,10);
                    byte[] weightBytes = new byte[4];
                    weightBytes[2] = response[3];
                    weightBytes[3] = response[4];
                    int weightInt = ByteUtil.bytes2Int(weightBytes);
//                    weightInt=weightInt*5*2;
                    num += (weightInt * 10);
//                    num += weightInt;
                    a++;
                    Log.i("while","********"+a);
                }
                Log.i("num",num+"****"+a+"");
                byte[] weightBytes = new byte[4];
                weightBytes[2] = response[3];
                weightBytes[3] = response[4];
                int weightInt = ByteUtil.bytes2Int(weightBytes);
                weightInt=weightInt*10;
                System.out.println("称重读数："+weightInt);
                int weightNumber=num/a++;
                if(weightInt>=327670){
                    weightNumber=0;
                }
                return (int) weightNumber;
            }else {
                Log.i("返回称重","错误");
                SPUtils.getInstance().put("RunningState",1);
                MainViewModel.SendSmsResponse("readWeight称重失灵");
                return 1;
            }
            /*int readLen = port.read(response,200);
            System.out.println("readweight len:"+readLen+"  bytes;"+ByteUtil.bytesToString(response));
            */
//            return 1;
//
        }catch ( Exception e ){
            e.printStackTrace();
            SPUtils.getInstance().put("RunningState",1);
            MainViewModel.SendSmsResponse("readWeight称重设备未检测到");

            Log.e(TAG,"读取称重器读数错误",e);
            return 1;
        }

    }
    /**
     * 读数清零
     */
    public synchronized void weightClear(){
        byte[] cleanOrderBytes = new byte[]{0x1F,0x06 ,0x00 ,0x24,0x00 ,0x00, (byte) 0xCA,0x7F};
        System.out.println();
        try {
            port.write(cleanOrderBytes,150);
            byte[] response=new byte[8];
            port.read(response,200);
            Log.i(TAG,"称重器读数清零！！！！！:"+ByteUtil.bytesToString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 空载
     * */
    public synchronized void zeroCalibration(){
        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x08 ,0x00 ,0x02 ,0x04 ,0x00 ,0x00 ,0x00 ,0x00 , (byte) 0x92,0x21 };
        try {
            port.write(cleanOrderBytes,150);
            byte[] response=new byte[8];
            port.read(response,200);
            Log.i(TAG,"空载:"+ByteUtil.bytesToString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
     * 设置分度值
     * */
    public synchronized void setScale(){//1F 06 00 04 00 01 0A 75              02  4A 74

//        byte[] cleanOrderBytes = new byte[]{0x1F, 0x06 ,0x00 ,0x04 ,0x00 ,0x02 ,0x0A ,0x75};
        byte[] cleanOrderBytes = new byte[]{0x1F, 0x06 ,0x00 ,0x04 ,0x00 ,0x02 ,0x4A ,0x74};

        try {
            port.write(cleanOrderBytes,150);
            byte[] response=new byte[8];
            port.read(response,200);
            Log.i(TAG,"设置分度值2:"+ByteUtil.bytesToString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
     * 量程设定
     * */
    public synchronized void weightSet(){//1F 10 00 00 00 02 04 27 10 00 00 98 F6
        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x00 ,0x00 ,0x02 ,0x04 , 0x27, 0x10,0x00 ,0x00 , (byte) 0x98, (byte) 0xF6};
//        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x00 ,0x00 ,0x02 ,0x04 , 0x4E, 0x20,0x00 ,0x00 , (byte) 0x98, (byte) 0xF6};

        try {
            port.write(cleanOrderBytes,150);
            byte[] response=new byte[8];
            port.read(response,200);
            Log.i(TAG,"l0000量程设定:"+ByteUtil.bytesToString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
     * 砝码校准
     * */
    public synchronized void weightCalibration(){
        //1F 10 00 10 00 02 04 03 E8 00 00 12 FB
        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x03 , (byte) 0xE8,0x00 ,0x00, 0x12, (byte) 0xFB};
//        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x27 , 0x10,0x00 ,0x00, (byte) 0x96, (byte) 0xE4};

//        byte[] cleanOrderBytes = new byte[]{0x1F ,0x10 ,0x00 ,0x10 ,0x00 ,0x02 ,0x04 ,0x27 ,0x10 ,0x00 ,0x00, (byte) 0x96, (byte) 0xE4};
        try {
            port.write(cleanOrderBytes,150);
            byte[] response=new byte[8];
            port.read(response,200);
            Log.i(TAG,"砝码校准10kg:"+ByteUtil.bytesToString(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    private SingleLiveEvent<byte[]> requestFilePermissions = new SingleLiveEvent<>();
    private short latestWeight = 0;

    @Override
    public void connect(UsbManager usbManager) throws IOException {
        super.connect(usbManager);
        System.out.println("connect  readWeight:");
//        weightClear();
    }

    @Override
    void onDataReceived(byte[] response) {
        byte[] weightBytes = new byte[2];
        weightBytes[0] = response[3];
        weightBytes[1] = response[4];
        latestWeight = ByteUtil.byte2short(weightBytes);
    }

    java.util.Observer observer = new java.util.Observer() {
        /**
         * This method is called whenever the observed object is changed. An
         * application calls an <tt>Observable</tt> object's
         * <code>notifyObservers</code> method to have all the object's
         * observers notified of the change.
         *
         * @param observable   the observable object.
         * @param arg an argument passed to the <code>notifyObservers</code>
         */
        @Override
        public void update(java.util.Observable observable, Object arg) {

        }
    };


    /**
     * 串口的连接参数：
     * baudRate: 波特率
     * dataBits: 数据位 一般为8
     * stopBits: 停止位 一般为1
     * parity: 奇偶校验 UsbSerialPort.PARITY_ODD、UsbSerialPort.PARITY_EVEN、UsbSerialPort.PARITY_NONE
     */
    @Override
    int getBaudRate() {
        return 19200;
//        return 115200;
    }

    @Override
    int getDataBits() {
        return UsbSerialPort.DATABITS_8;
    }

    @Override
    int getStopBits() {
        return UsbSerialPort.STOPBITS_1;
    }

    @Override
    int getParity() {
        return UsbSerialPort.PARITY_EVEN;
//        return UsbSerialPort.PARITY_NONE;
    }

    @Override
    int getVendorId() {
        return 6790;
    }

}
